repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/partials/bulk-delete.blade.php | resources/views/partials/bulk-delete.blade.php | <a class="btn btn-danger" id="bulk_delete_btn"><i class="voyager-trash"></i> <span>{{ __('voyager::generic.bulk_delete') }}</span></a>
{{-- Bulk delete modal --}}
<div class="modal modal-danger fade" tabindex="-1" id="bulk_delete_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title">
<i class="voyager-trash"></i> {{ __('voyager::generic.are_you_sure_delete') }} <span id="bulk_delete_count"></span> <span id="bulk_delete_display_name"></span>?
</h4>
</div>
<div class="modal-body" id="bulk_delete_modal_body">
</div>
<div class="modal-footer">
<form action="{{ route('voyager.'.$dataType->slug.'.index') }}/0" id="bulk_delete_form" method="POST">
{{ method_field("DELETE") }}
{{ csrf_field() }}
<input type="hidden" name="ids" id="bulk_delete_input" value="">
<input type="submit" class="btn btn-danger pull-right delete-confirm"
value="{{ __('voyager::generic.bulk_delete_confirm') }} {{ strtolower($dataType->getTranslatedAttribute('display_name_plural')) }}">
</form>
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">
{{ __('voyager::generic.cancel') }}
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
window.onload = function () {
// Bulk delete selectors
var $bulkDeleteBtn = $('#bulk_delete_btn');
var $bulkDeleteModal = $('#bulk_delete_modal');
var $bulkDeleteCount = $('#bulk_delete_count');
var $bulkDeleteDisplayName = $('#bulk_delete_display_name');
var $bulkDeleteInput = $('#bulk_delete_input');
// Reposition modal to prevent z-index issues
$bulkDeleteModal.appendTo('body');
// Bulk delete listener
$bulkDeleteBtn.click(function () {
var ids = [];
var $checkedBoxes = $('#dataTable input[type=checkbox]:checked').not('.select_all');
var count = $checkedBoxes.length;
if (count) {
// Reset input value
$bulkDeleteInput.val('');
// Deletion info
var displayName = count > 1 ? '{{ $dataType->getTranslatedAttribute('display_name_plural') }}' : '{{ $dataType->getTranslatedAttribute('display_name_singular') }}';
displayName = displayName.toLowerCase();
$bulkDeleteCount.html(count);
$bulkDeleteDisplayName.html(displayName);
// Gather IDs
$.each($checkedBoxes, function () {
var value = $(this).val();
ids.push(value);
})
// Set input value
$bulkDeleteInput.val(ids);
// Show modal
$bulkDeleteModal.modal('show');
} else {
// No row selected
toastr.warning('{{ __('voyager::generic.bulk_delete_nothing') }}');
}
});
}
</script>
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/partials/coordinates.blade.php | resources/views/partials/coordinates.blade.php | <style>
#map {
height: 400px;
width: 100%;
}
</style>
<script type="application/javascript">
function initMap() {
@forelse($dataTypeContent->getCoordinates() as $point)
var center = {lat: {{ $point['lat'] }}, lng: {{ $point['lng'] }}};
@empty
var center = {lat: {{ config('voyager.googlemaps.center.lat') }}, lng: {{ config('voyager.googlemaps.center.lng') }}};
@endforelse
var map = new google.maps.Map(document.getElementById('map'), {
zoom: {{ config('voyager.googlemaps.zoom') }},
center: center
});
var markers = [];
@foreach($dataTypeContent->getCoordinates() as $point)
var marker = new google.maps.Marker({
position: {lat: {{ $point['lat'] }}, lng: {{ $point['lng'] }}},
map: map
});
markers.push(marker);
@endforeach
}
</script>
<div id="map"/>
<script async defer src="https://maps.googleapis.com/maps/api/js?key={{ config('voyager.googlemaps.key') }}&callback=initMap"></script> | php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/partials/coordinates-static-image.blade.php | resources/views/partials/coordinates-static-image.blade.php | <img src="https://maps.googleapis.com/maps/api/staticmap?zoom={{ config('voyager.googlemaps.zoom') }}&size=400x100&maptype=roadmap&@foreach($data->getCoordinates() as $point)markers=color:red%7C{{ $point['lat'] }},{{ $point['lng'] }}¢er={{ $point['lat'] }},{{ $point['lng'] }}@endforeach&key={{ config('voyager.googlemaps.key') }}"/> | php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/dashboard/navbar.blade.php | resources/views/dashboard/navbar.blade.php | <nav class="navbar navbar-default navbar-fixed-top navbar-top">
<div class="container-fluid">
<div class="navbar-header">
<button class="hamburger btn-link">
<span class="hamburger-inner"></span>
</button>
@section('breadcrumbs')
<ol class="breadcrumb hidden-xs">
@php
$segments = array_filter(explode('/', str_replace(route('voyager.dashboard'), '', Request::url())));
$url = route('voyager.dashboard');
@endphp
@if(count($segments) == 0)
<li class="active"><i class="voyager-boat"></i> {{ __('voyager::generic.dashboard') }}</li>
@else
<li class="active">
<a href="{{ route('voyager.dashboard')}}"><i class="voyager-boat"></i> {{ __('voyager::generic.dashboard') }}</a>
</li>
@foreach ($segments as $segment)
@php
$url .= '/'.$segment;
@endphp
@if ($loop->last)
<li>{{ ucfirst(urldecode($segment)) }}</li>
@else
<li>
<a href="{{ $url }}">{{ ucfirst(urldecode($segment)) }}</a>
</li>
@endif
@endforeach
@endif
</ol>
@show
</div>
<ul class="nav navbar-nav @if (__('voyager::generic.is_rtl') == 'true') navbar-left @else navbar-right @endif">
<li class="dropdown profile">
<a href="#" class="dropdown-toggle text-right" data-toggle="dropdown" role="button"
aria-expanded="false"><img src="{{ $user_avatar }}" class="profile-img"> <span
class="caret"></span></a>
<ul class="dropdown-menu dropdown-menu-animated">
<li class="profile-img">
<img src="{{ $user_avatar }}" class="profile-img">
<div class="profile-body">
<h5>{{ Auth::user()->name }}</h5>
<h6>{{ Auth::user()->email }}</h6>
</div>
</li>
<li class="divider"></li>
<?php $nav_items = config('voyager.dashboard.navbar_items'); ?>
@if(is_array($nav_items) && !empty($nav_items))
@foreach($nav_items as $name => $item)
<li {!! isset($item['classes']) && !empty($item['classes']) ? 'class="'.$item['classes'].'"' : '' !!}>
@if(isset($item['route']) && $item['route'] == 'voyager.logout')
<form action="{{ route('voyager.logout') }}" method="POST">
{{ csrf_field() }}
<button type="submit" class="btn btn-danger btn-block">
@if(isset($item['icon_class']) && !empty($item['icon_class']))
<i class="{!! $item['icon_class'] !!}"></i>
@endif
{{__($name)}}
</button>
</form>
@else
<a href="{{ isset($item['route']) && Route::has($item['route']) ? route($item['route']) : (isset($item['route']) ? $item['route'] : '#') }}" {!! isset($item['target_blank']) && $item['target_blank'] ? 'target="_blank"' : '' !!}>
@if(isset($item['icon_class']) && !empty($item['icon_class']))
<i class="{!! $item['icon_class'] !!}"></i>
@endif
{{__($name)}}
</a>
@endif
</li>
@endforeach
@endif
</ul>
</li>
</ul>
</div>
</nav>
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/dashboard/sidebar.blade.php | resources/views/dashboard/sidebar.blade.php | <div class="side-menu sidebar-inverse">
<nav class="navbar navbar-default" role="navigation">
<div class="side-menu-container">
<div class="navbar-header">
<a class="navbar-brand" href="{{ route('voyager.dashboard') }}">
<div class="logo-icon-container">
<?php $admin_logo_img = Voyager::setting('admin.icon_image', ''); ?>
@if($admin_logo_img == '')
<img src="{{ voyager_asset('images/logo-icon-light.png') }}" alt="Logo Icon">
@else
<img src="{{ Voyager::image($admin_logo_img) }}" alt="Logo Icon">
@endif
</div>
<div class="title">{{Voyager::setting('admin.title', 'VOYAGER')}}</div>
</a>
</div><!-- .navbar-header -->
<div class="panel widget center bgimage"
style="background-image:url({{ Voyager::image( Voyager::setting('admin.bg_image'), voyager_asset('images/bg.jpg') ) }}); background-size: cover; background-position: 0px;">
<div class="dimmer"></div>
<div class="panel-content">
<img src="{{ $user_avatar }}" class="avatar" alt="{{ Auth::user()->name }} avatar">
<h4>{{ ucwords(Auth::user()->name) }}</h4>
<p>{{ Auth::user()->email }}</p>
<a href="{{ route('voyager.profile') }}" class="btn btn-primary">{{ __('voyager::generic.profile') }}</a>
<div style="clear:both"></div>
</div>
</div>
</div>
<div id="adminmenu">
<admin-menu :items="{{ menu('admin', '_json') }}"></admin-menu>
</div>
</nav>
</div>
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/users/edit-add.blade.php | resources/views/users/edit-add.blade.php | @extends('voyager::master')
@section('page_title', __('voyager::generic.'.(isset($dataTypeContent->id) ? 'edit' : 'add')).' '.$dataType->getTranslatedAttribute('display_name_singular'))
@section('css')
<meta name="csrf-token" content="{{ csrf_token() }}">
@stop
@section('page_header')
<h1 class="page-title">
<i class="{{ $dataType->icon }}"></i>
{{ __('voyager::generic.'.(isset($dataTypeContent->id) ? 'edit' : 'add')).' '.$dataType->getTranslatedAttribute('display_name_singular') }}
</h1>
@stop
@section('content')
<div class="page-content container-fluid">
<form class="form-edit-add" role="form"
action="@if(!is_null($dataTypeContent->getKey())){{ route('voyager.'.$dataType->slug.'.update', $dataTypeContent->getKey()) }}@else{{ route('voyager.'.$dataType->slug.'.store') }}@endif"
method="POST" enctype="multipart/form-data" autocomplete="off">
<!-- PUT Method if we are editing -->
@if(isset($dataTypeContent->id))
{{ method_field("PUT") }}
@endif
{{ csrf_field() }}
<div class="row">
<div class="col-md-8">
<div class="panel panel-bordered">
{{-- <div class="panel"> --}}
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="panel-body">
<div class="form-group">
<label for="name">{{ __('voyager::generic.name') }}</label>
<input type="text" class="form-control" id="name" name="name" placeholder="{{ __('voyager::generic.name') }}"
value="{{ old('name', $dataTypeContent->name ?? '') }}">
</div>
<div class="form-group">
<label for="email">{{ __('voyager::generic.email') }}</label>
<input type="email" class="form-control" id="email" name="email" placeholder="{{ __('voyager::generic.email') }}"
value="{{ old('email', $dataTypeContent->email ?? '') }}">
</div>
<div class="form-group">
<label for="password">{{ __('voyager::generic.password') }}</label>
@if(isset($dataTypeContent->password))
<br>
<small>{{ __('voyager::profile.password_hint') }}</small>
@endif
<input type="password" class="form-control" id="password" name="password" value="" autocomplete="new-password">
</div>
@can('editRoles', $dataTypeContent)
<div class="form-group">
<label for="default_role">{{ __('voyager::profile.role_default') }}</label>
@php
$dataTypeRows = $dataType->{(isset($dataTypeContent->id) ? 'editRows' : 'addRows' )};
$row = $dataTypeRows->where('field', 'user_belongsto_role_relationship')->first();
$options = $row->details;
@endphp
@include('voyager::formfields.relationship')
</div>
<div class="form-group">
<label for="additional_roles">{{ __('voyager::profile.roles_additional') }}</label>
@php
$row = $dataTypeRows->where('field', 'user_belongstomany_role_relationship')->first();
$options = $row->details;
@endphp
@include('voyager::formfields.relationship')
</div>
@endcan
@php
if (isset($dataTypeContent->locale)) {
$selected_locale = $dataTypeContent->locale;
} else {
$selected_locale = config('app.locale', 'en');
}
@endphp
<div class="form-group">
<label for="locale">{{ __('voyager::generic.locale') }}</label>
<select class="form-control select2" id="locale" name="locale">
@foreach (Voyager::getLocales() as $locale)
<option value="{{ $locale }}"
{{ ($locale == $selected_locale ? 'selected' : '') }}>{{ $locale }}</option>
@endforeach
</select>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel panel-bordered panel-warning">
<div class="panel-body">
<div class="form-group">
@if(isset($dataTypeContent->avatar))
<img src="{{ filter_var($dataTypeContent->avatar, FILTER_VALIDATE_URL) ? $dataTypeContent->avatar : Voyager::image( $dataTypeContent->avatar ) }}" style="width:200px; height:auto; clear:both; display:block; padding:2px; border:1px solid #ddd; margin-bottom:10px;" />
@endif
<input type="file" data-name="avatar" name="avatar">
</div>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary pull-right save">
{{ __('voyager::generic.save') }}
</button>
</form>
<div style="display:none">
<input type="hidden" id="upload_url" value="{{ route('voyager.upload') }}">
<input type="hidden" id="upload_type_slug" value="{{ $dataType->slug }}">
</div>
</div>
@stop
@section('javascript')
<script>
$('document').ready(function () {
$('.toggleswitch').bootstrapToggle();
});
</script>
@stop
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/media/index.blade.php | resources/views/media/index.blade.php | @extends('voyager::master')
@section('page_title', __('voyager::generic.media'))
@section('content')
<div class="page-content container-fluid">
@include('voyager::alerts')
<div class="row">
<div class="col-md-12">
<div class="admin-section-title">
<h3><i class="voyager-images"></i> {{ __('voyager::generic.media') }}</h3>
</div>
<div class="clear"></div>
<div id="filemanager">
<media-manager
base-path="{{ config('voyager.media.path', '/') }}"
:show-folders="{{ config('voyager.media.show_folders', true) ? 'true' : 'false' }}"
:allow-upload="{{ config('voyager.media.allow_upload', true) ? 'true' : 'false' }}"
:allow-move="{{ config('voyager.media.allow_move', true) ? 'true' : 'false' }}"
:allow-delete="{{ config('voyager.media.allow_delete', true) ? 'true' : 'false' }}"
:allow-create-folder="{{ config('voyager.media.allow_create_folder', true) ? 'true' : 'false' }}"
:allow-rename="{{ config('voyager.media.allow_rename', true) ? 'true' : 'false' }}"
:allow-crop="{{ config('voyager.media.allow_crop', true) ? 'true' : 'false' }}"
:details="{{ json_encode(['thumbnails' => config('voyager.media.thumbnails', []), 'watermark' => config('voyager.media.watermark', (object)[])]) }}"
></media-manager>
</div>
</div><!-- .row -->
</div><!-- .col-md-12 -->
</div><!-- .page-content container-fluid -->
@stop
@section('javascript')
<script>
new Vue({
el: '#filemanager'
});
</script>
@endsection
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/media/manager.blade.php | resources/views/media/manager.blade.php | @section('media-manager')
<div>
<div v-if="hidden_element" :id="'dd_'+this._uid" class="dd">
<ol id="files" class="dd-list">
<li v-for="file in getSelectedFiles()" class="dd-item" :data-url="file">
<div class="file_link selected" aria-hidden="true" data-toggle="tooltip" data-placement="auto" :title="file">
<div class="link_icon">
<template v-if="fileIs(file, 'image')">
<div class="img_icon" :style="imgIcon('{{ Storage::disk(config('voyager.storage.disk'))->url('/') }}'+file)"></div>
</template>
<template v-else-if="fileIs(file, 'video')">
<i class="icon voyager-video"></i>
</template>
<template v-else-if="fileIs(file, 'audio')">
<i class="icon voyager-music"></i>
</template>
<template v-else-if="fileIs(file, 'zip')">
<i class="icon voyager-archive"></i>
</template>
<template v-else-if="fileIs(file, 'folder')">
<i class="icon voyager-folder"></i>
</template>
<template v-else>
<i class="icon voyager-file-text"></i>
</template>
</div>
<div class="details">
<div class="folder">
<h4>@{{ getFileName(file) }}</h4>
</div>
</div>
<i class="voyager-x dd-nodrag" v-on:click="removeFileFromInput(file)"></i>
</div>
</li>
</ol>
</div>
<div v-if="hidden_element">
<div class="btn btn-sm btn-default" v-on:click="isExpanded = !isExpanded;" style="width:100%">
<div v-if="!isExpanded"><i class="voyager-double-down"></i> {{ __('voyager::generic.open') }}</div>
<div v-if="isExpanded"><i class="voyager-double-up"></i> {{ __('voyager::generic.close') }}</div>
</div>
</div>
<div id="toolbar" v-if="showToolbar" :style="isExpanded ? 'display:block' : 'display:none'">
<div class="btn-group offset-right">
<button type="button" class="btn btn-primary" id="upload" v-if="allowUpload">
<i class="voyager-upload"></i>
{{ __('voyager::generic.upload') }}
</button>
<button type="button" class="btn btn-primary" v-if="allowCreateFolder" data-toggle="modal" :data-target="'#create_dir_modal_'+this._uid">
<i class="voyager-folder"></i>
{{ __('voyager::generic.add_folder') }}
</button>
</div>
<button type="button" class="btn btn-default" v-on:click="getFiles()">
<i class="voyager-refresh"></i>
</button>
<div class="btn-group offset-right">
<button type="button" :disabled="selected_files.length == 0" v-if="allowUpload && hidden_element" class="btn btn-default" v-on:click="addSelectedFiles()">
<i class="voyager-upload"></i>
{{ __('voyager::media.add_all_selected') }}
</button>
<button type="button" v-if="showFolders && allowMove" class="btn btn-default" data-toggle="modal" :data-target="'#move_files_modal_'+this._uid">
<i class="voyager-move"></i>
{{ __('voyager::generic.move') }}
</button>
<button type="button" v-if="allowDelete" :disabled="selected_files.length == 0" class="btn btn-default" data-toggle="modal" :data-target="'#confirm_delete_modal_'+this._uid">
<i class="voyager-trash"></i>
{{ __('voyager::generic.delete') }}
</button>
<button v-if="allowCrop" :disabled="selected_files.length != 1 || !fileIs(selected_file, 'image')" type="button" class="btn btn-default" data-toggle="modal" :data-target="'#crop_modal_'+this._uid">
<i class="voyager-crop"></i>
{{ __('voyager::media.crop') }}
</button>
</div>
</div>
<div id="uploadPreview" style="display:none;" v-if="allowUpload"></div>
<div id="uploadProgress" class="progress active progress-striped" v-if="allowUpload">
<div class="progress-bar progress-bar-success" style="width: 0"></div>
</div>
<div id="content" :style="isExpanded ? 'display:block' : 'display:none'">
<div class="breadcrumb-container">
<ol class="breadcrumb filemanager">
<li class="media_breadcrumb" v-on:click="setCurrentPath(-1)">
<span class="arrow"></span>
<strong>{{ __('voyager::media.library') }}</strong>
</li>
<li v-for="(folder, i) in getCurrentPath()" v-on:click="setCurrentPath(i)">
<span class="arrow"></span>
@{{ folder }}
</li>
</ol>
</div>
<div class="flex">
<div id="left">
<ul id="files">
<li v-for="(file) in files" v-on:click="selectFile(file, $event)" v-on:dblclick="openFile(file)" v-if="filter(file)">
<div :class="'file_link ' + (isFileSelected(file) ? 'selected' : '')">
<div class="link_icon">
<template v-if="fileIs(file, 'image')">
<div class="img_icon" :style="imgIcon(file.path)"></div>
</template>
<template v-else-if="fileIs(file, 'video')">
<i class="icon voyager-video"></i>
</template>
<template v-else-if="fileIs(file, 'audio')">
<i class="icon voyager-music"></i>
</template>
<template v-else-if="fileIs(file, 'zip')">
<i class="icon voyager-archive"></i>
</template>
<template v-else-if="fileIs(file, 'folder')">
<i class="icon voyager-folder"></i>
</template>
<template v-else>
<i class="icon voyager-file-text"></i>
</template>
</div>
<div class="details">
<div :class="file.type">
<h4>@{{ file.name }}</h4>
<small v-if="!fileIs(file, 'folder')">
<span class="file_size">@{{ bytesToSize(file.size) }}</span>
</small>
</div>
</div>
</div>
</li>
</ul>
<div id="file_loader" v-if="is_loading">
<?php $admin_loader_img = Voyager::setting('admin.loader', ''); ?>
@if($admin_loader_img == '')
<img src="{{ voyager_asset('images/logo-icon.png') }}" alt="Voyager Loader">
@else
<img src="{{ Voyager::image($admin_loader_img) }}" alt="Voyager Loader">
@endif
<p>{{ __('voyager::media.loading') }}</p>
</div>
<div id="no_files" v-if="files.length == 0">
<h3><i class="voyager-meh"></i> {{ __('voyager::media.no_files_in_folder') }}</h3>
</div>
</div>
<div id="right">
<div class="right_details">
<div v-if="selected_files.length > 1" class="right_none_selected">
<i class="voyager-list"></i>
<p>@{{ selected_files.length }} {{ __('voyager::media.files_selected') }}</p>
</div>
<div v-else-if="selected_files.length == 1" class="right_details">
<div class="detail_img">
<div v-if="fileIs(selected_file, 'image')">
<img :src="selected_file.path" />
</div>
<div v-else-if="fileIs(selected_file, 'video')">
<video width="100%" height="auto" ref="videoplayer" controls>
<source :src="selected_file.path" type="video/mp4">
<source :src="selected_file.path" type="video/ogg">
<source :src="selected_file.path" type="video/webm">
{{ __('voyager::media.browser_video_support') }}
</video>
</div>
<div v-else-if="fileIs(selected_file, 'audio')">
<i class="voyager-music"></i>
<audio controls style="width:100%; margin-top:5px;" ref="audioplayer">
<source :src="selected_file.path" type="audio/ogg">
<source :src="selected_file.path" type="audio/mpeg">
{{ __('voyager::media.browser_audio_support') }}
</audio>
</div>
<div v-else-if="fileIs(selected_file, 'zip')">
<i class="voyager-archive"></i>
</div>
<div v-else-if="fileIs(selected_file, 'folder')">
<i class="voyager-folder"></i>
</div>
<div v-else>
<i class="voyager-file-text"></i>
</div>
</div>
<div class="detail_info">
<span>
<h4>{{ __('voyager::media.title') }}:</h4>
<input v-if="allowRename" type="text" class="form-control" :value="selected_file.name" @keydown.enter.prevent="renameFile">
<p v-else>@{{ selected_file.name }}</p>
</span>
<span>
<h4>{{ __('voyager::media.type') }}:</h4>
<p>@{{ selected_file.type }}</p>
</span>
<template v-if="!fileIs(selected_file, 'folder')">
<span>
<h4>{{ __('voyager::media.size') }}:</h4>
<p><span class="selected_file_size">@{{ bytesToSize(selected_file.size) }}</span></p>
</span>
<span>
<h4>{{ __('voyager::media.public_url') }}:</h4>
<p><a :href="selected_file.path" target="_blank">{{ __('voyager::generic.click_here') }}</a></p>
</span>
<span>
<h4>{{ __('voyager::media.last_modified') }}:</h4>
<p>@{{ dateFilter(selected_file.last_modified) }}</p>
</span>
</template>
<span v-if="fileIs(selected_file, 'image') && selected_file.thumbnails.length > 0">
<h4>Thumbnails</h4><br>
<ul>
<li v-for="thumbnail in selected_file.thumbnails">
<a :href="thumbnail.path" target="_blank">
@{{ thumbnail.thumb_name }}
</a>
</li>
</ul>
</span>
</div>
</div>
<div v-else class="right_none_selected">
<i class="voyager-cursor"></i>
<p>{{ __('voyager::media.nothing_selected') }}</p>
</div>
</div>
</div>
</div>
</div>
<!-- Image Modal -->
<div class="modal fade" :id="'imagemodal_'+this._uid" v-if="selected_file && fileIs(selected_file, 'image')">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<img :src="selected_file.path" class="img img-responsive" style="margin: 0 auto;">
</div>
<div class="modal-footer text-left">
<small class="image-title">@{{ selected_file.name }}</small>
</div>
</div>
</div>
</div>
<!-- End Image Modal -->
<!-- New Folder Modal -->
<div class="modal fade modal-info" :id="'create_dir_modal_'+this._uid">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="voyager-folder"></i> {{ __('voyager::media.add_new_folder') }}</h4>
</div>
<div class="modal-body">
<input name="new_folder_name" placeholder="{{ __('voyager::media.new_folder_name') }}" class="form-control" value="" v-model="modals.new_folder.name" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{{ __('voyager::generic.cancel') }}</button>
<button type="button" class="btn btn-info" v-on:click="createFolder">{{ __('voyager::media.create_new_folder') }}
</button>
</div>
</div>
</div>
</div>
<!-- End New Folder Modal -->
<!-- Delete File Modal -->
<div class="modal fade modal-danger" :id="'confirm_delete_modal_'+this._uid" v-if="allowDelete">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="voyager-warning"></i> {{ __('voyager::generic.are_you_sure') }}</h4>
</div>
<div class="modal-body">
<h4>{{ __('voyager::media.delete_question') }}</h4>
<ul>
<li v-for="file in selected_files">@{{ file.name }}</li>
</ul>
<h5 class="folder_warning">
<i class="voyager-warning"></i> {{ __('voyager::media.delete_folder_question') }}
</h5>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{{ __('voyager::generic.cancel') }}</button>
<button type="button" class="btn btn-danger" v-on:click="deleteFiles">{{ __('voyager::generic.delete_confirm') }}
</button>
</div>
</div>
</div>
</div>
<!-- End Delete File Modal -->
<!-- Move Files Modal -->
<div class="modal fade modal-warning" :id="'move_files_modal_'+this._uid" v-if="allowMove">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title"><i class="voyager-move"></i> {{ __('voyager::media.move_file_folder') }}</h4>
</div>
<div class="modal-body">
<h4>{{ __('voyager::media.destination_folder') }}</h4>
<select class="form-control" v-model="modals.move_files.destination">
<option value="" disabled>{{ __('voyager::media.destination_folder') }}</option>
<option v-if="current_folder != basePath && showFolders" value="/../">../</option>
<option v-for="file in files" v-if="file.type == 'folder' && !selected_files.includes(file)" :value="current_folder+'/'+file.name">@{{ file.name }}</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{{ __('voyager::generic.cancel') }}</button>
<button type="button" class="btn btn-warning" v-on:click="moveFiles">{{ __('voyager::generic.move') }}</button>
</div>
</div>
</div>
</div>
<!-- End Move File Modal -->
<!-- Crop Image Modal -->
<div class="modal fade modal-warning" :id="'crop_modal_'+this._uid" v-if="allowCrop">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">{{ __('voyager::media.crop_image') }}</h4>
</div>
<div class="modal-body">
<div class="crop-container">
<img :id="'cropping-image_'+this._uid" v-if="selected_files.length == 1 && fileIs(selected_file, 'image')" class="img img-responsive" :src="selected_file.path + '?' + selected_file.last_modified" />
</div>
<div class="new-image-info">
{{ __('voyager::media.width') }} <span :id="'new-image-width_'+this._uid"></span>, {{ __('voyager::media.height') }}<span :id="'new-image-height_'+this._uid"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{{ __('voyager::generic.cancel') }}</button>
<button type="button" class="btn btn-warning" v-on:click="crop(false)">{{ __('voyager::media.crop') }}</button>
<button type="button" class="btn btn-warning" v-on:click="crop(true)">{{ __('voyager::media.crop_and_create') }}</button>
</div>
</div>
</div>
</div>
<!-- End Crop Image Modal -->
</div>
@endsection
<script>
Vue.component('media-manager', {
template: `@yield('media-manager')`,
props: {
basePath: {
type: String,
default: '/'
},
filename: {
type: String,
default: null
},
allowMultiSelect: {
type: Boolean,
default: true
},
maxSelectedFiles: {
type: Number,
default: 0
},
minSelectedFiles: {
type: Number,
default: 0
},
showFolders: {
type: Boolean,
default: true
},
showToolbar: {
type: Boolean,
default: true
},
allowUpload: {
type: Boolean,
default: true
},
allowMove: {
type: Boolean,
default: true
},
allowDelete: {
type: Boolean,
default: true
},
allowCreateFolder: {
type: Boolean,
default: true
},
allowRename: {
type: Boolean,
default: true
},
allowCrop: {
type: Boolean,
default: true
},
allowedTypes: {
type: Array,
default: function() {
return [];
}
},
preSelect: {
type: Boolean,
default: true,
},
element: {
type: String,
default: ""
},
details: {
type: Object,
default: function() {
return {};
}
},
expanded: {
type: Boolean,
default: true,
},
},
data: function() {
return {
current_folder: this.basePath,
selected_files: [],
files: [],
is_loading: true,
hidden_element: null,
isExpanded: this.expanded,
modals: {
new_folder: {
name: ''
},
move_files: {
destination: ''
}
}
};
},
computed: {
selected_file: function() {
return this.selected_files[0];
}
},
methods: {
getFiles: function() {
var vm = this;
vm.is_loading = true;
$.post('{{ route('voyager.media.files') }}', { folder: vm.current_folder, _token: '{{ csrf_token() }}', details: vm.details }, function(data) {
vm.files = [];
for (var i = 0, file; file = data[i]; i++) {
if (vm.filter(file)) {
vm.files.push(file);
}
}
vm.selected_files = [];
if (vm.preSelect && data.length > 0) {
vm.selected_files.push(data[0]);
}
vm.is_loading = false;
});
},
selectFile: function(file, e) {
if ((!e.ctrlKey && !e.metaKey && !e.shiftKey) || !this.allowMultiSelect) {
this.selected_files = [];
}
if (e.shiftKey && this.allowMultiSelect && this.selected_files.length == 1) {
var index = null;
var start = 0;
for (var i = 0, cfile; cfile = this.files[i]; i++) {
if (cfile === this.selected_file) {
start = i;
break;
}
}
var end = 0;
for (var i = 0, cfile; cfile = this.files[i]; i++) {
if (cfile === file) {
end = i;
break;
}
}
for (var i = start; i < end; i++) {
index = this.selected_files.indexOf(this.files[i]);
if (index === -1) {
this.selected_files.push(this.files[i]);
}
}
}
index = this.selected_files.indexOf(file);
if (index === -1) {
this.selected_files.push(file);
}
if (this.selected_files.length == 1) {
var vm = this;
Vue.nextTick(function () {
if (vm.fileIs(vm.selected_file, 'video')) {
vm.$refs.videoplayer.load();
} else if (vm.fileIs(vm.selected_file, 'audio')) {
vm.$refs.audioplayer.load();
}
});
}
},
openFile: function(file) {
if (file.type == 'folder') {
this.current_folder += file.name+"/";
this.getFiles();
} else if (this.hidden_element) {
this.addFileToInput(file);
} else {
if (this.fileIs(this.selected_file, 'image')) {
$('#imagemodal_' + this._uid).modal('show');
} else {
// ...
}
}
},
isFileSelected: function(file) {
return this.selected_files.includes(file);
},
fileIs: function(file, type) {
if (typeof file === 'string') {
if (type == 'image') {
return this.endsWithAny(['jpg', 'jpeg', 'png', 'bmp'], file.toLowerCase());
}
//Todo: add other types
} else {
return file.type.includes(type);
}
return false;
},
getCurrentPath: function() {
var path = this.current_folder.replace(this.basePath, '').split('/').filter(function (el) {
return el != '';
});
return path;
},
setCurrentPath: function(i) {
if (i == -1) {
this.current_folder = this.basePath;
} else {
var path = this.getCurrentPath();
path.length = i + 1;
this.current_folder = this.basePath+path.join('/') + '/';
}
this.getFiles();
},
filter: function(file) {
if (this.allowedTypes.length > 0) {
if (file.type != 'folder') {
for (var i = 0, type; type = this.allowedTypes[i]; i++) {
if (file.type.includes(type)) {
return true;
}
}
}
}
if (file.type == 'folder' && this.showFolders) {
return true;
} else if (file.type == 'folder' && !this.showFolders) {
return false;
}
if (this.allowedTypes.length == 0) {
return true;
}
return false;
},
addFileToInput: function(file) {
if (file.type != 'folder') {
if (!this.allowMultiSelect) {
this.hidden_element.value = file.relative_path;
} else {
var content = JSON.parse(this.hidden_element.value);
if (content.indexOf(file.relative_path) !== -1) {
return;
}
if (content.length >= this.maxSelectedFiles && this.maxSelectedFiles > 0) {
var msg_sing = "{{ trans_choice('voyager::media.max_files_select', 1) }}";
var msg_plur = "{{ trans_choice('voyager::media.max_files_select', 2) }}";
if (this.maxSelectedFiles == 1) {
toastr.error(msg_sing);
} else {
toastr.error(msg_plur.replace('2', this.maxSelectedFiles));
}
} else {
content.push(file.relative_path);
this.hidden_element.value = JSON.stringify(content);
}
}
this.$forceUpdate();
}
},
removeFileFromInput: function(path) {
if (this.allowMultiSelect) {
var content = JSON.parse(this.hidden_element.value);
if (content.indexOf(path) !== -1) {
content.splice(content.indexOf(path), 1);
this.hidden_element.value = JSON.stringify(content);
this.$forceUpdate();
}
} else {
this.hidden_element.value = '';
}
},
getSelectedFiles: function() {
if (!this.allowMultiSelect) {
var content = [];
if (this.hidden_element.value != '') {
content.push(this.hidden_element.value);
}
return content;
} else {
return JSON.parse(this.hidden_element.value);
}
},
renameFile: function(object) {
var vm = this;
if (!this.allowRename || vm.selected_file.name == object.target.value) {
return;
}
$.post('{{ route('voyager.media.rename') }}', {
folder_location: vm.current_folder,
filename: vm.selected_file.name,
new_filename: object.target.value,
_token: '{{ csrf_token() }}'
}, function(data){
if (data.success == true) {
toastr.success('{{ __('voyager::media.success_renamed') }}', "{{ __('voyager::generic.sweet_success') }}");
vm.getFiles();
} else {
toastr.error(data.error, "{{ __('voyager::generic.whoopsie') }}");
}
});
},
createFolder: function(e) {
if (!this.allowCreateFolder) {
return;
}
var vm = this;
var name = this.modals.new_folder.name;
$.post('{{ route('voyager.media.new_folder') }}', { new_folder: vm.current_folder+'/'+name, _token: '{{ csrf_token() }}' }, function(data) {
if(data.success == true){
toastr.success('{{ __('voyager::generic.successfully_created') }} ' + name, "{{ __('voyager::generic.sweet_success') }}");
vm.getFiles();
} else {
toastr.error(data.error, "{{ __('voyager::generic.whoopsie') }}");
}
vm.modals.new_folder.name = '';
$('#create_dir_modal_'+vm._uid).modal('hide');
});
},
deleteFiles: function() {
if (!this.allowDelete) {
return;
}
var vm = this;
$.post('{{ route('voyager.media.delete') }}', {
path: vm.current_folder,
files: vm.selected_files,
_token: '{{ csrf_token() }}'
}, function(data){
if(data.success == true){
toastr.success('', "{{ __('voyager::generic.sweet_success') }}");
vm.getFiles();
$('#confirm_delete_modal_'+vm._uid).modal('hide');
} else {
toastr.error(data.error, "{{ __('voyager::generic.whoopsie') }}");
vm.getFiles();
$('#confirm_delete_modal_'+vm._uid).modal('hide');
}
});
},
moveFiles: function(e) {
if (!this.allowMove) {
return;
}
var vm = this;
var destination = this.modals.move_files.destination;
if (destination === '') {
return;
}
$('#move_files_modal_'+vm._uid).modal('hide');
$.post('{{ route('voyager.media.move') }}', {
path: vm.current_folder,
files: vm.selected_files,
destination: destination,
_token: '{{ csrf_token() }}'
}, function(data){
if(data.success == true){
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | true |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/menus/builder.blade.php | resources/views/menus/builder.blade.php | @extends('voyager::master')
@section('page_title', __('voyager::generic.menu_builder'))
@section('page_header')
<h1 class="page-title">
<i class="voyager-list"></i>{{ __('voyager::generic.menu_builder') }} ({{ $menu->name }})
<div class="btn btn-success add_item"><i class="voyager-plus"></i> {{ __('voyager::menu_builder.new_menu_item') }}</div>
</h1>
@include('voyager::multilingual.language-selector')
@stop
@section('content')
@include('voyager::menus.partial.notice')
<div class="page-content container-fluid">
<div class="row">
<div class="col-md-12">
<div class="panel panel-bordered">
<div class="panel-heading">
<p class="panel-title" style="color:#777">{{ __('voyager::menu_builder.drag_drop_info') }}</p>
</div>
<div class="panel-body" style="padding:30px;">
<div class="dd">
{!! menu($menu->name, 'admin', ['isModelTranslatable' => $isModelTranslatable]) !!}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal modal-danger fade" tabindex="-1" id="delete_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="{{ __('voyager::generic.close') }}"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title"><i class="voyager-trash"></i> {{ __('voyager::menu_builder.delete_item_question') }}</h4>
</div>
<div class="modal-footer">
<form action="{{ route('voyager.menus.item.destroy', ['menu' => $menu->id, 'id' => '__id']) }}"
id="delete_form"
method="POST">
{{ method_field("DELETE") }}
{{ csrf_field() }}
<input type="submit" class="btn btn-danger pull-right delete-confirm"
value="{{ __('voyager::menu_builder.delete_item_confirm') }}">
</form>
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">{{ __('voyager::generic.cancel') }}</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div class="modal modal-info fade" tabindex="-1" id="menu_item_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="{{ __('voyager::generic.close') }}"><span
aria-hidden="true">×</span></button>
<h4 id="m_hd_add" class="modal-title hidden"><i class="voyager-plus"></i> {{ __('voyager::menu_builder.create_new_item') }}</h4>
<h4 id="m_hd_edit" class="modal-title hidden"><i class="voyager-edit"></i> {{ __('voyager::menu_builder.edit_item') }}</h4>
</div>
<form action="" id="m_form" method="POST"
data-action-add="{{ route('voyager.menus.item.add', ['menu' => $menu->id]) }}"
data-action-update="{{ route('voyager.menus.item.update', ['menu' => $menu->id]) }}">
<input id="m_form_method" type="hidden" name="_method" value="POST">
{{ csrf_field() }}
<div class="modal-body">
<div>
@include('voyager::multilingual.language-selector')
<label for="name">{{ __('voyager::menu_builder.item_title') }}</label>
@include('voyager::multilingual.input-hidden', ['_field_name' => 'title', '_field_trans' => ''])
<input type="text" class="form-control" id="m_title" name="title" placeholder="{{ __('voyager::generic.title') }}"><br>
</div>
<label for="type">{{ __('voyager::menu_builder.link_type') }}</label>
<select id="m_link_type" class="form-control" name="type">
<option value="url" selected="selected">{{ __('voyager::menu_builder.static_url') }}</option>
<option value="route">{{ __('voyager::menu_builder.dynamic_route') }}</option>
</select><br>
<div id="m_url_type">
<label for="url">{{ __('voyager::menu_builder.url') }}</label>
<input type="text" class="form-control" id="m_url" name="url" placeholder="{{ __('voyager::generic.url') }}"><br>
</div>
<div id="m_route_type">
<label for="route">{{ __('voyager::menu_builder.item_route') }}</label>
<input type="text" class="form-control" id="m_route" name="route" placeholder="{{ __('voyager::generic.route') }}"><br>
<label for="parameters">{{ __('voyager::menu_builder.route_parameter') }}</label>
<textarea rows="3" class="form-control" id="m_parameters" name="parameters" placeholder="{{ json_encode(['key' => 'value'], JSON_PRETTY_PRINT) }}"></textarea><br>
</div>
<label for="icon_class">{{ __('voyager::menu_builder.icon_class') }} <a
href="{{ route('voyager.compass.index') }}#fonts"
target="_blank">{!! __('voyager::menu_builder.icon_class2') !!}</label>
<input type="text" class="form-control" id="m_icon_class" name="icon_class"
placeholder="{{ __('voyager::menu_builder.icon_class_ph') }}"><br>
<label for="color">{{ __('voyager::menu_builder.color') }}</label>
<input type="color" class="form-control" id="m_color" name="color"
placeholder="{{ __('voyager::menu_builder.color_ph') }}"><br>
<label for="target">{{ __('voyager::menu_builder.open_in') }}</label>
<select id="m_target" class="form-control" name="target">
<option value="_self" selected="selected">{{ __('voyager::menu_builder.open_same') }}</option>
<option value="_blank">{{ __('voyager::menu_builder.open_new') }}</option>
</select>
<input type="hidden" name="menu_id" value="{{ $menu->id }}">
<input type="hidden" name="id" id="m_id" value="">
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-success pull-right delete-confirm__" value="{{ __('voyager::generic.update') }}">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">{{ __('voyager::generic.cancel') }}</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
@stop
@section('javascript')
<script>
$(document).ready(function () {
@if ($isModelTranslatable)
/**
* Multilingual setup for main page
*/
$('.side-body').multilingual({
"transInputs": '.dd-list input[data-i18n=true]'
});
/**
* Multilingual for Add/Edit Menu
*/
$('#menu_item_modal').multilingual({
"form": 'form',
"transInputs": '#menu_item_modal input[data-i18n=true]',
"langSelectors": '.language-selector input',
"editing": true
});
@endif
$('.dd').nestable({
expandBtnHTML: '',
collapseBtnHTML: ''
});
/**
* Set Variables
*/
var $m_modal = $('#menu_item_modal'),
$m_hd_add = $('#m_hd_add').hide().removeClass('hidden'),
$m_hd_edit = $('#m_hd_edit').hide().removeClass('hidden'),
$m_form = $('#m_form'),
$m_form_method = $('#m_form_method'),
$m_title = $('#m_title'),
$m_title_i18n = $('#title_i18n'),
$m_url_type = $('#m_url_type'),
$m_url = $('#m_url'),
$m_link_type = $('#m_link_type'),
$m_route_type = $('#m_route_type'),
$m_route = $('#m_route'),
$m_parameters = $('#m_parameters'),
$m_icon_class = $('#m_icon_class'),
$m_color = $('#m_color'),
$m_target = $('#m_target'),
$m_id = $('#m_id');
/**
* Add Menu
*/
$('.add_item').click(function() {
$m_form.trigger('reset');
$m_form.find("input[type=submit]").val('{{ __('voyager::generic.add') }}');
$m_modal.modal('show', {data: null});
});
/**
* Edit Menu
*/
$('.item_actions').on('click', '.edit', function (e) {
$m_form.find("input[type=submit]").val('{{ __('voyager::generic.update') }}');
$m_modal.modal('show', {data: $(e.currentTarget)});
});
/**
* Menu Modal is Open
*/
$m_modal.on('show.bs.modal', function(e, data) {
var _adding = e.relatedTarget.data ? false : true,
translatable = $m_modal.data('multilingual'),
$_str_i18n = '';
if (_adding) {
$m_form.attr('action', $m_form.data('action-add'));
$m_form_method.val('POST');
$m_hd_add.show();
$m_hd_edit.hide();
$m_target.val('_self').change();
$m_link_type.val('url').change();
$m_url.val('');
$m_icon_class.val('');
} else {
$m_form.attr('action', $m_form.data('action-update'));
$m_form_method.val('PUT');
$m_hd_add.hide();
$m_hd_edit.show();
var _src = e.relatedTarget.data, // the source
id = _src.data('id');
$m_title.val(_src.data('title'));
$m_url.val(_src.data('url'));
$m_route.val(_src.data('route'));
$m_parameters.val(JSON.stringify(_src.data('parameters')));
$m_icon_class.val(_src.data('icon_class'));
$m_color.val(_src.data('color'));
$m_id.val(id);
if(translatable){
$_str_i18n = $("#title" + id + "_i18n").val();
}
if (_src.data('target') == '_self') {
$m_target.val('_self').change();
} else if (_src.data('target') == '_blank') {
$m_target.find("option[value='_self']").removeAttr('selected');
$m_target.find("option[value='_blank']").attr('selected', 'selected');
$m_target.val('_blank');
}
if (_src.data('route') != "") {
$m_link_type.val('route').change();
$m_url_type.hide();
} else {
$m_link_type.val('url').change();
$m_route_type.hide();
}
if ($m_link_type.val() == 'route') {
$m_url_type.hide();
$m_route_type.show();
} else {
$m_route_type.hide();
$m_url_type.show();
}
}
if (translatable) {
$m_title_i18n.val($_str_i18n);
translatable.refresh();
}
});
/**
* Toggle Form Menu Type
*/
$m_link_type.on('change', function (e) {
if ($m_link_type.val() == 'route') {
$m_url_type.hide();
$m_route_type.show();
} else {
$m_url_type.show();
$m_route_type.hide();
}
});
/**
* Delete menu item
*/
$('.item_actions').on('click', '.delete', function (e) {
id = $(e.currentTarget).data('id');
$('#delete_form')[0].action = '{{ route('voyager.menus.item.destroy', ['menu' => $menu->id, 'id' => '__id']) }}'.replace('__id', id);
$('#delete_modal').modal('show');
});
/**
* Reorder items
*/
$('.dd').on('change', function (e) {
$.post('{{ route('voyager.menus.order_item',['menu' => $menu->id]) }}', {
order: JSON.stringify($('.dd').nestable('serialize')),
_token: '{{ csrf_token() }}'
}, function (data) {
toastr.success("{{ __('voyager::menu_builder.updated_order') }}");
});
});
});
</script>
@stop
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/menus/browse.blade.php | resources/views/menus/browse.blade.php | @extends('voyager::master')
@section('page_title', __('voyager::generic.viewing').' '.$dataType->getTranslatedAttribute('display_name_plural'))
@section('page_header')
<h1 class="page-title">
<i class="voyager-list-add"></i> {{ $dataType->getTranslatedAttribute('display_name_plural') }}
@can('add',app($dataType->model_name))
<a href="{{ route('voyager.'.$dataType->slug.'.create') }}" class="btn btn-success">
<i class="voyager-plus"></i> {{ __('voyager::generic.add_new') }}
</a>
@endcan
</h1>
@stop
@section('content')
@include('voyager::menus.partial.notice')
<div class="page-content container-fluid">
@include('voyager::alerts')
<div class="row">
<div class="col-md-12">
<div class="panel panel-bordered">
<div class="panel-body">
<table id="dataTable" class="table table-hover">
<thead>
<tr>
@foreach($dataType->browseRows as $row)
<th>{{ $row->display_name }}</th>
@endforeach
<th class="actions text-right">{{ __('voyager::generic.actions') }}</th>
</tr>
</thead>
<tbody>
@foreach($dataTypeContent as $data)
<tr>
@foreach($dataType->browseRows as $row)
<td>
@if($row->type == 'image')
<img src="@if( strpos($data->{$row->field}, 'http://') === false && strpos($data->{$row->field}, 'https://') === false){{ Voyager::image( $data->{$row->field} ) }}@else{{ $data->{$row->field} }}@endif" style="width:100px">
@else
{{ $data->{$row->field} }}
@endif
</td>
@endforeach
<td class="no-sort no-click bread-actions">
@can('delete', $data)
<div class="btn btn-sm btn-danger pull-right delete" data-id="{{ $data->{$data->getKeyName()} }}">
<i class="voyager-trash"></i> {{ __('voyager::generic.delete') }}
</div>
@endcan
@can('edit', $data)
<a href="{{ route('voyager.'.$dataType->slug.'.edit', $data->{$data->getKeyName()}) }}" class="btn btn-sm btn-primary pull-right edit">
<i class="voyager-edit"></i> {{ __('voyager::generic.edit') }}
</a>
@endcan
@can('edit', $data)
<a href="{{ route('voyager.'.$dataType->slug.'.builder', $data->{$data->getKeyName()}) }}" class="btn btn-sm btn-success pull-right">
<i class="voyager-list"></i> {{ __('voyager::generic.builder') }}
</a>
@endcan
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal modal-danger fade" tabindex="-1" id="delete_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="{{ __('voyager::generic.close') }}">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">
<i class="voyager-trash"></i> {{ __('voyager::generic.delete_question') }} {{ $dataType->getTranslatedAttribute('display_name_singular') }}?
</h4>
</div>
<div class="modal-footer">
<form action="#" id="delete_form" method="POST">
{{ method_field("DELETE") }}
{{ csrf_field() }}
<input type="submit" class="btn btn-danger pull-right delete-confirm" value="{{ __('voyager::generic.delete_this_confirm') }} {{ $dataType->getTranslatedAttribute('display_name_singular') }}">
</form>
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">{{ __('voyager::generic.cancel') }}</button>
</div>
</div>
</div>
</div>
@stop
@section('javascript')
<!-- DataTables -->
<script>
$(document).ready(function () {
$('#dataTable').DataTable({
"order": [],
"language": {!! json_encode(__('voyager::datatable'), true) !!},
"columnDefs": [{"targets": -1, "searchable": false, "orderable": false}]
@if(config('dashboard.data_tables.responsive')), responsive: true @endif
});
});
$('td').on('click', '.delete', function (e) {
$('#delete_form')[0].action = '{{ route('voyager.'.$dataType->slug.'.destroy', ['id' => '__menu']) }}'.replace('__menu', $(this).data('id'));
$('#delete_modal').modal('show');
});
</script>
@stop
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/menus/partial/notice.blade.php | resources/views/menus/partial/notice.blade.php | @if(config('voyager.show_dev_tips'))
<div class="container-fluid">
<div class="alert alert-info">
<strong>{{ __('voyager::generic.how_to_use') }}:</strong>
<p>{{ trans_choice('voyager::menu_builder.usage_hint', !empty($menu) ? 0 : 1) }} <code>menu('{{ !empty($menu) ? $menu->name : 'name' }}')</code></p>
</div>
</div>
@endif
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/menu/bootstrap.blade.php | resources/views/menu/bootstrap.blade.php | @if(!isset($innerLoop))
<ul class="nav navbar-nav">
@else
<ul class="dropdown-menu">
@endif
@php
if (Voyager::translatable($items)) {
$items = $items->load('translations');
}
@endphp
@foreach ($items as $item)
@php
$originalItem = $item;
if (Voyager::translatable($item)) {
$item = $item->translate($options->locale);
}
$listItemClass = null;
$linkAttributes = null;
$styles = null;
$icon = null;
$caret = null;
// Background Color or Color
if (isset($options->color) && $options->color == true) {
$styles = 'color:'.$item->color;
}
if (isset($options->background) && $options->background == true) {
$styles = 'background-color:'.$item->color;
}
// With Children Attributes
if(!$originalItem->children->isEmpty()) {
$linkAttributes = 'class="dropdown-toggle" data-toggle="dropdown"';
$caret = '<span class="caret"></span>';
if(url($item->link()) == url()->current()){
$listItemClass = 'dropdown active';
}else{
$listItemClass = 'dropdown';
}
}
// Set Icon
if(isset($options->icon) && $options->icon == true){
$icon = '<i class="' . $item->icon_class . '"></i>';
}
@endphp
<li class="{{ $listItemClass }}">
<a href="{{ url($item->link()) }}" target="{{ $item->target }}" style="{{ $styles }}" {!! $linkAttributes ?? '' !!}>
{!! $icon !!}
<span>{{ $item->title }}</span>
{!! $caret !!}
</a>
@if(!$originalItem->children->isEmpty())
@include('voyager::menu.bootstrap', ['items' => $originalItem->children, 'options' => $options, 'innerLoop' => true])
@endif
</li>
@endforeach
</ul>
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/menu/default.blade.php | resources/views/menu/default.blade.php | <ul>
@php
if (Voyager::translatable($items)) {
$items = $items->load('translations');
}
@endphp
@foreach ($items as $item)
@php
$originalItem = $item;
if (Voyager::translatable($item)) {
$item = $item->translate($options->locale);
}
$isActive = null;
$styles = null;
$icon = null;
// Background Color or Color
if (isset($options->color) && $options->color == true) {
$styles = 'color:'.$item->color;
}
if (isset($options->background) && $options->background == true) {
$styles = 'background-color:'.$item->color;
}
// Check if link is current
if(url($item->link()) == url()->current()){
$isActive = 'active';
}
// Set Icon
if(isset($options->icon) && $options->icon == true){
$icon = '<i class="' . $item->icon_class . '"></i>';
}
@endphp
<li class="{{ $isActive }}">
<a href="{{ url($item->link()) }}" target="{{ $item->target }}" style="{{ $styles }}">
{!! $icon !!}
<span>{{ $item->title }}</span>
</a>
@if(!$originalItem->children->isEmpty())
@include('voyager::menu.default', ['items' => $originalItem->children, 'options' => $options])
@endif
</li>
@endforeach
</ul>
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/menu/admin.blade.php | resources/views/menu/admin.blade.php | <ol class="dd-list">
@foreach ($items as $item)
<li class="dd-item" data-id="{{ $item->id }}">
<div class="pull-right item_actions">
<div class="btn btn-sm btn-danger pull-right delete" data-id="{{ $item->id }}">
<i class="voyager-trash"></i> {{ __('voyager::generic.delete') }}
</div>
<div class="btn btn-sm btn-primary pull-right edit"
data-id="{{ $item->id }}"
data-title="{{ $item->title }}"
data-url="{{ $item->url }}"
data-target="{{ $item->target }}"
data-icon_class="{{ $item->icon_class }}"
data-color="{{ $item->color }}"
data-route="{{ $item->route }}"
data-parameters="{{ json_encode($item->parameters) }}"
>
<i class="voyager-edit"></i> {{ __('voyager::generic.edit') }}
</div>
</div>
<div class="dd-handle">
@if($options->isModelTranslatable)
@include('voyager::multilingual.input-hidden', [
'isModelTranslatable' => true,
'_field_name' => 'title'.$item->id,
'_field_trans' => json_encode($item->getTranslationsOf('title'))
])
@endif
<span>{{ $item->title }}</span> <small class="url">{{ $item->link() }}</small>
</div>
@if(!$item->children->isEmpty())
@include('voyager::menu.admin', ['items' => $item->children])
@endif
</li>
@endforeach
</ol>
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/compass/index.blade.php | resources/views/compass/index.blade.php | @extends('voyager::master')
@section('css')
@include('voyager::compass.includes.styles')
@stop
@section('page_header')
<h1 class="page-title">
<i class="voyager-compass"></i>
<p> {{ __('voyager::generic.compass') }}</p>
<span class="page-description">{{ __('voyager::compass.welcome') }}</span>
</h1>
@stop
@section('content')
<div id="gradient_bg"></div>
<div class="container-fluid">
@include('voyager::alerts')
</div>
<div class="page-content compass container-fluid">
<ul class="nav nav-tabs">
<li @if(empty($active_tab) || (isset($active_tab) && $active_tab == 'resources')){!! 'class="active"' !!}@endif><a data-toggle="tab" href="#resources"><i class="voyager-book"></i> {{ __('voyager::compass.resources.title') }}</a></li>
<li @if($active_tab == 'commands'){!! 'class="active"' !!}@endif><a data-toggle="tab" href="#commands"><i class="voyager-terminal"></i> {{ __('voyager::compass.commands.title') }}</a></li>
<li @if($active_tab == 'logs'){!! 'class="active"' !!}@endif><a data-toggle="tab" href="#logs"><i class="voyager-logbook"></i> {{ __('voyager::compass.logs.title') }}</a></li>
</ul>
<div class="tab-content">
<div id="resources" class="tab-pane fade in @if(empty($active_tab) || (isset($active_tab) && $active_tab == 'resources')){!! 'active' !!}@endif">
<h3><i class="voyager-book"></i> {{ __('voyager::compass.resources.title') }} <small>{{ __('voyager::compass.resources.text') }}</small></h3>
<div class="collapsible">
<div class="collapse-head" data-toggle="collapse" data-target="#links" aria-expanded="true" aria-controls="links">
<h4>{{ __('voyager::compass.links.title') }}</h4>
<i class="voyager-angle-down"></i>
<i class="voyager-angle-up"></i>
</div>
<div class="collapse-content collapse in" id="links">
<div class="row">
<div class="col-md-6">
<a href="https://voyager-docs.devdojo.com/" target="_blank" class="voyager-link" style="background-image:url('{{ voyager_asset('images/compass/documentation.jpg') }}')">
<span class="resource_label"><i class="voyager-documentation"></i> <span class="copy">{{ __('voyager::compass.links.documentation') }}</span></span>
</a>
</div>
<div class="col-md-6">
<a href="https://voyager.devdojo.com/" target="_blank" class="voyager-link" style="background-image:url('{{ voyager_asset('images/compass/voyager-home.jpg') }}')">
<span class="resource_label"><i class="voyager-browser"></i> <span class="copy">{{ __('voyager::compass.links.voyager_homepage') }}</span></span>
</a>
</div>
</div>
</div>
</div>
<div class="collapsible">
<div class="collapse-head" data-toggle="collapse" data-target="#fonts" aria-expanded="true" aria-controls="fonts">
<h4>{{ __('voyager::compass.fonts.title') }}</h4>
<i class="voyager-angle-down"></i>
<i class="voyager-angle-up"></i>
</div>
<div class="collapse-content collapse in" id="fonts">
@include('voyager::compass.includes.fonts')
</div>
</div>
</div>
<div id="commands" class="tab-pane fade in @if($active_tab == 'commands'){!! 'active' !!}@endif">
<h3><i class="voyager-terminal"></i> {{ __('voyager::compass.commands.title') }} <small>{{ __('voyager::compass.commands.text') }}</small></h3>
<div id="command_lists">
@include('voyager::compass.includes.commands')
</div>
</div>
<div id="logs" class="tab-pane fade in @if($active_tab == 'logs'){!! 'active' !!}@endif">
<div class="row">
@include('voyager::compass.includes.logs')
</div>
</div>
</div>
</div>
@stop
@section('javascript')
<script>
$('document').ready(function(){
$('.collapse-head').click(function(){
var collapseContainer = $(this).parent();
if(collapseContainer.find('.collapse-content').hasClass('in')){
collapseContainer.find('.voyager-angle-up').fadeOut('fast');
collapseContainer.find('.voyager-angle-down').fadeIn('slow');
} else {
collapseContainer.find('.voyager-angle-down').fadeOut('fast');
collapseContainer.find('.voyager-angle-up').fadeIn('slow');
}
});
});
</script>
<!-- JS for commands -->
<script>
$(document).ready(function(){
$('.command').click(function(){
$(this).find('.cmd_form').slideDown();
$(this).addClass('more_args');
$(this).find('input[type="text"]').focus();
});
$('.close-output').click(function(){
$('#commands pre').slideUp();
});
});
</script>
<!-- JS for logs -->
<script>
$(document).ready(function () {
$('.table-container tr').on('click', function () {
$('#' + $(this).data('display')).toggle();
});
$('#table-log').DataTable({
"order": [1, 'desc'],
"stateSave": true,
"language": {!! json_encode(__('voyager::datatable')) !!},
"stateSaveCallback": function (settings, data) {
window.localStorage.setItem("datatable", JSON.stringify(data));
},
"stateLoadCallback": function (settings) {
var data = JSON.parse(window.localStorage.getItem("datatable"));
if (data) data.start = 0;
return data;
}
});
$('#delete-log, #delete-all-log').click(function () {
return confirm('{{ __('voyager::generic.are_you_sure') }}');
});
});
</script>
@stop
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/compass/includes/commands.blade.php | resources/views/compass/includes/commands.blade.php | @if($artisan_output)
<pre>
<i class="close-output voyager-x">{{ __('voyager::compass.commands.clear_output') }}</i><span class="art_out">{{ __('voyager::compass.commands.command_output') }}:</span>{{ trim(trim($artisan_output,'"')) }}
</pre>
@endif
@foreach($commands as $command)
<div class="command" data-command="{{ $command->name }}">
<code>php artisan {{ $command->name }}</code>
<small>{{ $command->description }}</small><i class="voyager-terminal"></i>
<form action="{{ route('voyager.compass.post') }}" class="cmd_form" method="POST">
{{ csrf_field() }}
<input type="text" name="args" autofocus class="form-control" placeholder="{{ __('voyager::compass.commands.additional_args') }}">
<input type="submit" class="btn btn-primary pull-right delete-confirm"
value="{{ __('voyager::compass.commands.run_command') }}">
<input type="hidden" name="command" id="hidden_cmd" value="{{ $command->name }}">
</form>
</div>
@endforeach
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/compass/includes/styles.blade.php | resources/views/compass/includes/styles.blade.php | <style type="text/css">
.voyager .compass .nav-tabs{
background:none;
border-bottom:0px;
}
.voyager .compass .nav-tabs > li{
margin-bottom:-1px !important;
}
.voyager .compass .nav-tabs a{
text-align: center;
font-size: 10px;
font-weight: normal;
background: #f8f8f8;
border: 1px solid #f1f1f1;
position: relative;
top: -1px;
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
}
.voyager .compass .nav-tabs a i{
display: block;
font-size: 22px;
}
.tab-content{
background:#ffffff;
border: 1px solid transparent;
border-radius: 4px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}
.page-title{
height:85px;
z-index:2;
position:relative;
}
.page-content{
z-index:2;
position:relative;
}
.page-title p{
height: 20px;
margin-bottom: 0px;
padding-top: 0px;
position: relative;
top: -10px;
}
.page-title span{
font-size: 10px;
font-weight: normal;
top: -12px;
position: relative;
}
#gradient_bg{
position: fixed;
top: 61px;
left: 0px;
background-image: url({{ voyager_asset('images/bg.jpg') }});
background-size: cover;
background-position: 0px;
width: 100%;
height: 220px;
z-index: 0;
}
#gradient_bg::after{
content:'';
position:absolute;
left:0px;
top:0px;
width:100%;
height:100%;
/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#f8f8f8+0,f8f8f8+100&0.95+0,1+80 */
background: -moz-linear-gradient(top, rgba(248,248,248,0.93) 0%, rgba(248,248,248,1) 80%, rgba(248,248,248,1) 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(top, rgba(248,248,248,0.93) 0%,rgba(248,248,248,1) 80%,rgba(248,248,248,1) 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(to bottom, rgba(248,248,248,0.93) 0%,rgba(248,248,248,1) 80%,rgba(248,248,248,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f2f8f8f8', endColorstr='#f8f8f8',GradientType=0 ); /* IE6-9 */
z-index:1;
}
.nav-tabs > li.active > a, .nav-tabs > li.active > a:focus, .nav-tabs > li.active > a:hover{
background:#fff !important;
color:#62a8ea !important;
border-bottom:1px solid #fff !important;
top:-1px !important;
}
.nav-tabs > li a{
transition:all 0.3s ease;
}
.nav-tabs > li.active > a:focus{
top:0px !important;
}
.voyager .compass .nav-tabs > li > a:hover{
background-color:#fff !important;
}
.voyager-link{
width: 100%;
min-height: 220px;
display: block;
border-radius: 3px;
background-position: center center;
background-size: cover;
position:relative;
}
.voyager-link span.resource_label{
text-align: center;
color: #fff;
display: block;
position: absolute;
z-index: 9;
top: 0px;
left: 0px;
width: 100%;
padding: 0px;
opacity:0.8;
transition:all 0.3s ease;
line-height: 220px;
height: 100%;
}
.voyager-link span.resource_label:hover{
opacity:1;
}
.voyager-link i{
font-size: 48px;
margin-right: 0px;
position: absolute;
width: 70px;
height: 70px;
padding: 10px;
border-radius: 5px;
line-height: 55px;
display: inline-block;
left: 50%;
margin-top: -50px;
margin-left: -35px;
top: 50%;
line-height:55px;
padding:10px;
}
.voyager-link span.resource_label:hover i{
opacity:1;
transition:all 0.3s linear;
}
.voyager-link span.copy{
position: absolute;
font-size: 16px;
left: 0px;
bottom: 70px;
line-height: 12px;
text-transform: uppercase;
text-align: center;
width: 100%;
}
h3 small{
font-size: 11px;
position: relative;
top: -3px;
left: 10px;
color: #999;
}
.collapsible{
margin-top:20px;
border:1px solid #f7f7f7;
border-radius:3px;
display:block;
}
.collapse-head{
border-bottom: 1px solid #f7f7f7;
border-top-right-radius: 3px;
padding:5px 15px;
display:block;
cursor:pointer;
background:#ffffff;
position:relative;
}
.collapse-head:after{
content:'';
clear:both;
display:block;
}
.collapse-head h4{
float:left;
}
.collapse-head i{
font-size: 16px;
position: absolute;
top: 13px;
right:15px;
float:right;
}
.collapse-content{
padding:15px;
background:#fcfcfc;
}
.collapse-content .row{
padding-bottom:0px;
margin-bottom:0px;
}
.collapse-content .col-md-4{
padding-right:0px;
margin-bottom:0px;
}
.collapse-content .col-md-4:nth-child(3){
padding-right:15px;
}
.voyager-link span.desc{
font-size:11px;
color:rgba(255, 255, 255, 0.8);
width:100%;
height:100%;
position:absolute;
text-align:center;
}
.voyager-angle-down{
display:none;
}
.voyager-link::after{
content:'';
position:absolute;
width:100%;
height:100%;
background: -moz-linear-gradient(-65deg, rgba(17,17,17,0.7) 0%, rgba(35,35,47,0.7) 50%, rgba(17,17,23,0.7) 51%, rgba(17,17,23,0.7) 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(-65deg, rgba(17,17,17,0.7) 0%,rgba(35,35,47,0.7) 50%,rgba(17,17,23,0.7) 51%,rgba(17,17,23,0.7) 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(155deg, rgba(17,17,17,0.7) 0%,rgba(35,35,47,0.7) 50%,rgba(17,17,23,0.7) 51%,rgba(17,17,23,0.7) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#b3111111', endColorstr='#b3111117',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
left:0px;
top:0px;
border-radius:3px;
}
#fonts ul{
list-style:none;
display:flex;
padding-left:10px;
flex-wrap:wrap;
justify-content:flex-start;
}
#fonts .icon{
float: left;
padding: 2px;
font-size: 20px;
padding-right: 10px;
position: absolute;
left: 0px;
}
#fonts li{
flex: 1;
max-width:212px;
padding: 10px;
padding-left: 30px;
position: relative;
}
#fonts .voyager-angle-down{
display:block;
}
#fonts h2{
font-size: 12px;
padding: 20px;
padding-top: 0px;
font-weight: bold;
padding-left:5px;
}
#fonts h2:nth-child(2){
padding-top:20px;
}
#fonts input{
border-radius: 3px;
border: 1px solid #f1f1f1;
padding: 3px 7px;
}
#logs .level .glyphicon{
float:left;
}
#logs table.dataTable thead th.sorting:after{
top:13px;
}
#logs table.dataTable thead .sorting_asc:after{
top:12px;
}
#logs .table-container{
margin-top:20px;
}
#logs .list-group{
margin-top:42px;
border: 1px solid #ececec;
border-right: 0px;
border-radius: 3px;
}
#logs .list-group-item{
background: #ffffff;
border: 0px;
border-radius: 0px;
font-size: 12px;
font-weight: normal;
color: #97999C;
border-right:1px solid #ececec;
}
.voyager #logs .table>thead>tr>th:first-child{
border-top-left-radius: 3px;
}
.voyager #logs .table>thead>tr>th:last-child{
border-top-right-radius: 3px;
}
#logs .list-group-item i{
position: relative;
top: 2px;
left: -3px;
}
#logs .list-group-item.llv-active{
background: #F9FCFF;
font-weight: bold;
position:relative;
}
#logs .list-group-item:hover{
background: #F9FCFF;
}
#logs .list-group-item.llv-active:after, #logs .list-group-item.llv-active:before, #logs .list-group-item:hover:after, #logs .list-group-item:hover:before{
content:'';
position:absolute;
width:100%;
height:1px;
left:0px;
background: rgb(241,241,241); /* Old browsers */
background: -moz-linear-gradient(left, rgba(241,241,241,1) 0%, rgba(255,255,255,1) 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(left, rgba(241,241,241,1) 0%,rgba(255,255,255,1) 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(to right, rgba(241,241,241,1) 0%,rgba(255,255,255,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f1f1f1', endColorstr='#ffffff',GradientType=1 ); /* IE6-9 */
}
#logs .list-group-item.llv-active:before, #logs .list-group-item:hover:before{
top:0px;
}
#logs .list-group-item.llv-active:after, #logs .list-group-item:hover:after{
bottom: 0px;
z-index: 9;
}
#command_lists{
display:flex;
flex-wrap:wrap;
}
#commands h3{
width: 100%;
clear: both;
margin-bottom: 20px;
}
#commands h3 i{
position: relative;
top: 3px;
}
#commands .command{
padding: 10px;
border: 1px solid #f1f1f1;
border-radius: 4px;
border-bottom: 2px solid #f5f5f5;
cursor:pointer;
transition:all 0.3s ease;
position:relative;
padding-top:30px;
padding-right: 52px;
flex:1;
min-width:275px;
margin:10px;
margin-left:0px;
}
#commands .command.more_args{
padding-bottom:40px;
}
#commands .command i{
position: absolute;
right: 4px;
top: -6px;
font-size: 45px;
}
#commands code{
color: #549DEA;
padding: 4px 7px;
font-weight: normal;
font-size: 12px;
background: #f3f7ff;
border: 0px;
position: absolute;
top: 0px;
left: 0px;
border-bottom-left-radius: 0px;
border-top-right-radius: 0px;
}
#commands .command:hover{
border-color:#eaeaea;
border-bottom-width:2px;
}
.cmd_form{
display:none;
position:absolute;
bottom: 0px;
left: 0px;
width: 100%;
}
.cmd_form input[type="text"], .cmd_form input[type="submit"]{
width:30%;
float:left;
margin: 0px;
font-size: 12px;
}
.cmd_form input[type="text"]{
line-height: 30px;
padding-top: 0px;
padding-bottom: 0px;
height: 30px;
border-top-right-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius:0px;
padding-left:5px;
font-size:12px;
width:70%;
}
.cmd_form .form-control.focus, .cmd_form .form-control:focus{
border-color:#eee;
}
.cmd_form input[type="submit"]{
border-top-right-radius: 0px;
border-bottom-left-radius: 0px;
border-top-left-radius:0px;
font-size: 10px;
padding-left: 7px;
padding-right: 7px;
height: 30px;
}
#commands pre{
background:#323A42;
color:#fff;
width:100%;
margin:10px;
margin-left:0px;
padding: 15px;
padding-top: 0px;
padding-bottom: 0px;
position:relative;
}
#commands .close-output{
position:absolute;
right:15px;
top:15px;
color:#ccc;
cursor:pointer;
padding: 5px 14px;
background: rgba(0, 0, 0, 0.2);
border-radius: 25px;
transition:all 0.3s ease;
}
#commands .close-output:hover{
color:#fff;
background: rgba(0, 0, 0, 0.3);
}
#commands pre i:before{
position:relative;
top:3px;
right:5px;
}
#commands pre .art_out{
width: 100%;
display: block;
color: #98cb00;
margin-bottom:10px;
}
</style> | php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/compass/includes/logs.blade.php | resources/views/compass/includes/logs.blade.php |
<div class="col-sm-3 col-md-3 sidebar">
<h3><i class="voyager-logbook"></i> {{ __('voyager::compass.logs.title') }} <small>{{ __('voyager::compass.logs.text') }}.</small></h3>
<div class="list-group">
@foreach($files as $file)
<a href="?log={{ base64_encode($file) }}"
class="list-group-item @if ($current_file == $file) llv-active @endif">
<i class="voyager-file-text"></i> {{$file}}
</a>
@endforeach
</div>
</div>
<div class="col-sm-9 col-md-9 table-container">
@if ($logs === null)
<div>
{{ __('voyager::compass.logs.file_too_big') }}
</div>
@else
<table id="table-log" class="table table-striped">
<thead>
<tr>
<th>{{ __('voyager::compass.logs.level') }}</th>
<th>{{ __('voyager::compass.logs.context') }}</th>
<th>{{ __('voyager::compass.logs.date') }}</th>
<th>{{ __('voyager::compass.logs.content') }}</th>
</tr>
</thead>
<tbody>
@foreach($logs as $key => $log)
<tr data-display="stack{{{$key}}}">
<td class="text-{{{$log['level_class']}}} level"><span class="glyphicon glyphicon-{{{$log['level_img']}}}-sign"
aria-hidden="true"></span> {{$log['level']}}</td>
<td class="text">{{$log['context']}}</td>
<td class="date">{{{$log['date']}}}</td>
<td class="text">
@if ($log['stack']) <a class="pull-right expand btn btn-default btn-xs"
data-display="stack{{{$key}}}"><span
class="glyphicon glyphicon-search"></span></a>@endif
{{{$log['text']}}}
@if (isset($log['in_file'])) <br/>{{{$log['in_file']}}}@endif
@if ($log['stack'])
<div class="stack" id="stack{{{$key}}}"
style="display: none; white-space: pre-wrap;">{{{ trim($log['stack']) }}}
</div>@endif
</td>
</tr>
@endforeach
</tbody>
</table>
@endif
<div>
@if($current_file)
<a href="?download={{ base64_encode($current_file) }}"><span class="glyphicon glyphicon-download-alt"></span>
{{ __('voyager::compass.logs.download_file') }}</a>
-
<a id="delete-log" href="?del={{ base64_encode($current_file) }}"><span
class="glyphicon glyphicon-trash"></span> {{ __('voyager::compass.logs.delete_file') }}</a>
@if(count($files) > 1)
-
<a id="delete-all-log" href="?delall=true"><span class="glyphicon glyphicon-trash"></span> {{ __('voyager::compass.logs.delete_all_files') }}</a>
@endif
@endif
</div>
</div>
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | false |
thedevdojo/voyager | https://github.com/thedevdojo/voyager/blob/7e7e0f4f0e115d2d9e0481a86153a1ceff194c00/resources/views/compass/includes/fonts.blade.php | resources/views/compass/includes/fonts.blade.php | <h2>{{ __('voyager::compass.fonts.font_class') }}</h2>
<ul class="glyphs css-mapping">
<li>
<div class="icon voyager-bread"></div>
<input type="text" readonly="readonly" value="voyager-bread">
</li>
<li>
<div class="icon voyager-helm"></div>
<input type="text" readonly="readonly" value="voyager-helm">
</li>
<li>
<div class="icon voyager-play"></div>
<input type="text" readonly="readonly" value="voyager-play">
</li>
<li>
<div class="icon voyager-activity"></div>
<input type="text" readonly="readonly" value="voyager-activity">
</li>
<li>
<div class="icon voyager-company"></div>
<input type="text" readonly="readonly" value="voyager-company">
</li>
<li>
<div class="icon voyager-file-text"></div>
<input type="text" readonly="readonly" value="voyager-file-text">
</li>
<li>
<div class="icon voyager-folder"></div>
<input type="text" readonly="readonly" value="voyager-folder">
</li>
<li>
<div class="icon voyager-paw"></div>
<input type="text" readonly="readonly" value="voyager-paw">
</li>
<li>
<div class="icon voyager-sort"></div>
<input type="text" readonly="readonly" value="voyager-sort">
</li>
<li>
<div class="icon voyager-sort-asc"></div>
<input type="text" readonly="readonly" value="voyager-sort-asc">
</li>
<li>
<div class="icon voyager-sort-desc"></div>
<input type="text" readonly="readonly" value="voyager-sort-desc">
</li>
<li>
<div class="icon voyager-handle"></div>
<input type="text" readonly="readonly" value="voyager-handle">
</li>
<li>
<div class="icon voyager-hammer"></div>
<input type="text" readonly="readonly" value="voyager-hammer">
</li>
<li>
<div class="icon voyager-images"></div>
<input type="text" readonly="readonly" value="voyager-images">
</li>
<li>
<div class="icon voyager-categories"></div>
<input type="text" readonly="readonly" value="voyager-categories">
</li>
<li>
<div class="icon voyager-group"></div>
<input type="text" readonly="readonly" value="voyager-group">
</li>
<li>
<div class="icon voyager-person"></div>
<input type="text" readonly="readonly" value="voyager-person">
</li>
<li>
<div class="icon voyager-people"></div>
<input type="text" readonly="readonly" value="voyager-people">
</li>
<li>
<div class="icon voyager-power"></div>
<input type="text" readonly="readonly" value="voyager-power">
</li>
<li>
<div class="icon voyager-tools"></div>
<input type="text" readonly="readonly" value="voyager-tools">
</li>
<li>
<div class="icon voyager-anchor"></div>
<input type="text" readonly="readonly" value="voyager-anchor">
</li>
<li>
<div class="icon voyager-double-down"></div>
<input type="text" readonly="readonly" value="voyager-double-down">
</li>
<li>
<div class="icon voyager-double-up"></div>
<input type="text" readonly="readonly" value="voyager-double-up">
</li>
<li>
<div class="icon voyager-double-left"></div>
<input type="text" readonly="readonly" value="voyager-double-left">
</li>
<li>
<div class="icon voyager-double-right"></div>
<input type="text" readonly="readonly" value="voyager-double-right">
</li>
<li>
<div class="icon voyager-window-list"></div>
<input type="text" readonly="readonly" value="voyager-window-list">
</li>
<li>
<div class="icon voyager-x"></div>
<input type="text" readonly="readonly" value="voyager-x">
</li>
<li>
<div class="icon voyager-dot"></div>
<input type="text" readonly="readonly" value="voyager-dot">
</li>
<li>
<div class="icon voyager-dot-2"></div>
<input type="text" readonly="readonly" value="voyager-dot-2">
</li>
<li>
<div class="icon voyager-dot-3"></div>
<input type="text" readonly="readonly" value="voyager-dot-3">
</li>
<li>
<div class="icon voyager-list"></div>
<input type="text" readonly="readonly" value="voyager-list">
</li>
<li>
<div class="icon voyager-list-add"></div>
<input type="text" readonly="readonly" value="voyager-list-add">
</li>
<li>
<div class="icon voyager-pie-chart"></div>
<input type="text" readonly="readonly" value="voyager-pie-chart">
</li>
<li>
<div class="icon voyager-watch"></div>
<input type="text" readonly="readonly" value="voyager-watch">
</li>
<li>
<div class="icon voyager-data"></div>
<input type="text" readonly="readonly" value="voyager-data">
</li>
<li>
<div class="icon voyager-music"></div>
<input type="text" readonly="readonly" value="voyager-music">
</li>
<li>
<div class="icon voyager-settings"></div>
<input type="text" readonly="readonly" value="voyager-settings">
</li>
<li>
<div class="icon voyager-video"></div>
<input type="text" readonly="readonly" value="voyager-video">
</li>
<li>
<div class="icon voyager-trash"></div>
<input type="text" readonly="readonly" value="voyager-trash">
</li>
<li>
<div class="icon voyager-tv"></div>
<input type="text" readonly="readonly" value="voyager-tv">
</li>
<li>
<div class="icon voyager-lock"></div>
<input type="text" readonly="readonly" value="voyager-lock">
</li>
<li>
<div class="icon voyager-news"></div>
<input type="text" readonly="readonly" value="voyager-news">
</li>
<li>
<div class="icon voyager-bag"></div>
<input type="text" readonly="readonly" value="voyager-bag">
</li>
<li>
<div class="icon voyager-upload"></div>
<input type="text" readonly="readonly" value="voyager-upload">
</li>
<li>
<div class="icon voyager-refresh"></div>
<input type="text" readonly="readonly" value="voyager-refresh">
</li>
<li>
<div class="icon voyager-character"></div>
<input type="text" readonly="readonly" value="voyager-character">
</li>
<li>
<div class="icon voyager-move"></div>
<input type="text" readonly="readonly" value="voyager-move">
</li>
<li>
<div class="icon voyager-paypal"></div>
<input type="text" readonly="readonly" value="voyager-paypal">
</li>
<li>
<div class="icon voyager-paper-plane"></div>
<input type="text" readonly="readonly" value="voyager-paper-plane">
</li>
<li>
<div class="icon voyager-ticket"></div>
<input type="text" readonly="readonly" value="voyager-ticket">
</li>
<li>
<div class="icon voyager-youtube-play"></div>
<input type="text" readonly="readonly" value="voyager-youtube-play">
</li>
<li>
<div class="icon voyager-boat"></div>
<input type="text" readonly="readonly" value="voyager-boat">
</li>
<li>
<div class="icon voyager-check"></div>
<input type="text" readonly="readonly" value="voyager-check">
</li>
<li>
<div class="icon voyager-alarm-clock"></div>
<input type="text" readonly="readonly" value="voyager-alarm-clock">
</li>
<li>
<div class="icon voyager-controller"></div>
<input type="text" readonly="readonly" value="voyager-controller">
</li>
<li>
<div class="icon voyager-pizza"></div>
<input type="text" readonly="readonly" value="voyager-pizza">
</li>
<li>
<div class="icon voyager-backpack"></div>
<input type="text" readonly="readonly" value="voyager-backpack">
</li>
<li>
<div class="icon voyager-barbeque"></div>
<input type="text" readonly="readonly" value="voyager-barbeque">
</li>
<li>
<div class="icon voyager-bomb"></div>
<input type="text" readonly="readonly" value="voyager-bomb">
</li>
<li>
<div class="icon voyager-book-download"></div>
<input type="text" readonly="readonly" value="voyager-book-download">
</li>
<li>
<div class="icon voyager-browser"></div>
<input type="text" readonly="readonly" value="voyager-browser">
</li>
<li>
<div class="icon voyager-brush"></div>
<input type="text" readonly="readonly" value="voyager-brush">
</li>
<li>
<div class="icon voyager-bubble-hear"></div>
<input type="text" readonly="readonly" value="voyager-bubble-hear">
</li>
<li>
<div class="icon voyager-polaroid"></div>
<input type="text" readonly="readonly" value="voyager-polaroid">
</li>
<li>
<div class="icon voyager-crop"></div>
<input type="text" readonly="readonly" value="voyager-crop">
</li>
<li>
<div class="icon voyager-dashboard"></div>
<input type="text" readonly="readonly" value="voyager-dashboard">
</li>
<li>
<div class="icon voyager-hotdog"></div>
<input type="text" readonly="readonly" value="voyager-hotdog">
</li>
<li>
<div class="icon voyager-laptop"></div>
<input type="text" readonly="readonly" value="voyager-laptop">
</li>
<li>
<div class="icon voyager-paint-bucket"></div>
<input type="text" readonly="readonly" value="voyager-paint-bucket">
</li>
<li>
<div class="icon voyager-photo"></div>
<input type="text" readonly="readonly" value="voyager-photo">
</li>
<li>
<div class="icon voyager-photos"></div>
<input type="text" readonly="readonly" value="voyager-photos">
</li>
<li>
<div class="icon voyager-receipt"></div>
<input type="text" readonly="readonly" value="voyager-receipt">
</li>
<li>
<div class="icon voyager-buy"></div>
<input type="text" readonly="readonly" value="voyager-buy">
</li>
<li>
<div class="icon voyager-lightbulb"></div>
<input type="text" readonly="readonly" value="voyager-lightbulb">
</li>
<li>
<div class="icon voyager-archive"></div>
<input type="text" readonly="readonly" value="voyager-archive">
</li>
<li>
<div class="icon voyager-paperclip"></div>
<input type="text" readonly="readonly" value="voyager-paperclip">
</li>
<li>
<div class="icon voyager-warning"></div>
<input type="text" readonly="readonly" value="voyager-warning">
</li>
<li>
<div class="icon voyager-basket"></div>
<input type="text" readonly="readonly" value="voyager-basket">
</li>
<li>
<div class="icon voyager-bell"></div>
<input type="text" readonly="readonly" value="voyager-bell">
</li>
<li>
<div class="icon voyager-book"></div>
<input type="text" readonly="readonly" value="voyager-book">
</li>
<li>
<div class="icon voyager-chat"></div>
<input type="text" readonly="readonly" value="voyager-chat">
</li>
<li>
<div class="icon voyager-down-circled"></div>
<input type="text" readonly="readonly" value="voyager-down-circled">
</li>
<li>
<div class="icon voyager-location"></div>
<input type="text" readonly="readonly" value="voyager-location">
</li>
<li>
<div class="icon voyager-forward"></div>
<input type="text" readonly="readonly" value="voyager-forward">
</li>
<li>
<div class="icon voyager-flashlight"></div>
<input type="text" readonly="readonly" value="voyager-flashlight">
</li>
<li>
<div class="icon voyager-trophy"></div>
<input type="text" readonly="readonly" value="voyager-trophy">
</li>
<li>
<div class="icon voyager-diamond"></div>
<input type="text" readonly="readonly" value="voyager-diamond">
</li>
<li>
<div class="icon voyager-credit-cards"></div>
<input type="text" readonly="readonly" value="voyager-credit-cards">
</li>
<li>
<div class="icon voyager-shop"></div>
<input type="text" readonly="readonly" value="voyager-shop">
</li>
<li>
<div class="icon voyager-sound"></div>
<input type="text" readonly="readonly" value="voyager-sound">
</li>
<li>
<div class="icon voyager-study"></div>
<input type="text" readonly="readonly" value="voyager-study">
</li>
<li>
<div class="icon voyager-pen"></div>
<input type="text" readonly="readonly" value="voyager-pen">
</li>
<li>
<div class="icon voyager-params"></div>
<input type="text" readonly="readonly" value="voyager-params">
</li>
<li>
<div class="icon voyager-fire"></div>
<input type="text" readonly="readonly" value="voyager-fire">
</li>
<li>
<div class="icon voyager-dollar"></div>
<input type="text" readonly="readonly" value="voyager-dollar">
</li>
<li>
<div class="icon voyager-bulb"></div>
<input type="text" readonly="readonly" value="voyager-bulb">
</li>
<li>
<div class="icon voyager-lab"></div>
<input type="text" readonly="readonly" value="voyager-lab">
</li>
<li>
<div class="icon voyager-cup"></div>
<input type="text" readonly="readonly" value="voyager-cup">
</li>
<li>
<div class="icon voyager-megaphone"></div>
<input type="text" readonly="readonly" value="voyager-megaphone">
</li>
<li>
<div class="icon voyager-heart"></div>
<input type="text" readonly="readonly" value="voyager-heart">
</li>
<li>
<div class="icon voyager-bubble"></div>
<input type="text" readonly="readonly" value="voyager-bubble">
</li>
<li>
<div class="icon voyager-search"></div>
<input type="text" readonly="readonly" value="voyager-search">
</li>
<li>
<div class="icon voyager-tag"></div>
<input type="text" readonly="readonly" value="voyager-tag">
</li>
<li>
<div class="icon voyager-world"></div>
<input type="text" readonly="readonly" value="voyager-world">
</li>
<li>
<div class="icon voyager-camera"></div>
<input type="text" readonly="readonly" value="voyager-camera">
</li>
<li>
<div class="icon voyager-calendar"></div>
<input type="text" readonly="readonly" value="voyager-calendar">
</li>
<li>
<div class="icon voyager-mail"></div>
<input type="text" readonly="readonly" value="voyager-mail">
</li>
<li>
<div class="icon voyager-phone"></div>
<input type="text" readonly="readonly" value="voyager-phone">
</li>
<li>
<div class="icon voyager-star"></div>
<input type="text" readonly="readonly" value="voyager-star">
</li>
<li>
<div class="icon voyager-star-half"></div>
<input type="text" readonly="readonly" value="voyager-star-half">
</li>
<li>
<div class="icon voyager-star-half-1"></div>
<input type="text" readonly="readonly" value="voyager-star-half-1">
</li>
<li>
<div class="icon voyager-star-two"></div>
<input type="text" readonly="readonly" value="voyager-star-two">
</li>
<li>
<div class="icon voyager-medal-rank-star"></div>
<input type="text" readonly="readonly" value="voyager-medal-rank-star">
</li>
<li>
<div class="icon voyager-facebook"></div>
<input type="text" readonly="readonly" value="voyager-facebook">
</li>
<li>
<div class="icon voyager-google-plus"></div>
<input type="text" readonly="readonly" value="voyager-google-plus">
</li>
<li>
<div class="icon voyager-twitter"></div>
<input type="text" readonly="readonly" value="voyager-twitter">
</li>
<li>
<div class="icon voyager-github"></div>
<input type="text" readonly="readonly" value="voyager-github">
</li>
<li>
<div class="icon voyager-code"></div>
<input type="text" readonly="readonly" value="voyager-code">
</li>
<li>
<div class="icon voyager-pie-graph"></div>
<input type="text" readonly="readonly" value="voyager-pie-graph">
</li>
<li>
<div class="icon voyager-javascript"></div>
<input type="text" readonly="readonly" value="voyager-javascript">
</li>
<li>
<div class="icon voyager-wand"></div>
<input type="text" readonly="readonly" value="voyager-wand">
</li>
<li>
<div class="icon voyager-wineglass"></div>
<input type="text" readonly="readonly" value="voyager-wineglass">
</li>
<li>
<div class="icon voyager-milestone"></div>
<input type="text" readonly="readonly" value="voyager-milestone">
</li>
<li>
<div class="icon voyager-terminal"></div>
<input type="text" readonly="readonly" value="voyager-terminal">
</li>
<li>
<div class="icon voyager-plug"></div>
<input type="text" readonly="readonly" value="voyager-plug">
</li>
<li>
<div class="icon voyager-gift"></div>
<input type="text" readonly="readonly" value="voyager-gift">
</li>
<li>
<div class="icon voyager-markdown"></div>
<input type="text" readonly="readonly" value="voyager-markdown">
</li>
<li>
<div class="icon voyager-beer"></div>
<input type="text" readonly="readonly" value="voyager-beer">
</li>
<li>
<div class="icon voyager-credit-card"></div>
<input type="text" readonly="readonly" value="voyager-credit-card">
</li>
<li>
<div class="icon voyager-bolt"></div>
<input type="text" readonly="readonly" value="voyager-bolt">
</li>
<li>
<div class="icon voyager-external"></div>
<input type="text" readonly="readonly" value="voyager-external">
</li>
<li>
<div class="icon voyager-magnet"></div>
<input type="text" readonly="readonly" value="voyager-magnet">
</li>
<li>
<div class="icon voyager-certificate"></div>
<input type="text" readonly="readonly" value="voyager-certificate">
</li>
<li>
<div class="icon voyager-cloud-download"></div>
<input type="text" readonly="readonly" value="voyager-cloud-download">
</li>
<li>
<div class="icon voyager-campfire"></div>
<input type="text" readonly="readonly" value="voyager-campfire">
</li>
<li>
<div class="icon voyager-new"></div>
<input type="text" readonly="readonly" value="voyager-new">
</li>
<li>
<div class="icon voyager-skull"></div>
<input type="text" readonly="readonly" value="voyager-skull">
</li>
<li>
<div class="icon voyager-telephone"></div>
<input type="text" readonly="readonly" value="voyager-telephone">
</li>
<li>
<div class="icon voyager-trees"></div>
<input type="text" readonly="readonly" value="voyager-trees">
</li>
<li>
<div class="icon voyager-bar-chart"></div>
<input type="text" readonly="readonly" value="voyager-bar-chart">
</li>
<li>
<div class="icon voyager-check-circle"></div>
<input type="text" readonly="readonly" value="voyager-check-circle">
</li>
<li>
<div class="icon voyager-exclamation"></div>
<input type="text" readonly="readonly" value="voyager-exclamation">
</li>
<li>
<div class="icon voyager-font"></div>
<input type="text" readonly="readonly" value="voyager-font">
</li>
<li>
<div class="icon voyager-puzzle"></div>
<input type="text" readonly="readonly" value="voyager-puzzle">
</li>
<li>
<div class="icon voyager-smile"></div>
<input type="text" readonly="readonly" value="voyager-smile">
</li>
<li>
<div class="icon voyager-frown"></div>
<input type="text" readonly="readonly" value="voyager-frown">
</li>
<li>
<div class="icon voyager-meh"></div>
<input type="text" readonly="readonly" value="voyager-meh">
</li>
<li>
<div class="icon voyager-leaf"></div>
<input type="text" readonly="readonly" value="voyager-leaf">
</li>
<li>
<div class="icon voyager-info-circled"></div>
<input type="text" readonly="readonly" value="voyager-info-circled">
</li>
<li>
<div class="icon voyager-underline"></div>
<input type="text" readonly="readonly" value="voyager-underline">
</li>
<li>
<div class="icon voyager-wallet"></div>
<input type="text" readonly="readonly" value="voyager-wallet">
</li>
<li>
<div class="icon voyager-truck"></div>
<input type="text" readonly="readonly" value="voyager-truck">
</li>
<li>
<div class="icon voyager-eye"></div>
<input type="text" readonly="readonly" value="voyager-eye">
</li>
<li>
<div class="icon voyager-sun"></div>
<input type="text" readonly="readonly" value="voyager-sun">
</li>
<li>
<div class="icon voyager-barbell"></div>
<input type="text" readonly="readonly" value="voyager-barbell">
</li>
<li>
<div class="icon voyager-bookmark"></div>
<input type="text" readonly="readonly" value="voyager-bookmark">
</li>
<li>
<div class="icon voyager-volume-up"></div>
<input type="text" readonly="readonly" value="voyager-volume-up">
</li>
<li>
<div class="icon voyager-volume-down"></div>
<input type="text" readonly="readonly" value="voyager-volume-down">
</li>
<li>
<div class="icon voyager-wifi"></div>
<input type="text" readonly="readonly" value="voyager-wifi">
</li>
<li>
<div class="icon voyager-pause"></div>
<input type="text" readonly="readonly" value="voyager-pause">
</li>
<li>
<div class="icon voyager-resize-full"></div>
<input type="text" readonly="readonly" value="voyager-resize-full">
</li>
<li>
<div class="icon voyager-resize-small"></div>
<input type="text" readonly="readonly" value="voyager-resize-small">
</li>
<li>
<div class="icon voyager-download"></div>
<input type="text" readonly="readonly" value="voyager-download">
</li>
<li>
<div class="icon voyager-droplet"></div>
<input type="text" readonly="readonly" value="voyager-droplet">
</li>
<li>
<div class="icon voyager-umbrella"></div>
<input type="text" readonly="readonly" value="voyager-umbrella">
</li>
<li>
<div class="icon voyager-harddrive"></div>
<input type="text" readonly="readonly" value="voyager-harddrive">
</li>
<li>
<div class="icon voyager-css3"></div>
<input type="text" readonly="readonly" value="voyager-css3">
</li>
<li>
<div class="icon voyager-html5"></div>
<input type="text" readonly="readonly" value="voyager-html5">
</li>
<li>
<div class="icon voyager-tree"></div>
<input type="text" readonly="readonly" value="voyager-tree">
</li>
<li>
<div class="icon voyager-file-code"></div>
<input type="text" readonly="readonly" value="voyager-file-code">
</li>
<li>
<div class="icon voyager-bug"></div>
<input type="text" readonly="readonly" value="voyager-bug">
</li>
<li>
<div class="icon voyager-rocket"></div>
<input type="text" readonly="readonly" value="voyager-rocket">
</li>
<li>
<div class="icon voyager-key"></div>
<input type="text" readonly="readonly" value="voyager-key">
</li>
<li>
<div class="icon voyager-question"></div>
<input type="text" readonly="readonly" value="voyager-question">
</li>
<li>
<div class="icon voyager-cursor"></div>
<input type="text" readonly="readonly" value="voyager-cursor">
</li>
<li>
<div class="icon voyager-lifebuoy"></div>
<input type="text" readonly="readonly" value="voyager-lifebuoy">
</li>
<li>
<div class="icon voyager-thumbs-up"></div>
<input type="text" readonly="readonly" value="voyager-thumbs-up">
</li>
<li>
<div class="icon voyager-thumb-tack"></div>
<input type="text" readonly="readonly" value="voyager-thumb-tack">
</li>
<li>
<div class="icon voyager-edit"></div>
<input type="text" readonly="readonly" value="voyager-edit">
</li>
<li>
<div class="icon voyager-angle-down"></div>
<input type="text" readonly="readonly" value="voyager-angle-down">
</li>
<li>
<div class="icon voyager-angle-left"></div>
<input type="text" readonly="readonly" value="voyager-angle-left">
</li>
<li>
<div class="icon voyager-angle-right"></div>
<input type="text" readonly="readonly" value="voyager-angle-right">
</li>
<li>
<div class="icon voyager-angle-up"></div>
<input type="text" readonly="readonly" value="voyager-angle-up">
</li>
<li>
<div class="icon voyager-home"></div>
<input type="text" readonly="readonly" value="voyager-home">
</li>
<li>
<div class="icon voyager-pirate-swords"></div>
<input type="text" readonly="readonly" value="voyager-pirate-swords">
</li>
<li>
<div class="icon voyager-pirate"></div>
<input type="text" readonly="readonly" value="voyager-pirate">
</li>
<li>
<div class="icon voyager-rum"></div>
<input type="text" readonly="readonly" value="voyager-rum">
</li>
<li>
<div class="icon voyager-cannon"></div>
<input type="text" readonly="readonly" value="voyager-cannon">
</li>
<li>
<div class="icon voyager-hook"></div>
<input type="text" readonly="readonly" value="voyager-hook">
</li>
<li>
<div class="icon voyager-kraken"></div>
<input type="text" readonly="readonly" value="voyager-kraken">
</li>
<li>
<div class="icon voyager-lighthouse"></div>
<input type="text" readonly="readonly" value="voyager-lighthouse">
</li>
<li>
<div class="icon voyager-pirate-hat"></div>
<input type="text" readonly="readonly" value="voyager-pirate-hat">
</li>
<li>
<div class="icon voyager-rum-1"></div>
<input type="text" readonly="readonly" value="voyager-rum-1">
</li>
<li>
<div class="icon voyager-ship"></div>
<input type="text" readonly="readonly" value="voyager-ship">
</li>
<li>
<div class="icon voyager-treasure"></div>
<input type="text" readonly="readonly" value="voyager-treasure">
</li>
<li>
<div class="icon voyager-treasure-open"></div>
<input type="text" readonly="readonly" value="voyager-treasure-open">
</li>
<li>
<div class="icon voyager-whale"></div>
<input type="text" readonly="readonly" value="voyager-whale">
</li>
<li>
<div class="icon voyager-compass"></div>
<input type="text" readonly="readonly" value="voyager-compass">
</li>
<li>
<div class="icon voyager-logbook"></div>
<input type="text" readonly="readonly" value="voyager-logbook">
</li>
<li>
<div class="icon voyager-plus"></div>
<input type="text" readonly="readonly" value="voyager-plus">
</li>
<li>
<div class="icon voyager-documentation"></div>
<input type="text" readonly="readonly" value="voyager-documentation">
</li>
<li>
<div class="icon voyager-belt"></div>
<input type="text" readonly="readonly" value="voyager-belt">
</li>
<li>
<div class="icon voyager-zoom-in"></div>
<input type="text" readonly="readonly" value="voyager-zoom-in">
</li>
<li>
<div class="icon voyager-zoom-out"></div>
<input type="text" readonly="readonly" value="voyager-zoom-out">
</li>
<li>
<div class="icon voyager-scissors"></div>
<input type="text" readonly="readonly" value="voyager-scissors">
</li>
<li>
<div class="icon voyager-github-icon"></div>
<input type="text" readonly="readonly" value="voyager-github-icon">
</li>
</ul>
<h2>{{ __('voyager::compass.fonts.font_character') }}</h2>
<ul class="glyphs character-mapping">
<li>
<div data-icon="a" class="icon"></div>
<input type="text" readonly="readonly" value="a">
</li>
<li>
<div data-icon="b" class="icon"></div>
<input type="text" readonly="readonly" value="b">
</li>
<li>
<div data-icon="c" class="icon"></div>
<input type="text" readonly="readonly" value="c">
</li>
<li>
<div data-icon="d" class="icon"></div>
<input type="text" readonly="readonly" value="d">
</li>
<li>
<div data-icon="e" class="icon"></div>
<input type="text" readonly="readonly" value="e">
</li>
<li>
<div data-icon="f" class="icon"></div>
<input type="text" readonly="readonly" value="f">
</li>
<li>
<div data-icon="g" class="icon"></div>
<input type="text" readonly="readonly" value="g">
</li>
<li>
<div data-icon="h" class="icon"></div>
<input type="text" readonly="readonly" value="h">
</li>
<li>
<div data-icon="o" class="icon"></div>
<input type="text" readonly="readonly" value="o">
</li>
<li>
<div data-icon="p" class="icon"></div>
<input type="text" readonly="readonly" value="p">
</li>
<li>
<div data-icon="q" class="icon"></div>
<input type="text" readonly="readonly" value="q">
</li>
<li>
<div data-icon="m" class="icon"></div>
<input type="text" readonly="readonly" value="m">
</li>
<li>
<div data-icon="n" class="icon"></div>
<input type="text" readonly="readonly" value="n">
</li>
<li>
<div data-icon="i" class="icon"></div>
<input type="text" readonly="readonly" value="i">
</li>
<li>
<div data-icon="j" class="icon"></div>
<input type="text" readonly="readonly" value="j">
</li>
<li>
<div data-icon="k" class="icon"></div>
<input type="text" readonly="readonly" value="k">
</li>
<li>
<div data-icon="s" class="icon"></div>
<input type="text" readonly="readonly" value="s">
</li>
<li>
<div data-icon="t" class="icon"></div>
<input type="text" readonly="readonly" value="t">
</li>
<li>
<div data-icon="u" class="icon"></div>
<input type="text" readonly="readonly" value="u">
</li>
<li>
<div data-icon="v" class="icon"></div>
<input type="text" readonly="readonly" value="v">
</li>
<li>
<div data-icon="w" class="icon"></div>
<input type="text" readonly="readonly" value="w">
</li>
<li>
<div data-icon="x" class="icon"></div>
<input type="text" readonly="readonly" value="x">
</li>
<li>
<div data-icon="y" class="icon"></div>
<input type="text" readonly="readonly" value="y">
</li>
<li>
<div data-icon="z" class="icon"></div>
<input type="text" readonly="readonly" value="z">
</li>
<li>
<div data-icon="A" class="icon"></div>
<input type="text" readonly="readonly" value="A">
</li>
<li>
<div data-icon="B" class="icon"></div>
<input type="text" readonly="readonly" value="B">
</li>
<li>
<div data-icon="C" class="icon"></div>
<input type="text" readonly="readonly" value="C">
</li>
<li>
<div data-icon="D" class="icon"></div>
<input type="text" readonly="readonly" value="D">
</li>
<li>
<div data-icon="E" class="icon"></div>
<input type="text" readonly="readonly" value="E">
</li>
<li>
<div data-icon="F" class="icon"></div>
<input type="text" readonly="readonly" value="F">
</li>
<li>
<div data-icon="G" class="icon"></div>
| php | MIT | 7e7e0f4f0e115d2d9e0481a86153a1ceff194c00 | 2026-01-04T15:03:42.463743Z | true |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Token.php | src/Token.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth;
use Tymon\JWTAuth\Validators\TokenValidator;
class Token
{
/**
* @var string
*/
private $value;
/**
* Create a new JSON Web Token.
*
* @param string $value
* @return void
*/
public function __construct($value)
{
$this->value = (string) (new TokenValidator)->check($value);
}
/**
* Get the token.
*
* @return string
*/
public function get()
{
return $this->value;
}
/**
* Get the token when casting to string.
*
* @return string
*/
public function __toString()
{
return $this->get();
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Payload.php | src/Payload.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth;
use ArrayAccess;
use BadMethodCallException;
use Countable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use JsonSerializable;
use Tymon\JWTAuth\Claims\Claim;
use Tymon\JWTAuth\Claims\Collection;
use Tymon\JWTAuth\Exceptions\PayloadException;
use Tymon\JWTAuth\Validators\PayloadValidator;
class Payload implements ArrayAccess, Arrayable, Countable, Jsonable, JsonSerializable
{
/**
* The collection of claims.
*
* @var \Tymon\JWTAuth\Claims\Collection
*/
private $claims;
/**
* Build the Payload.
*
* @param \Tymon\JWTAuth\Claims\Collection $claims
* @param \Tymon\JWTAuth\Validators\PayloadValidator $validator
* @param bool $refreshFlow
* @return void
*/
public function __construct(Collection $claims, PayloadValidator $validator, $refreshFlow = false)
{
$this->claims = $validator->setRefreshFlow($refreshFlow)->check($claims);
}
/**
* Get the array of claim instances.
*
* @return \Tymon\JWTAuth\Claims\Collection
*/
public function getClaims()
{
return $this->claims;
}
/**
* Checks if a payload matches some expected values.
*
* @param array $values
* @param bool $strict
* @return bool
*/
public function matches(array $values, $strict = false)
{
if (empty($values)) {
return false;
}
$claims = $this->getClaims();
foreach ($values as $key => $value) {
if (! $claims->has($key) || ! $claims->get($key)->matches($value, $strict)) {
return false;
}
}
return true;
}
/**
* Checks if a payload strictly matches some expected values.
*
* @param array $values
* @return bool
*/
public function matchesStrict(array $values)
{
return $this->matches($values, true);
}
/**
* Get the payload.
*
* @param mixed $claim
* @return mixed
*/
public function get($claim = null)
{
$claim = value($claim);
if ($claim !== null) {
if (is_array($claim)) {
return array_map([$this, 'get'], $claim);
}
return Arr::get($this->toArray(), $claim);
}
return $this->toArray();
}
/**
* Get the underlying Claim instance.
*
* @param string $claim
* @return \Tymon\JWTAuth\Claims\Claim
*/
public function getInternal($claim)
{
return $this->claims->getByClaimName($claim);
}
/**
* Determine whether the payload has the claim (by instance).
*
* @param \Tymon\JWTAuth\Claims\Claim $claim
* @return bool
*/
public function has(Claim $claim)
{
return $this->claims->has($claim->getName());
}
/**
* Determine whether the payload has the claim (by key).
*
* @param string $claim
* @return bool
*/
public function hasKey($claim)
{
return $this->offsetExists($claim);
}
/**
* Get the array of claims.
*
* @return array
*/
public function toArray()
{
return $this->claims->toPlainArray();
}
/**
* Convert the object into something JSON serializable.
*
* @return array
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->toArray();
}
/**
* Get the payload as JSON.
*
* @param int $options
* @return string
*/
public function toJson($options = JSON_UNESCAPED_SLASHES)
{
return json_encode($this->toArray(), $options);
}
/**
* Get the payload as a string.
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
/**
* Determine if an item exists at an offset.
*
* @param mixed $key
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($key)
{
return Arr::has($this->toArray(), $key);
}
/**
* Get an item at a given offset.
*
* @param mixed $key
* @return mixed
*/
#[\ReturnTypeWillChange]
public function offsetGet($key)
{
return Arr::get($this->toArray(), $key);
}
/**
* Don't allow changing the payload as it should be immutable.
*
* @param mixed $key
* @param mixed $value
*
* @throws \Tymon\JWTAuth\Exceptions\PayloadException
*/
#[\ReturnTypeWillChange]
public function offsetSet($key, $value)
{
throw new PayloadException('The payload is immutable');
}
/**
* Don't allow changing the payload as it should be immutable.
*
* @param string $key
* @return void
*
* @throws \Tymon\JWTAuth\Exceptions\PayloadException
*/
#[\ReturnTypeWillChange]
public function offsetUnset($key)
{
throw new PayloadException('The payload is immutable');
}
/**
* Count the number of claims.
*
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
{
return count($this->toArray());
}
/**
* Invoke the Payload as a callable function.
*
* @param mixed $claim
* @return mixed
*/
public function __invoke($claim = null)
{
return $this->get($claim);
}
/**
* Magically get a claim value.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
if (preg_match('/get(.+)\b/i', $method, $matches)) {
foreach ($this->claims as $claim) {
if (get_class($claim) === 'Tymon\\JWTAuth\\Claims\\'.$matches[1]) {
return $claim->getValue();
}
}
}
throw new BadMethodCallException(sprintf('The claim [%s] does not exist on the payload.', Str::after($method, 'get')));
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/JWTGuard.php | src/JWTGuard.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth;
use BadMethodCallException;
use Illuminate\Auth\GuardHelpers;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Traits\Macroable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\UserNotDefinedException;
class JWTGuard implements Guard
{
use GuardHelpers, Macroable {
__call as macroCall;
}
/**
* The user we last attempted to retrieve.
*
* @var \Illuminate\Contracts\Auth\Authenticatable
*/
protected $lastAttempted;
/**
* The JWT instance.
*
* @var \Tymon\JWTAuth\JWT
*/
protected $jwt;
/**
* The request instance.
*
* @var \Illuminate\Http\Request
*/
protected $request;
/**
* Instantiate the class.
*
* @param \Tymon\JWTAuth\JWT $jwt
* @param \Illuminate\Contracts\Auth\UserProvider $provider
* @param \Illuminate\Http\Request $request
* @return void
*/
public function __construct(JWT $jwt, UserProvider $provider, Request $request)
{
$this->jwt = $jwt;
$this->provider = $provider;
$this->request = $request;
}
/**
* Get the currently authenticated user.
*
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function user()
{
if ($this->user !== null) {
return $this->user;
}
if ($this->jwt->setRequest($this->request)->getToken() &&
($payload = $this->jwt->check(true)) &&
$this->validateSubject()
) {
return $this->user = $this->provider->retrieveById($payload['sub']);
}
}
/**
* Get the currently authenticated user or throws an exception.
*
* @return \Illuminate\Contracts\Auth\Authenticatable
*
* @throws \Tymon\JWTAuth\Exceptions\UserNotDefinedException
*/
public function userOrFail()
{
if (! $user = $this->user()) {
throw new UserNotDefinedException;
}
return $user;
}
/**
* Validate a user's credentials.
*
* @param array $credentials
* @return bool
*/
public function validate(array $credentials = [])
{
return (bool) $this->attempt($credentials, false);
}
/**
* Attempt to authenticate the user using the given credentials and return the token.
*
* @param array $credentials
* @param bool $login
* @return bool|string
*/
public function attempt(array $credentials = [], $login = true)
{
$this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
if ($this->hasValidCredentials($user, $credentials)) {
return $login ? $this->login($user) : true;
}
return false;
}
/**
* Create a token for a user.
*
* @param \Tymon\JWTAuth\Contracts\JWTSubject $user
* @return string
*/
public function login(JWTSubject $user)
{
$token = $this->jwt->fromUser($user);
$this->setToken($token)->setUser($user);
return $token;
}
/**
* Logout the user, thus invalidating the token.
*
* @param bool $forceForever
* @return void
*/
public function logout($forceForever = false)
{
$this->requireToken()->invalidate($forceForever);
$this->user = null;
$this->jwt->unsetToken();
}
/**
* Refresh the token.
*
* @param bool $forceForever
* @param bool $resetClaims
* @return string
*/
public function refresh($forceForever = false, $resetClaims = false)
{
return $this->requireToken()->refresh($forceForever, $resetClaims);
}
/**
* Invalidate the token.
*
* @param bool $forceForever
* @return \Tymon\JWTAuth\JWT
*/
public function invalidate($forceForever = false)
{
return $this->requireToken()->invalidate($forceForever);
}
/**
* Create a new token by User id.
*
* @param mixed $id
* @return string|null
*/
public function tokenById($id)
{
if ($user = $this->provider->retrieveById($id)) {
return $this->jwt->fromUser($user);
}
}
/**
* Log a user into the application using their credentials.
*
* @param array $credentials
* @return bool
*/
public function once(array $credentials = [])
{
if ($this->validate($credentials)) {
$this->setUser($this->lastAttempted);
return true;
}
return false;
}
/**
* Log the given User into the application.
*
* @param mixed $id
* @return bool
*/
public function onceUsingId($id)
{
if ($user = $this->provider->retrieveById($id)) {
$this->setUser($user);
return true;
}
return false;
}
/**
* Alias for onceUsingId.
*
* @param mixed $id
* @return bool
*/
public function byId($id)
{
return $this->onceUsingId($id);
}
/**
* Add any custom claims.
*
* @param array $claims
* @return $this
*/
public function claims(array $claims)
{
$this->jwt->claims($claims);
return $this;
}
/**
* Get the raw Payload instance.
*
* @return \Tymon\JWTAuth\Payload
*/
public function getPayload()
{
return $this->requireToken()->getPayload();
}
/**
* Alias for getPayload().
*
* @return \Tymon\JWTAuth\Payload
*/
public function payload()
{
return $this->getPayload();
}
/**
* Set the token.
*
* @param \Tymon\JWTAuth\Token|string $token
* @return $this
*/
public function setToken($token)
{
$this->jwt->setToken($token);
return $this;
}
/**
* Set the token ttl.
*
* @param int $ttl
* @return $this
*/
public function setTTL($ttl)
{
$this->jwt->factory()->setTTL($ttl);
return $this;
}
/**
* Get the user provider used by the guard.
*
* @return \Illuminate\Contracts\Auth\UserProvider
*/
public function getProvider()
{
return $this->provider;
}
/**
* Set the user provider used by the guard.
*
* @param \Illuminate\Contracts\Auth\UserProvider $provider
* @return $this
*/
public function setProvider(UserProvider $provider)
{
$this->provider = $provider;
return $this;
}
/**
* Return the currently cached user.
*
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function getUser()
{
return $this->user;
}
/**
* Get the current request instance.
*
* @return \Illuminate\Http\Request
*/
public function getRequest()
{
return $this->request ?: Request::createFromGlobals();
}
/**
* Set the current request instance.
*
* @param \Illuminate\Http\Request $request
* @return $this
*/
public function setRequest(Request $request)
{
$this->request = $request;
return $this;
}
/**
* Get the token's auth factory.
*
* @return \Tymon\JWTAuth\Factory
*/
public function factory()
{
return $this->jwt->factory();
}
/**
* Get the last user we attempted to authenticate.
*
* @return \Illuminate\Contracts\Auth\Authenticatable
*/
public function getLastAttempted()
{
return $this->lastAttempted;
}
/**
* Determine if the user matches the credentials.
*
* @param mixed $user
* @param array $credentials
* @return bool
*/
protected function hasValidCredentials($user, $credentials)
{
return $user !== null && $this->provider->validateCredentials($user, $credentials);
}
/**
* Ensure the JWTSubject matches what is in the token.
*
* @return bool
*/
protected function validateSubject()
{
// If the provider doesn't have the necessary method
// to get the underlying model name then allow.
if (! method_exists($this->provider, 'getModel')) {
return true;
}
return $this->jwt->checkSubjectModel($this->provider->getModel());
}
/**
* Ensure that a token is available in the request.
*
* @return \Tymon\JWTAuth\JWT
*
* @throws \Tymon\JWTAuth\Exceptions\JWTException
*/
protected function requireToken()
{
if (! $this->jwt->setRequest($this->getRequest())->getToken()) {
throw new JWTException('Token could not be parsed from the request.');
}
return $this->jwt;
}
/**
* Magically call the JWT instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
if (method_exists($this->jwt, $method)) {
return call_user_func_array([$this->jwt, $method], $parameters);
}
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
throw new BadMethodCallException("Method [$method] does not exist.");
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Manager.php | src/Manager.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth;
use Tymon\JWTAuth\Contracts\Providers\JWT as JWTContract;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Support\CustomClaims;
use Tymon\JWTAuth\Support\RefreshFlow;
class Manager
{
use CustomClaims, RefreshFlow;
/**
* The provider.
*
* @var \Tymon\JWTAuth\Contracts\Providers\JWT
*/
protected $provider;
/**
* The blacklist.
*
* @var \Tymon\JWTAuth\Blacklist
*/
protected $blacklist;
/**
* the payload factory.
*
* @var \Tymon\JWTAuth\Factory
*/
protected $payloadFactory;
/**
* The blacklist flag.
*
* @var bool
*/
protected $blacklistEnabled = true;
/**
* the persistent claims.
*
* @var array
*/
protected $persistentClaims = [];
/**
* Constructor.
*
* @param \Tymon\JWTAuth\Contracts\Providers\JWT $provider
* @param \Tymon\JWTAuth\Blacklist $blacklist
* @param \Tymon\JWTAuth\Factory $payloadFactory
* @return void
*/
public function __construct(JWTContract $provider, Blacklist $blacklist, Factory $payloadFactory)
{
$this->provider = $provider;
$this->blacklist = $blacklist;
$this->payloadFactory = $payloadFactory;
}
/**
* Encode a Payload and return the Token.
*
* @param \Tymon\JWTAuth\Payload $payload
* @return \Tymon\JWTAuth\Token
*/
public function encode(Payload $payload)
{
$token = $this->provider->encode($payload->get());
return new Token($token);
}
/**
* Decode a Token and return the Payload.
*
* @param \Tymon\JWTAuth\Token $token
* @param bool $checkBlacklist
* @return \Tymon\JWTAuth\Payload
*
* @throws \Tymon\JWTAuth\Exceptions\TokenBlacklistedException
*/
public function decode(Token $token, $checkBlacklist = true)
{
$payloadArray = $this->provider->decode($token->get());
$payload = $this->payloadFactory
->setRefreshFlow($this->refreshFlow)
->customClaims($payloadArray)
->make();
if ($checkBlacklist && $this->blacklistEnabled && $this->blacklist->has($payload)) {
throw new TokenBlacklistedException('The token has been blacklisted');
}
return $payload;
}
/**
* Refresh a Token and return a new Token.
*
* @param \Tymon\JWTAuth\Token $token
* @param bool $forceForever
* @param bool $resetClaims
* @return \Tymon\JWTAuth\Token
*/
public function refresh(Token $token, $forceForever = false, $resetClaims = false)
{
$this->setRefreshFlow();
$claims = $this->buildRefreshClaims($this->decode($token));
if ($this->blacklistEnabled) {
// Invalidate old token
$this->invalidate($token, $forceForever);
}
// Return the new token
return $this->encode(
$this->payloadFactory->customClaims($claims)->make($resetClaims)
);
}
/**
* Invalidate a Token by adding it to the blacklist.
*
* @param \Tymon\JWTAuth\Token $token
* @param bool $forceForever
* @return bool
*
* @throws \Tymon\JWTAuth\Exceptions\JWTException
*/
public function invalidate(Token $token, $forceForever = false)
{
if (! $this->blacklistEnabled) {
throw new JWTException('You must have the blacklist enabled to invalidate a token.');
}
return call_user_func(
[$this->blacklist, $forceForever ? 'addForever' : 'add'],
$this->decode($token, false)
);
}
/**
* Build the claims to go into the refreshed token.
*
* @param \Tymon\JWTAuth\Payload $payload
* @return array
*/
protected function buildRefreshClaims(Payload $payload)
{
// Get the claims to be persisted from the payload
$persistentClaims = collect($payload->toArray())
->only($this->persistentClaims)
->toArray();
// persist the relevant claims
return array_merge(
$this->customClaims,
$persistentClaims,
[
'sub' => $payload['sub'],
'iat' => $payload['iat'],
]
);
}
/**
* Get the Payload Factory instance.
*
* @return \Tymon\JWTAuth\Factory
*/
public function getPayloadFactory()
{
return $this->payloadFactory;
}
/**
* Get the JWTProvider instance.
*
* @return \Tymon\JWTAuth\Contracts\Providers\JWT
*/
public function getJWTProvider()
{
return $this->provider;
}
/**
* Get the Blacklist instance.
*
* @return \Tymon\JWTAuth\Blacklist
*/
public function getBlacklist()
{
return $this->blacklist;
}
/**
* Set whether the blacklist is enabled.
*
* @param bool $enabled
* @return $this
*/
public function setBlacklistEnabled($enabled)
{
$this->blacklistEnabled = $enabled;
return $this;
}
/**
* Set the claims to be persisted when refreshing a token.
*
* @param array $claims
* @return $this
*/
public function setPersistentClaims(array $claims)
{
$this->persistentClaims = $claims;
return $this;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Blacklist.php | src/Blacklist.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth;
use Tymon\JWTAuth\Contracts\Providers\Storage;
use Tymon\JWTAuth\Support\Utils;
class Blacklist
{
/**
* The storage.
*
* @var \Tymon\JWTAuth\Contracts\Providers\Storage
*/
protected $storage;
/**
* The grace period when a token is blacklisted. In seconds.
*
* @var int
*/
protected $gracePeriod = 0;
/**
* Number of minutes from issue date in which a JWT can be refreshed.
*
* @var int
*/
protected $refreshTTL = 20160;
/**
* The unique key held within the blacklist.
*
* @var string
*/
protected $key = 'jti';
/**
* Constructor.
*
* @param \Tymon\JWTAuth\Contracts\Providers\Storage $storage
* @return void
*/
public function __construct(Storage $storage)
{
$this->storage = $storage;
}
/**
* Add the token (jti claim) to the blacklist.
*
* @param \Tymon\JWTAuth\Payload $payload
* @return bool
*/
public function add(Payload $payload)
{
// if there is no exp claim then add the jwt to
// the blacklist indefinitely
if (! $payload->hasKey('exp')) {
return $this->addForever($payload);
}
// if we have already added this token to the blacklist
if (! empty($this->storage->get($this->getKey($payload)))) {
return true;
}
$this->storage->add(
$this->getKey($payload),
['valid_until' => $this->getGraceTimestamp()],
$this->getMinutesUntilExpired($payload)
);
return true;
}
/**
* Get the number of minutes until the token expiry.
*
* @param \Tymon\JWTAuth\Payload $payload
* @return int
*/
protected function getMinutesUntilExpired(Payload $payload)
{
$exp = Utils::timestamp($payload['exp']);
$iat = Utils::timestamp($payload['iat']);
// get the latter of the two expiration dates and find
// the number of minutes until the expiration date,
// plus 1 minute to avoid overlap
$expiration = $exp->max($iat->addMinutes($this->refreshTTL))->addMinute();
$minutes = method_exists($expiration, 'diffInRealMinutes')
? $expiration->diffInRealMinutes()
: $expiration->diffInUTCMinutes();
return (int) ceil(abs($minutes));
}
/**
* Add the token (jti claim) to the blacklist indefinitely.
*
* @param \Tymon\JWTAuth\Payload $payload
* @return bool
*/
public function addForever(Payload $payload)
{
$this->storage->forever($this->getKey($payload), 'forever');
return true;
}
/**
* Determine whether the token has been blacklisted.
*
* @param \Tymon\JWTAuth\Payload $payload
* @return bool
*/
public function has(Payload $payload)
{
$val = $this->storage->get($this->getKey($payload));
// exit early if the token was blacklisted forever,
if ($val === 'forever') {
return true;
}
// check whether the expiry + grace has past
return ! empty($val) && ! Utils::isFuture($val['valid_until']);
}
/**
* Remove the token (jti claim) from the blacklist.
*
* @param \Tymon\JWTAuth\Payload $payload
* @return bool
*/
public function remove(Payload $payload)
{
return $this->storage->destroy($this->getKey($payload));
}
/**
* Remove all tokens from the blacklist.
*
* @return bool
*/
public function clear()
{
$this->storage->flush();
return true;
}
/**
* Get the timestamp when the blacklist comes into effect
* This defaults to immediate (0 seconds).
*
* @return int
*/
protected function getGraceTimestamp()
{
return Utils::now()->addSeconds($this->gracePeriod)->getTimestamp();
}
/**
* Set the grace period.
*
* @param int $gracePeriod
* @return $this
*/
public function setGracePeriod($gracePeriod)
{
$this->gracePeriod = (int) $gracePeriod;
return $this;
}
/**
* Get the grace period.
*
* @return int
*/
public function getGracePeriod()
{
return $this->gracePeriod;
}
/**
* Get the unique key held within the blacklist.
*
* @param \Tymon\JWTAuth\Payload $payload
* @return mixed
*/
public function getKey(Payload $payload)
{
return $payload($this->key);
}
/**
* Set the unique key held within the blacklist.
*
* @param string $key
* @return $this
*/
public function setKey($key)
{
$this->key = value($key);
return $this;
}
/**
* Set the refresh time limit.
*
* @param int $ttl
* @return $this
*/
public function setRefreshTTL($ttl)
{
$this->refreshTTL = (int) $ttl;
return $this;
}
/**
* Get the refresh time limit.
*
* @return int
*/
public function getRefreshTTL()
{
return $this->refreshTTL;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/JWT.php | src/JWT.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth;
use BadMethodCallException;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Parser\Parser;
use Tymon\JWTAuth\Support\CustomClaims;
class JWT
{
use CustomClaims;
/**
* The authentication manager.
*
* @var \Tymon\JWTAuth\Manager
*/
protected $manager;
/**
* The HTTP parser.
*
* @var \Tymon\JWTAuth\Http\Parser\Parser
*/
protected $parser;
/**
* The token.
*
* @var \Tymon\JWTAuth\Token|null
*/
protected $token;
/**
* Lock the subject.
*
* @var bool
*/
protected $lockSubject = true;
/**
* JWT constructor.
*
* @param \Tymon\JWTAuth\Manager $manager
* @param \Tymon\JWTAuth\Http\Parser\Parser $parser
* @return void
*/
public function __construct(Manager $manager, Parser $parser)
{
$this->manager = $manager;
$this->parser = $parser;
}
/**
* Generate a token for a given subject.
*
* @param \Tymon\JWTAuth\Contracts\JWTSubject $subject
* @return string
*/
public function fromSubject(JWTSubject $subject)
{
$payload = $this->makePayload($subject);
return $this->manager->encode($payload)->get();
}
/**
* Alias to generate a token for a given user.
*
* @param \Tymon\JWTAuth\Contracts\JWTSubject $user
* @return string
*/
public function fromUser(JWTSubject $user)
{
return $this->fromSubject($user);
}
/**
* Refresh an expired token.
*
* @param bool $forceForever
* @param bool $resetClaims
* @return string
*/
public function refresh($forceForever = false, $resetClaims = false)
{
$this->requireToken();
return $this->manager->customClaims($this->getCustomClaims())
->refresh($this->token, $forceForever, $resetClaims)
->get();
}
/**
* Invalidate a token (add it to the blacklist).
*
* @param bool $forceForever
* @return $this
*/
public function invalidate($forceForever = false)
{
$this->requireToken();
$this->manager->invalidate($this->token, $forceForever);
return $this;
}
/**
* Alias to get the payload, and as a result checks that
* the token is valid i.e. not expired or blacklisted.
*
* @return \Tymon\JWTAuth\Payload
*
* @throws \Tymon\JWTAuth\Exceptions\JWTException
*/
public function checkOrFail()
{
return $this->getPayload();
}
/**
* Check that the token is valid.
*
* @param bool $getPayload
* @return \Tymon\JWTAuth\Payload|bool
*/
public function check($getPayload = false)
{
try {
$payload = $this->checkOrFail();
} catch (JWTException $e) {
return false;
}
return $getPayload ? $payload : true;
}
/**
* Get the token.
*
* @return \Tymon\JWTAuth\Token|null
*/
public function getToken()
{
if ($this->token === null) {
try {
$this->parseToken();
} catch (JWTException $e) {
$this->token = null;
}
}
return $this->token;
}
/**
* Parse the token from the request.
*
* @return $this
*
* @throws \Tymon\JWTAuth\Exceptions\JWTException
*/
public function parseToken()
{
if (! $token = $this->parser->parseToken()) {
throw new JWTException('The token could not be parsed from the request');
}
return $this->setToken($token);
}
/**
* Get the raw Payload instance.
*
* @return \Tymon\JWTAuth\Payload
*/
public function getPayload()
{
$this->requireToken();
return $this->manager->decode($this->token);
}
/**
* Alias for getPayload().
*
* @return \Tymon\JWTAuth\Payload
*/
public function payload()
{
return $this->getPayload();
}
/**
* Convenience method to get a claim value.
*
* @param string $claim
* @return mixed
*/
public function getClaim($claim)
{
return $this->payload()->get($claim);
}
/**
* Create a Payload instance.
*
* @param \Tymon\JWTAuth\Contracts\JWTSubject $subject
* @return \Tymon\JWTAuth\Payload
*/
public function makePayload(JWTSubject $subject)
{
return $this->factory()->customClaims($this->getClaimsArray($subject))->make();
}
/**
* Build the claims array and return it.
*
* @param \Tymon\JWTAuth\Contracts\JWTSubject $subject
* @return array
*/
protected function getClaimsArray(JWTSubject $subject)
{
return array_merge(
$this->getClaimsForSubject($subject),
$subject->getJWTCustomClaims(), // custom claims from JWTSubject method
$this->customClaims // custom claims from inline setter
);
}
/**
* Get the claims associated with a given subject.
*
* @param \Tymon\JWTAuth\Contracts\JWTSubject $subject
* @return array
*/
protected function getClaimsForSubject(JWTSubject $subject)
{
return array_merge([
'sub' => $subject->getJWTIdentifier(),
], $this->lockSubject ? ['prv' => $this->hashSubjectModel($subject)] : []);
}
/**
* Hash the subject model and return it.
*
* @param string|object $model
* @return string
*/
protected function hashSubjectModel($model)
{
return sha1(is_object($model) ? get_class($model) : $model);
}
/**
* Check if the subject model matches the one saved in the token.
*
* @param string|object $model
* @return bool
*/
public function checkSubjectModel($model)
{
if (($prv = $this->payload()->get('prv')) === null) {
return true;
}
return $this->hashSubjectModel($model) === $prv;
}
/**
* Set the token.
*
* @param \Tymon\JWTAuth\Token|string $token
* @return $this
*/
public function setToken($token)
{
$this->token = $token instanceof Token ? $token : new Token($token);
return $this;
}
/**
* Unset the current token.
*
* @return $this
*/
public function unsetToken()
{
$this->token = null;
return $this;
}
/**
* Ensure that a token is available.
*
* @return void
*
* @throws \Tymon\JWTAuth\Exceptions\JWTException
*/
protected function requireToken()
{
if (! $this->token) {
throw new JWTException('A token is required');
}
}
/**
* Set the request instance.
*
* @param \Illuminate\Http\Request $request
* @return $this
*/
public function setRequest(Request $request)
{
$this->parser->setRequest($request);
return $this;
}
/**
* Set whether the subject should be "locked".
*
* @param bool $lock
* @return $this
*/
public function lockSubject($lock)
{
$this->lockSubject = $lock;
return $this;
}
/**
* Get the Manager instance.
*
* @return \Tymon\JWTAuth\Manager
*/
public function manager()
{
return $this->manager;
}
/**
* Get the Parser instance.
*
* @return \Tymon\JWTAuth\Http\Parser\Parser
*/
public function parser()
{
return $this->parser;
}
/**
* Get the Payload Factory.
*
* @return \Tymon\JWTAuth\Factory
*/
public function factory()
{
return $this->manager->getPayloadFactory();
}
/**
* Get the Blacklist.
*
* @return \Tymon\JWTAuth\Blacklist
*/
public function blacklist()
{
return $this->manager->getBlacklist();
}
/**
* Magically call the JWT Manager.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
if (method_exists($this->manager, $method)) {
return call_user_func_array([$this->manager, $method], $parameters);
}
throw new BadMethodCallException("Method [$method] does not exist.");
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Factory.php | src/Factory.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth;
use Tymon\JWTAuth\Claims\Claim;
use Tymon\JWTAuth\Claims\Collection;
use Tymon\JWTAuth\Claims\Factory as ClaimFactory;
use Tymon\JWTAuth\Support\CustomClaims;
use Tymon\JWTAuth\Support\RefreshFlow;
use Tymon\JWTAuth\Validators\PayloadValidator;
class Factory
{
use CustomClaims, RefreshFlow;
/**
* The claim factory.
*
* @var \Tymon\JWTAuth\Claims\Factory
*/
protected $claimFactory;
/**
* The validator.
*
* @var \Tymon\JWTAuth\Validators\PayloadValidator
*/
protected $validator;
/**
* The default claims.
*
* @var array
*/
protected $defaultClaims = [
'iss',
'iat',
'exp',
'nbf',
'jti',
];
/**
* The claims collection.
*
* @var \Tymon\JWTAuth\Claims\Collection
*/
protected $claims;
/**
* Constructor.
*
* @param \Tymon\JWTAuth\Claims\Factory $claimFactory
* @param \Tymon\JWTAuth\Validators\PayloadValidator $validator
* @return void
*/
public function __construct(ClaimFactory $claimFactory, PayloadValidator $validator)
{
$this->claimFactory = $claimFactory;
$this->validator = $validator;
$this->claims = new Collection;
}
/**
* Create the Payload instance.
*
* @param bool $resetClaims
* @return \Tymon\JWTAuth\Payload
*/
public function make($resetClaims = false)
{
if ($resetClaims) {
$this->emptyClaims();
}
return $this->withClaims($this->buildClaimsCollection());
}
/**
* Empty the claims collection.
*
* @return $this
*/
public function emptyClaims()
{
$this->claims = new Collection;
return $this;
}
/**
* Add an array of claims to the Payload.
*
* @param array $claims
* @return $this
*/
protected function addClaims(array $claims)
{
foreach ($claims as $name => $value) {
$this->addClaim($name, $value);
}
return $this;
}
/**
* Add a claim to the Payload.
*
* @param string $name
* @param mixed $value
* @return $this
*/
protected function addClaim($name, $value)
{
$this->claims->put($name, $value);
return $this;
}
/**
* Build the default claims.
*
* @return $this
*/
protected function buildClaims()
{
// remove the exp claim if it exists and the ttl is null
if ($this->claimFactory->getTTL() === null && $key = array_search('exp', $this->defaultClaims)) {
unset($this->defaultClaims[$key]);
}
// add the default claims
foreach ($this->defaultClaims as $claim) {
$this->addClaim($claim, $this->claimFactory->make($claim));
}
// add custom claims on top, allowing them to overwrite defaults
return $this->addClaims($this->getCustomClaims());
}
/**
* Build out the Claim DTO's.
*
* @return \Tymon\JWTAuth\Claims\Collection
*/
protected function resolveClaims()
{
return $this->claims->map(function ($value, $name) {
return $value instanceof Claim ? $value : $this->claimFactory->get($name, $value);
});
}
/**
* Build and get the Claims Collection.
*
* @return \Tymon\JWTAuth\Claims\Collection
*/
public function buildClaimsCollection()
{
return $this->buildClaims()->resolveClaims();
}
/**
* Get a Payload instance with a claims collection.
*
* @param \Tymon\JWTAuth\Claims\Collection $claims
* @return \Tymon\JWTAuth\Payload
*/
public function withClaims(Collection $claims)
{
return new Payload($claims, $this->validator, $this->refreshFlow);
}
/**
* Set the default claims to be added to the Payload.
*
* @param array $claims
* @return $this
*/
public function setDefaultClaims(array $claims)
{
$this->defaultClaims = $claims;
return $this;
}
/**
* Helper to set the ttl.
*
* @param int $ttl
* @return $this
*/
public function setTTL($ttl)
{
$this->claimFactory->setTTL($ttl);
return $this;
}
/**
* Helper to get the ttl.
*
* @return int
*/
public function getTTL()
{
return $this->claimFactory->getTTL();
}
/**
* Get the default claims.
*
* @return array
*/
public function getDefaultClaims()
{
return $this->defaultClaims;
}
/**
* Get the PayloadValidator instance.
*
* @return \Tymon\JWTAuth\Validators\PayloadValidator
*/
public function validator()
{
return $this->validator;
}
/**
* Magically add a claim.
*
* @param string $method
* @param array $parameters
* @return $this
*/
public function __call($method, $parameters)
{
$this->addClaim($method, $parameters[0]);
return $this;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/JWTAuth.php | src/JWTAuth.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth;
use Tymon\JWTAuth\Contracts\Providers\Auth;
use Tymon\JWTAuth\Http\Parser\Parser;
/** @deprecated */
class JWTAuth extends JWT
{
/**
* The authentication provider.
*
* @var \Tymon\JWTAuth\Contracts\Providers\Auth
*/
protected $auth;
/**
* Constructor.
*
* @param \Tymon\JWTAuth\Manager $manager
* @param \Tymon\JWTAuth\Contracts\Providers\Auth $auth
* @param \Tymon\JWTAuth\Http\Parser\Parser $parser
* @return void
*/
public function __construct(Manager $manager, Auth $auth, Parser $parser)
{
parent::__construct($manager, $parser);
$this->auth = $auth;
}
/**
* Attempt to authenticate the user and return the token.
*
* @param array $credentials
* @return false|string
*/
public function attempt(array $credentials)
{
if (! $this->auth->byCredentials($credentials)) {
return false;
}
return $this->fromUser($this->user());
}
/**
* Authenticate a user via a token.
*
* @return \Tymon\JWTAuth\Contracts\JWTSubject|false
*/
public function authenticate()
{
$id = $this->getPayload()->get('sub');
if (! $this->auth->byId($id)) {
return false;
}
return $this->user();
}
/**
* Alias for authenticate().
*
* @return \Tymon\JWTAuth\Contracts\JWTSubject|false
*/
public function toUser()
{
return $this->authenticate();
}
/**
* Get the authenticated user.
*
* @return \Tymon\JWTAuth\Contracts\JWTSubject
*/
public function user()
{
return $this->auth->user();
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Exceptions/TokenExpiredException.php | src/Exceptions/TokenExpiredException.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Exceptions;
class TokenExpiredException extends JWTException
{
//
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Exceptions/TokenBlacklistedException.php | src/Exceptions/TokenBlacklistedException.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Exceptions;
class TokenBlacklistedException extends TokenInvalidException
{
//
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Exceptions/PayloadException.php | src/Exceptions/PayloadException.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Exceptions;
class PayloadException extends JWTException
{
//
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Exceptions/TokenInvalidException.php | src/Exceptions/TokenInvalidException.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Exceptions;
class TokenInvalidException extends JWTException
{
//
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Exceptions/UserNotDefinedException.php | src/Exceptions/UserNotDefinedException.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Exceptions;
class UserNotDefinedException extends JWTException
{
//
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Exceptions/JWTException.php | src/Exceptions/JWTException.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Exceptions;
use Exception;
class JWTException extends Exception
{
/**
* {@inheritdoc}
*/
protected $message = 'An error occurred';
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Exceptions/InvalidClaimException.php | src/Exceptions/InvalidClaimException.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Exceptions;
use Exception;
use Tymon\JWTAuth\Claims\Claim;
class InvalidClaimException extends JWTException
{
/**
* Constructor.
*
* @param \Tymon\JWTAuth\Claims\Claim $claim
* @param int $code
* @param \Exception|null $previous
* @return void
*/
public function __construct(Claim $claim, $code = 0, ?Exception $previous = null)
{
parent::__construct('Invalid value provided for claim ['.$claim->getName().']', $code, $previous);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Parser/KeyTrait.php | src/Http/Parser/KeyTrait.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Parser;
trait KeyTrait
{
/**
* The key.
*
* @var string
*/
protected $key = 'token';
/**
* Set the key.
*
* @param string $key
* @return $this
*/
public function setKey($key)
{
$this->key = $key;
return $this;
}
/**
* Get the key.
*
* @return string
*/
public function getKey()
{
return $this->key;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Parser/RouteParams.php | src/Http/Parser/RouteParams.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Parser;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Contracts\Http\Parser as ParserContract;
class RouteParams implements ParserContract
{
use KeyTrait;
/**
* Try to get the token from the route parameters.
*
* @param \Illuminate\Http\Request $request
* @return null|string
*/
public function parse(Request $request)
{
$route = $request->route();
// Route may not be an instance of Illuminate\Routing\Route
// (it's an array in Lumen <5.2) or not exist at all
// (if the request was never dispatched)
if (is_callable([$route, 'parameter'])) {
return $route->parameter($this->key);
}
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Parser/InputSource.php | src/Http/Parser/InputSource.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Parser;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Contracts\Http\Parser as ParserContract;
class InputSource implements ParserContract
{
use KeyTrait;
/**
* Try to parse the token from the request input source.
*
* @param \Illuminate\Http\Request $request
* @return null|string
*/
public function parse(Request $request)
{
return $request->input($this->key);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Parser/QueryString.php | src/Http/Parser/QueryString.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Parser;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Contracts\Http\Parser as ParserContract;
class QueryString implements ParserContract
{
use KeyTrait;
/**
* Try to parse the token from the request query string.
*
* @param \Illuminate\Http\Request $request
* @return null|string
*/
public function parse(Request $request)
{
return $request->query($this->key);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Parser/Parser.php | src/Http/Parser/Parser.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Parser;
use Illuminate\Http\Request;
class Parser
{
/**
* The chain.
*
* @var array
*/
private $chain;
/**
* The request.
*
* @var \Illuminate\Http\Request
*/
protected $request;
/**
* Constructor.
*
* @param \Illuminate\Http\Request $request
* @param array $chain
* @return void
*/
public function __construct(Request $request, array $chain = [])
{
$this->request = $request;
$this->chain = $chain;
}
/**
* Get the parser chain.
*
* @return array
*/
public function getChain()
{
return $this->chain;
}
/**
* Add a new parser to the chain.
*
* @param array|\Tymon\JWTAuth\Contracts\Http\Parser $parsers
* @return $this
*/
public function addParser($parsers)
{
$this->chain = array_merge($this->chain, is_array($parsers) ? $parsers : [$parsers]);
return $this;
}
/**
* Set the order of the parser chain.
*
* @param array $chain
* @return $this
*/
public function setChain(array $chain)
{
$this->chain = $chain;
return $this;
}
/**
* Alias for setting the order of the chain.
*
* @param array $chain
* @return $this
*/
public function setChainOrder(array $chain)
{
return $this->setChain($chain);
}
/**
* Iterate through the parsers and attempt to retrieve
* a value, otherwise return null.
*
* @return string|null
*/
public function parseToken()
{
foreach ($this->chain as $parser) {
if ($response = $parser->parse($this->request)) {
return $response;
}
}
}
/**
* Check whether a token exists in the chain.
*
* @return bool
*/
public function hasToken()
{
return $this->parseToken() !== null;
}
/**
* Set the request instance.
*
* @param \Illuminate\Http\Request $request
* @return $this
*/
public function setRequest(Request $request)
{
$this->request = $request;
return $this;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Parser/LumenRouteParams.php | src/Http/Parser/LumenRouteParams.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Parser;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
class LumenRouteParams extends RouteParams
{
/**
* Try to get the token from the route parameters.
*
* @param \Illuminate\Http\Request $request
* @return null|string
*/
public function parse(Request $request)
{
// WARNING: Only use this parser if you know what you're doing!
// It will only work with poorly-specified aspects of certain Lumen releases.
// Route is the expected kind of array, and has a parameter with the key we want.
return Arr::get($request->route(), '2.'.$this->key);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Parser/AuthHeaders.php | src/Http/Parser/AuthHeaders.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Parser;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Contracts\Http\Parser as ParserContract;
class AuthHeaders implements ParserContract
{
/**
* The header name.
*
* @var string
*/
protected $header = 'authorization';
/**
* The header prefix.
*
* @var string
*/
protected $prefix = 'bearer';
/**
* Attempt to parse the token from some other possible headers.
*
* @param \Illuminate\Http\Request $request
* @return null|string
*/
protected function fromAltHeaders(Request $request)
{
return $request->server->get('HTTP_AUTHORIZATION') ?: $request->server->get('REDIRECT_HTTP_AUTHORIZATION');
}
/**
* Try to parse the token from the request header.
*
* @param \Illuminate\Http\Request $request
* @return null|string
*/
public function parse(Request $request)
{
$header = $request->headers->get($this->header) ?: $this->fromAltHeaders($request);
if ($header !== null) {
$position = strripos($header, $this->prefix);
if ($position !== false) {
$header = substr($header, $position + strlen($this->prefix));
return trim(
strpos($header, ',') !== false ? strstr($header, ',', true) : $header
);
}
}
return null;
}
/**
* Set the header name.
*
* @param string $headerName
* @return $this
*/
public function setHeaderName($headerName)
{
$this->header = $headerName;
return $this;
}
/**
* Set the header prefix.
*
* @param string $headerPrefix
* @return $this
*/
public function setHeaderPrefix($headerPrefix)
{
$this->prefix = $headerPrefix;
return $this;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Parser/Cookies.php | src/Http/Parser/Cookies.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Parser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Tymon\JWTAuth\Contracts\Http\Parser as ParserContract;
class Cookies implements ParserContract
{
use KeyTrait;
/**
* Decrypt or not the cookie while parsing.
*
* @var bool
*/
private $decrypt;
public function __construct($decrypt = true)
{
$this->decrypt = $decrypt;
}
/**
* Try to parse the token from the request cookies.
*
* @param \Illuminate\Http\Request $request
* @return null|string
*/
public function parse(Request $request)
{
if ($this->decrypt && $request->hasCookie($this->key)) {
return Crypt::decrypt($request->cookie($this->key));
}
return $request->cookie($this->key);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Middleware/Authenticate.php | src/Http/Middleware/Authenticate.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Middleware;
use Closure;
/** @deprecated */
class Authenticate extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
*/
public function handle($request, Closure $next)
{
$this->authenticate($request);
return $next($request);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Middleware/Check.php | src/Http/Middleware/Check.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Middleware;
use Closure;
use Exception;
/** @deprecated */
class Check extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->parser()->setRequest($request)->hasToken()) {
try {
$this->auth->parseToken()->authenticate();
} catch (Exception $e) {
//
}
}
return $next($request);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Middleware/AuthenticateAndRenew.php | src/Http/Middleware/AuthenticateAndRenew.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Middleware;
use Closure;
/** @deprecated */
class AuthenticateAndRenew extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
*/
public function handle($request, Closure $next)
{
$this->authenticate($request);
$response = $next($request);
// Send the refreshed token back to the client.
return $this->setAuthenticationHeader($response);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Middleware/BaseMiddleware.php | src/Http/Middleware/BaseMiddleware.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Middleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\JWTAuth;
/** @deprecated */
abstract class BaseMiddleware
{
/**
* The JWT Authenticator.
*
* @var \Tymon\JWTAuth\JWTAuth
*/
protected $auth;
/**
* Create a new BaseMiddleware instance.
*
* @param \Tymon\JWTAuth\JWTAuth $auth
* @return void
*/
public function __construct(JWTAuth $auth)
{
$this->auth = $auth;
}
/**
* Check the request for the presence of a token.
*
* @param \Illuminate\Http\Request $request
* @return void
*
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
*/
public function checkForToken(Request $request)
{
if (! $this->auth->parser()->setRequest($request)->hasToken()) {
throw new UnauthorizedHttpException('jwt-auth', 'Token not provided');
}
}
/**
* Attempt to authenticate a user via the token in the request.
*
* @param \Illuminate\Http\Request $request
* @return void
*
* @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
*/
public function authenticate(Request $request)
{
$this->checkForToken($request);
try {
if (! $this->auth->parseToken()->authenticate()) {
throw new UnauthorizedHttpException('jwt-auth', 'User not found');
}
} catch (JWTException $e) {
throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
}
}
/**
* Set the authentication header.
*
* @param \Illuminate\Http\Response|\Illuminate\Http\JsonResponse $response
* @param string|null $token
* @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
*/
protected function setAuthenticationHeader($response, $token = null)
{
$token = $token ?: $this->auth->refresh();
$response->headers->set('Authorization', 'Bearer '.$token);
return $response;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Http/Middleware/RefreshToken.php | src/Http/Middleware/RefreshToken.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Http\Middleware;
use Closure;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
/** @deprecated */
class RefreshToken extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
*/
public function handle($request, Closure $next)
{
$this->checkForToken($request);
try {
$token = $this->auth->parseToken()->refresh();
} catch (JWTException $e) {
throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
}
$response = $next($request);
// Send the refreshed token back to the client.
return $this->setAuthenticationHeader($response, $token);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Support/CustomClaims.php | src/Support/CustomClaims.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Support;
trait CustomClaims
{
/**
* Custom claims.
*
* @var array
*/
protected $customClaims = [];
/**
* Set the custom claims.
*
* @param array $customClaims
* @return $this
*/
public function customClaims(array $customClaims)
{
$this->customClaims = $customClaims;
return $this;
}
/**
* Alias to set the custom claims.
*
* @param array $customClaims
* @return $this
*/
public function claims(array $customClaims)
{
return $this->customClaims($customClaims);
}
/**
* Get the custom claims.
*
* @return array
*/
public function getCustomClaims()
{
return $this->customClaims;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Support/Utils.php | src/Support/Utils.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Support;
use Carbon\Carbon;
class Utils
{
/**
* Get the Carbon instance for the current time.
*
* @return \Carbon\Carbon
*/
public static function now()
{
return Carbon::now('UTC');
}
/**
* Get the Carbon instance for the timestamp.
*
* @param int $timestamp
* @return \Carbon\Carbon
*/
public static function timestamp($timestamp)
{
return Carbon::createFromTimestampUTC($timestamp)->timezone('UTC');
}
/**
* Checks if a timestamp is in the past.
*
* @param int $timestamp
* @param int $leeway
* @return bool
*/
public static function isPast($timestamp, $leeway = 0)
{
$timestamp = static::timestamp($timestamp);
return $leeway > 0
? $timestamp->addSeconds($leeway)->isPast()
: $timestamp->isPast();
}
/**
* Checks if a timestamp is in the future.
*
* @param int $timestamp
* @param int $leeway
* @return bool
*/
public static function isFuture($timestamp, $leeway = 0)
{
$timestamp = static::timestamp($timestamp);
return $leeway > 0
? $timestamp->subSeconds($leeway)->isFuture()
: $timestamp->isFuture();
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Support/RefreshFlow.php | src/Support/RefreshFlow.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Support;
trait RefreshFlow
{
/**
* The refresh flow flag.
*
* @var bool
*/
protected $refreshFlow = false;
/**
* Set the refresh flow flag.
*
* @param bool $refreshFlow
* @return $this
*/
public function setRefreshFlow($refreshFlow = true)
{
$this->refreshFlow = $refreshFlow;
return $this;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Contracts/Claim.php | src/Contracts/Claim.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Contracts;
interface Claim
{
/**
* Set the claim value, and call a validate method.
*
* @param mixed $value
* @return $this
*
* @throws \Tymon\JWTAuth\Exceptions\InvalidClaimException
*/
public function setValue($value);
/**
* Get the claim value.
*
* @return mixed
*/
public function getValue();
/**
* Set the claim name.
*
* @param string $name
* @return $this
*/
public function setName($name);
/**
* Get the claim name.
*
* @return string
*/
public function getName();
/**
* Validate the Claim value.
*
* @param mixed $value
* @return bool
*/
public function validateCreate($value);
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Contracts/Validator.php | src/Contracts/Validator.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Contracts;
interface Validator
{
/**
* Perform some checks on the value.
*
* @param mixed $value
* @return void
*/
public function check($value);
/**
* Helper function to return a boolean.
*
* @param array $value
* @return bool
*/
public function isValid($value);
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Contracts/JWTSubject.php | src/Contracts/JWTSubject.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Contracts;
interface JWTSubject
{
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier();
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims();
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Contracts/Http/Parser.php | src/Contracts/Http/Parser.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Contracts\Http;
use Illuminate\Http\Request;
interface Parser
{
/**
* Parse the request.
*
* @param \Illuminate\Http\Request $request
* @return null|string
*/
public function parse(Request $request);
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Contracts/Providers/Storage.php | src/Contracts/Providers/Storage.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Contracts\Providers;
interface Storage
{
/**
* @param string $key
* @param mixed $value
* @param int $minutes
* @return void
*/
public function add($key, $value, $minutes);
/**
* @param string $key
* @param mixed $value
* @return void
*/
public function forever($key, $value);
/**
* @param string $key
* @return mixed
*/
public function get($key);
/**
* @param string $key
* @return bool
*/
public function destroy($key);
/**
* @return void
*/
public function flush();
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Contracts/Providers/Auth.php | src/Contracts/Providers/Auth.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Contracts\Providers;
interface Auth
{
/**
* Check a user's credentials.
*
* @param array $credentials
* @return mixed
*/
public function byCredentials(array $credentials);
/**
* Authenticate a user via the id.
*
* @param mixed $id
* @return mixed
*/
public function byId($id);
/**
* Get the currently authenticated user.
*
* @return mixed
*/
public function user();
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Contracts/Providers/JWT.php | src/Contracts/Providers/JWT.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Contracts\Providers;
interface JWT
{
/**
* @param array $payload
* @return string
*/
public function encode(array $payload);
/**
* @param string $token
* @return array
*/
public function decode($token);
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Facades/JWTFactory.php | src/Facades/JWTFactory.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Facades;
use Illuminate\Support\Facades\Facade;
class JWTFactory extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'tymon.jwt.payload.factory';
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Facades/JWTProvider.php | src/Facades/JWTProvider.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Facades;
use Illuminate\Support\Facades\Facade;
class JWTProvider extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'tymon.jwt.provider.jwt';
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Facades/JWTAuth.php | src/Facades/JWTAuth.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Facades;
use Illuminate\Support\Facades\Facade;
class JWTAuth extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'tymon.jwt.auth';
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Console/JWTGenerateSecretCommand.php | src/Console/JWTGenerateSecretCommand.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
class JWTGenerateSecretCommand extends Command
{
/**
* The console command signature.
*
* @var string
*/
protected $signature = 'jwt:secret
{--s|show : Display the key instead of modifying files.}
{--always-no : Skip generating key if it already exists.}
{--f|force : Skip confirmation when overwriting an existing key.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Set the JWTAuth secret key used to sign the tokens';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$key = Str::random(64);
if ($this->option('show')) {
$this->comment($key);
return;
}
if (file_exists($path = $this->envPath()) === false) {
return $this->displayKey($key);
}
if (Str::contains(file_get_contents($path), 'JWT_SECRET') === false) {
// create new entry
file_put_contents($path, PHP_EOL."JWT_SECRET=$key".PHP_EOL, FILE_APPEND);
} else {
if ($this->option('always-no')) {
$this->comment('Secret key already exists. Skipping...');
return;
}
if ($this->isConfirmed() === false) {
$this->comment('Phew... No changes were made to your secret key.');
return;
}
// update existing entry
file_put_contents($path, str_replace(
'JWT_SECRET='.$this->laravel['config']['jwt.secret'],
'JWT_SECRET='.$key, file_get_contents($path)
));
}
$this->displayKey($key);
}
/**
* Display the key.
*
* @param string $key
* @return void
*/
protected function displayKey($key)
{
$this->laravel['config']['jwt.secret'] = $key;
$this->info("jwt-auth secret [$key] set successfully.");
}
/**
* Check if the modification is confirmed.
*
* @return bool
*/
protected function isConfirmed()
{
return $this->option('force') ? true : $this->confirm(
'This will invalidate all existing tokens. Are you sure you want to override the secret key?'
);
}
/**
* Get the .env file path.
*
* @return string
*/
protected function envPath()
{
if (method_exists($this->laravel, 'environmentFilePath')) {
return $this->laravel->environmentFilePath();
}
// check if laravel version Less than 5.4.17
if (version_compare($this->laravel->version(), '5.4.17', '<')) {
return $this->laravel->basePath().DIRECTORY_SEPARATOR.'.env';
}
return $this->laravel->basePath('.env');
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Validators/TokenValidator.php | src/Validators/TokenValidator.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Validators;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
class TokenValidator extends Validator
{
/**
* Check the structure of the token.
*
* @param string $value
* @return string
*/
public function check($value)
{
return $this->validateStructure($value);
}
/**
* @param string $token
* @return string
*
* @throws \Tymon\JWTAuth\Exceptions\TokenInvalidException
*/
protected function validateStructure($token)
{
$parts = explode('.', $token);
if (count($parts) !== 3) {
throw new TokenInvalidException('Wrong number of segments');
}
$parts = array_filter(array_map('trim', $parts));
if (count($parts) !== 3 || implode('.', $parts) !== $token) {
throw new TokenInvalidException('Malformed token');
}
return $token;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Validators/Validator.php | src/Validators/Validator.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Validators;
use Tymon\JWTAuth\Contracts\Validator as ValidatorContract;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Support\RefreshFlow;
abstract class Validator implements ValidatorContract
{
use RefreshFlow;
/**
* Helper function to return a boolean.
*
* @param array $value
* @return bool
*/
public function isValid($value)
{
try {
$this->check($value);
} catch (JWTException $e) {
return false;
}
return true;
}
/**
* Run the validation.
*
* @param array $value
* @return void
*/
abstract public function check($value);
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Validators/PayloadValidator.php | src/Validators/PayloadValidator.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Validators;
use Tymon\JWTAuth\Claims\Collection;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
class PayloadValidator extends Validator
{
/**
* The required claims.
*
* @var array
*/
protected $requiredClaims = [
'iss',
'iat',
'exp',
'nbf',
'sub',
'jti',
];
/**
* The refresh TTL.
*
* @var int
*/
protected $refreshTTL = 20160;
/**
* Run the validations on the payload array.
*
* @param \Tymon\JWTAuth\Claims\Collection $value
* @return \Tymon\JWTAuth\Claims\Collection
*/
public function check($value)
{
$this->validateStructure($value);
return $this->refreshFlow ? $this->validateRefresh($value) : $this->validatePayload($value);
}
/**
* Ensure the payload contains the required claims and
* the claims have the relevant type.
*
* @param \Tymon\JWTAuth\Claims\Collection $claims
* @return void
*
* @throws \Tymon\JWTAuth\Exceptions\TokenInvalidException
*/
protected function validateStructure(Collection $claims)
{
if ($this->requiredClaims && ! $claims->hasAllClaims($this->requiredClaims)) {
throw new TokenInvalidException('JWT payload does not contain the required claims');
}
}
/**
* Validate the payload timestamps.
*
* @param \Tymon\JWTAuth\Claims\Collection $claims
* @return \Tymon\JWTAuth\Claims\Collection
*
* @throws \Tymon\JWTAuth\Exceptions\TokenExpiredException
* @throws \Tymon\JWTAuth\Exceptions\TokenInvalidException
*/
protected function validatePayload(Collection $claims)
{
return $claims->validate('payload');
}
/**
* Check the token in the refresh flow context.
*
* @param \Tymon\JWTAuth\Claims\Collection $claims
* @return \Tymon\JWTAuth\Claims\Collection
*
* @throws \Tymon\JWTAuth\Exceptions\TokenExpiredException
*/
protected function validateRefresh(Collection $claims)
{
return $this->refreshTTL === null ? $claims : $claims->validate('refresh', $this->refreshTTL);
}
/**
* Set the required claims.
*
* @param array $claims
* @return $this
*/
public function setRequiredClaims(array $claims)
{
$this->requiredClaims = $claims;
return $this;
}
/**
* Set the refresh ttl.
*
* @param int $ttl
* @return $this
*/
public function setRefreshTTL($ttl)
{
$this->refreshTTL = $ttl;
return $this;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/Collection.php | src/Claims/Collection.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
use Illuminate\Support\Collection as IlluminateCollection;
use Illuminate\Support\Str;
class Collection extends IlluminateCollection
{
/**
* Create a new collection.
*
* @param mixed $items
* @return void
*/
public function __construct($items = [])
{
parent::__construct($this->getArrayableItems($items));
}
/**
* Get a Claim instance by it's unique name.
*
* @param string $name
* @param callable|null $callback
* @param mixed $default
* @return \Tymon\JWTAuth\Claims\Claim
*/
public function getByClaimName($name, ?callable $callback = null, $default = null)
{
return $this->filter(function (Claim $claim) use ($name) {
return $claim->getName() === $name;
})->first($callback, $default);
}
/**
* Validate each claim under a given context.
*
* @param string $context
* @return $this
*/
public function validate($context = 'payload')
{
$args = func_get_args();
array_shift($args);
$this->each(function ($claim) use ($context, $args) {
call_user_func_array(
[$claim, 'validate'.Str::ucfirst($context)],
$args
);
});
return $this;
}
/**
* Determine if the Collection contains all of the given keys.
*
* @param mixed $claims
* @return bool
*/
public function hasAllClaims($claims)
{
return count($claims) && (new static($claims))->diff($this->keys())->isEmpty();
}
/**
* Get the claims as key/val array.
*
* @return array
*/
public function toPlainArray()
{
return $this->map(function (Claim $claim) {
return $claim->getValue();
})->toArray();
}
/**
* {@inheritdoc}
*/
protected function getArrayableItems($items)
{
return $this->sanitizeClaims($items);
}
/**
* Ensure that the given claims array is keyed by the claim name.
*
* @param mixed $items
* @return array
*/
private function sanitizeClaims($items)
{
$claims = [];
foreach ($items as $key => $value) {
if (! is_string($key) && $value instanceof Claim) {
$key = $value->getName();
}
$claims[$key] = $value;
}
return $claims;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/Issuer.php | src/Claims/Issuer.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
class Issuer extends Claim
{
/**
* {@inheritdoc}
*/
protected $name = 'iss';
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/DatetimeTrait.php | src/Claims/DatetimeTrait.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
use DateInterval;
use DateTimeInterface;
use Tymon\JWTAuth\Exceptions\InvalidClaimException;
use Tymon\JWTAuth\Support\Utils;
trait DatetimeTrait
{
/**
* Time leeway in seconds.
*
* @var int
*/
protected $leeway = 0;
/**
* Set the claim value, and call a validate method.
*
* @param mixed $value
* @return $this
*
* @throws \Tymon\JWTAuth\Exceptions\InvalidClaimException
*/
public function setValue($value)
{
if ($value instanceof DateInterval) {
$value = Utils::now()->add($value);
}
if ($value instanceof DateTimeInterface) {
$value = $value->getTimestamp();
}
return parent::setValue($value);
}
/**
* {@inheritdoc}
*/
public function validateCreate($value)
{
if (! is_numeric($value)) {
throw new InvalidClaimException($this);
}
return $value;
}
/**
* Determine whether the value is in the future.
*
* @param mixed $value
* @return bool
*/
protected function isFuture($value)
{
return Utils::isFuture($value, $this->leeway);
}
/**
* Determine whether the value is in the past.
*
* @param mixed $value
* @return bool
*/
protected function isPast($value)
{
return Utils::isPast($value, $this->leeway);
}
/**
* Set the leeway in seconds.
*
* @param int $leeway
* @return $this
*/
public function setLeeway($leeway)
{
$this->leeway = $leeway;
return $this;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/Audience.php | src/Claims/Audience.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
class Audience extends Claim
{
/**
* {@inheritdoc}
*/
protected $name = 'aud';
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/Subject.php | src/Claims/Subject.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
class Subject extends Claim
{
/**
* {@inheritdoc}
*/
protected $name = 'sub';
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/JwtId.php | src/Claims/JwtId.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
class JwtId extends Claim
{
/**
* {@inheritdoc}
*/
protected $name = 'jti';
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/Custom.php | src/Claims/Custom.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
class Custom extends Claim
{
/**
* @param string $name
* @param mixed $value
* @return void
*/
public function __construct($name, $value)
{
parent::__construct($value);
$this->setName($name);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/Claim.php | src/Claims/Claim.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use JsonSerializable;
use Tymon\JWTAuth\Contracts\Claim as ClaimContract;
abstract class Claim implements Arrayable, ClaimContract, Jsonable, JsonSerializable
{
/**
* The claim name.
*
* @var string
*/
protected $name;
/**
* The claim value.
*
* @var mixed
*/
private $value;
/**
* @param mixed $value
* @return void
*/
public function __construct($value)
{
$this->setValue($value);
}
/**
* Set the claim value, and call a validate method.
*
* @param mixed $value
* @return $this
*
* @throws \Tymon\JWTAuth\Exceptions\InvalidClaimException
*/
public function setValue($value)
{
$this->value = $this->validateCreate($value);
return $this;
}
/**
* Get the claim value.
*
* @return mixed
*/
public function getValue()
{
return $this->value;
}
/**
* Set the claim name.
*
* @param string $name
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get the claim name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Validate the claim in a standalone Claim context.
*
* @param mixed $value
* @return bool
*/
public function validateCreate($value)
{
return $value;
}
/**
* Validate the Claim within a Payload context.
*
* @return bool
*/
public function validatePayload()
{
return $this->getValue();
}
/**
* Validate the Claim within a refresh context.
*
* @param int $refreshTTL
* @return bool
*/
public function validateRefresh($refreshTTL)
{
return $this->getValue();
}
/**
* Checks if the value matches the claim.
*
* @param mixed $value
* @param bool $strict
* @return bool
*/
public function matches($value, $strict = true)
{
return $strict ? $this->value === $value : $this->value == $value;
}
/**
* Convert the object into something JSON serializable.
*
* @return array
*/
#[\ReturnTypeWillChange]
public function jsonSerialize(): mixed
{
return $this->toArray();
}
/**
* Build a key value array comprising of the claim name and value.
*
* @return array
*/
public function toArray()
{
return [$this->getName() => $this->getValue()];
}
/**
* Get the claim as JSON.
*
* @param int $options
* @return string
*/
public function toJson($options = JSON_UNESCAPED_SLASHES)
{
return json_encode($this->toArray(), $options);
}
/**
* Get the payload as a string.
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/NotBefore.php | src/Claims/NotBefore.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
class NotBefore extends Claim
{
use DatetimeTrait;
/**
* {@inheritdoc}
*/
protected $name = 'nbf';
/**
* {@inheritdoc}
*/
public function validatePayload()
{
if ($this->isFuture($this->getValue())) {
throw new TokenInvalidException('Not Before (nbf) timestamp cannot be in the future');
}
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/IssuedAt.php | src/Claims/IssuedAt.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
use Tymon\JWTAuth\Exceptions\InvalidClaimException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
class IssuedAt extends Claim
{
use DatetimeTrait {
validateCreate as commonValidateCreate;
}
/**
* {@inheritdoc}
*/
protected $name = 'iat';
/**
* {@inheritdoc}
*/
public function validateCreate($value)
{
$this->commonValidateCreate($value);
if ($this->isFuture($value)) {
throw new InvalidClaimException($this);
}
return $value;
}
/**
* {@inheritdoc}
*/
public function validatePayload()
{
if ($this->isFuture($this->getValue())) {
throw new TokenInvalidException('Issued At (iat) timestamp cannot be in the future');
}
}
/**
* {@inheritdoc}
*/
public function validateRefresh($refreshTTL)
{
if ($this->isPast($this->getValue() + $refreshTTL * 60)) {
throw new TokenExpiredException('Token has expired and can no longer be refreshed');
}
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/Factory.php | src/Claims/Factory.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Tymon\JWTAuth\Support\Utils;
class Factory
{
/**
* The request.
*
* @var \Illuminate\Http\Request
*/
protected $request;
/**
* The TTL.
*
* @var int
*/
protected $ttl = 60;
/**
* Time leeway in seconds.
*
* @var int
*/
protected $leeway = 0;
/**
* The classes map.
*
* @var array
*/
private $classMap = [
'aud' => Audience::class,
'exp' => Expiration::class,
'iat' => IssuedAt::class,
'iss' => Issuer::class,
'jti' => JwtId::class,
'nbf' => NotBefore::class,
'sub' => Subject::class,
];
/**
* Constructor.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Get the instance of the claim when passing the name and value.
*
* @param string $name
* @param mixed $value
* @return \Tymon\JWTAuth\Claims\Claim
*/
public function get($name, $value)
{
if ($this->has($name)) {
$claim = new $this->classMap[$name]($value);
return method_exists($claim, 'setLeeway') ?
$claim->setLeeway($this->leeway) :
$claim;
}
return new Custom($name, $value);
}
/**
* Check whether the claim exists.
*
* @param string $name
* @return bool
*/
public function has($name)
{
return array_key_exists($name, $this->classMap);
}
/**
* Generate the initial value and return the Claim instance.
*
* @param string $name
* @return \Tymon\JWTAuth\Claims\Claim
*/
public function make($name)
{
return $this->get($name, $this->$name());
}
/**
* Get the Issuer (iss) claim.
*
* @return string
*/
public function iss()
{
return $this->request->url();
}
/**
* Get the Issued At (iat) claim.
*
* @return int
*/
public function iat()
{
return Utils::now()->getTimestamp();
}
/**
* Get the Expiration (exp) claim.
*
* @return int
*/
public function exp()
{
return Utils::now()->addMinutes($this->ttl)->getTimestamp();
}
/**
* Get the Not Before (nbf) claim.
*
* @return int
*/
public function nbf()
{
return Utils::now()->getTimestamp();
}
/**
* Get the JWT Id (jti) claim.
*
* @return string
*/
public function jti()
{
return Str::random();
}
/**
* Add a new claim mapping.
*
* @param string $name
* @param string $classPath
* @return $this
*/
public function extend($name, $classPath)
{
$this->classMap[$name] = $classPath;
return $this;
}
/**
* Set the request instance.
*
* @param \Illuminate\Http\Request $request
* @return $this
*/
public function setRequest(Request $request)
{
$this->request = $request;
return $this;
}
/**
* Set the token ttl (in minutes).
*
* @param int $ttl
* @return $this
*/
public function setTTL($ttl)
{
$this->ttl = $ttl;
return $this;
}
/**
* Get the token ttl.
*
* @return int
*/
public function getTTL()
{
return $this->ttl;
}
/**
* Set the leeway in seconds.
*
* @param int $leeway
* @return $this
*/
public function setLeeway($leeway)
{
$this->leeway = $leeway;
return $this;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Claims/Expiration.php | src/Claims/Expiration.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Claims;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
class Expiration extends Claim
{
use DatetimeTrait;
/**
* {@inheritdoc}
*/
protected $name = 'exp';
/**
* {@inheritdoc}
*/
public function validatePayload()
{
if ($this->isPast($this->getValue())) {
throw new TokenExpiredException('Token has expired');
}
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Providers/LumenServiceProvider.php | src/Providers/LumenServiceProvider.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Providers;
use Tymon\JWTAuth\Http\Parser\LumenRouteParams;
class LumenServiceProvider extends AbstractServiceProvider
{
/**
* {@inheritdoc}
*/
public function boot()
{
$this->app->configure('jwt');
$path = realpath(__DIR__.'/../../config/config.php');
$this->mergeConfigFrom($path, 'jwt');
$this->app->routeMiddleware($this->middlewareAliases);
$this->extendAuthGuard();
$this->app['tymon.jwt.parser']->addParser(new LumenRouteParams);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Providers/LaravelServiceProvider.php | src/Providers/LaravelServiceProvider.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Providers;
use Tymon\JWTAuth\Http\Parser\Cookies;
use Tymon\JWTAuth\Http\Parser\RouteParams;
class LaravelServiceProvider extends AbstractServiceProvider
{
/**
* {@inheritdoc}
*/
public function boot()
{
$path = realpath(__DIR__.'/../../config/config.php');
$this->publishes([$path => config_path('jwt.php')], 'config');
$this->mergeConfigFrom($path, 'jwt');
$this->aliasMiddleware();
$this->extendAuthGuard();
$this->app['tymon.jwt.parser']->addParser([
new RouteParams,
new Cookies($this->config('decrypt_cookies')),
]);
}
/**
* {@inheritdoc}
*/
protected function registerStorageProvider()
{
$this->app->singleton('tymon.jwt.provider.storage', function () {
$instance = $this->getConfigInstance('providers.storage');
if (method_exists($instance, 'setLaravelVersion')) {
$instance->setLaravelVersion($this->app->version());
}
return $instance;
});
}
/**
* Alias the middleware.
*
* @return void
*/
protected function aliasMiddleware()
{
$router = $this->app['router'];
$method = method_exists($router, 'aliasMiddleware') ? 'aliasMiddleware' : 'middleware';
foreach ($this->middlewareAliases as $alias => $middleware) {
$router->$method($alias, $middleware);
}
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Providers/AbstractServiceProvider.php | src/Providers/AbstractServiceProvider.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Providers;
use Illuminate\Support\ServiceProvider;
use Namshi\JOSE\JWS;
use Tymon\JWTAuth\Blacklist;
use Tymon\JWTAuth\Claims\Factory as ClaimFactory;
use Tymon\JWTAuth\Console\JWTGenerateSecretCommand;
use Tymon\JWTAuth\Contracts\Providers\Auth;
use Tymon\JWTAuth\Contracts\Providers\JWT as JWTContract;
use Tymon\JWTAuth\Contracts\Providers\Storage;
use Tymon\JWTAuth\Factory;
use Tymon\JWTAuth\Http\Middleware\Authenticate;
use Tymon\JWTAuth\Http\Middleware\AuthenticateAndRenew;
use Tymon\JWTAuth\Http\Middleware\Check;
use Tymon\JWTAuth\Http\Middleware\RefreshToken;
use Tymon\JWTAuth\Http\Parser\AuthHeaders;
use Tymon\JWTAuth\Http\Parser\InputSource;
use Tymon\JWTAuth\Http\Parser\Parser;
use Tymon\JWTAuth\Http\Parser\QueryString;
use Tymon\JWTAuth\JWT;
use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\JWTGuard;
use Tymon\JWTAuth\Manager;
use Tymon\JWTAuth\Providers\JWT\Lcobucci;
use Tymon\JWTAuth\Providers\JWT\Namshi;
use Tymon\JWTAuth\Validators\PayloadValidator;
abstract class AbstractServiceProvider extends ServiceProvider
{
/**
* The middleware aliases.
*
* @var array
*/
protected $middlewareAliases = [
'jwt.auth' => Authenticate::class,
'jwt.check' => Check::class,
'jwt.refresh' => RefreshToken::class,
'jwt.renew' => AuthenticateAndRenew::class,
];
/**
* Boot the service provider.
*
* @return void
*/
abstract public function boot();
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerAliases();
$this->registerJWTProvider();
$this->registerAuthProvider();
$this->registerStorageProvider();
$this->registerJWTBlacklist();
$this->registerManager();
$this->registerTokenParser();
$this->registerJWT();
$this->registerJWTAuth();
$this->registerPayloadValidator();
$this->registerClaimFactory();
$this->registerPayloadFactory();
$this->registerJWTCommand();
$this->commands('tymon.jwt.secret');
}
/**
* Extend Laravel's Auth.
*
* @return void
*/
protected function extendAuthGuard()
{
$this->app['auth']->extend('jwt', function ($app, $name, array $config) {
$guard = new JWTGuard(
$app['tymon.jwt'],
$app['auth']->createUserProvider($config['provider']),
$app['request']
);
$app->refresh('request', $guard, 'setRequest');
return $guard;
});
}
/**
* Bind some aliases.
*
* @return void
*/
protected function registerAliases()
{
$this->app->alias('tymon.jwt', JWT::class);
$this->app->alias('tymon.jwt.auth', JWTAuth::class);
$this->app->alias('tymon.jwt.provider.jwt', JWTContract::class);
$this->app->alias('tymon.jwt.provider.jwt.namshi', Namshi::class);
$this->app->alias('tymon.jwt.provider.jwt.lcobucci', Lcobucci::class);
$this->app->alias('tymon.jwt.provider.auth', Auth::class);
$this->app->alias('tymon.jwt.provider.storage', Storage::class);
$this->app->alias('tymon.jwt.manager', Manager::class);
$this->app->alias('tymon.jwt.blacklist', Blacklist::class);
$this->app->alias('tymon.jwt.payload.factory', Factory::class);
$this->app->alias('tymon.jwt.validators.payload', PayloadValidator::class);
}
/**
* Register the bindings for the JSON Web Token provider.
*
* @return void
*/
protected function registerJWTProvider()
{
$this->registerNamshiProvider();
$this->registerLcobucciProvider();
$this->app->singleton('tymon.jwt.provider.jwt', function ($app) {
return $this->getConfigInstance('providers.jwt');
});
}
/**
* Register the bindings for the Lcobucci JWT provider.
*
* @return void
*/
protected function registerNamshiProvider()
{
$this->app->singleton('tymon.jwt.provider.jwt.namshi', function ($app) {
return new Namshi(
new JWS(['typ' => 'JWT', 'alg' => $this->config('algo')]),
$this->config('secret'),
$this->config('algo'),
$this->config('keys')
);
});
}
/**
* Register the bindings for the Lcobucci JWT provider.
*
* @return void
*/
protected function registerLcobucciProvider()
{
$this->app->singleton('tymon.jwt.provider.jwt.lcobucci', function ($app) {
return new Lcobucci(
$this->config('secret'),
$this->config('algo'),
$this->config('keys')
);
});
}
/**
* Register the bindings for the Auth provider.
*
* @return void
*/
protected function registerAuthProvider()
{
$this->app->singleton('tymon.jwt.provider.auth', function () {
return $this->getConfigInstance('providers.auth');
});
}
/**
* Register the bindings for the Storage provider.
*
* @return void
*/
protected function registerStorageProvider()
{
$this->app->singleton('tymon.jwt.provider.storage', function () {
return $this->getConfigInstance('providers.storage');
});
}
/**
* Register the bindings for the JWT Manager.
*
* @return void
*/
protected function registerManager()
{
$this->app->singleton('tymon.jwt.manager', function ($app) {
$instance = new Manager(
$app['tymon.jwt.provider.jwt'],
$app['tymon.jwt.blacklist'],
$app['tymon.jwt.payload.factory']
);
return $instance->setBlacklistEnabled((bool) $this->config('blacklist_enabled'))
->setPersistentClaims($this->config('persistent_claims'));
});
}
/**
* Register the bindings for the Token Parser.
*
* @return void
*/
protected function registerTokenParser()
{
$this->app->singleton('tymon.jwt.parser', function ($app) {
$parser = new Parser(
$app['request'],
[
new AuthHeaders,
new QueryString,
new InputSource,
]
);
$app->refresh('request', $parser, 'setRequest');
return $parser;
});
}
/**
* Register the bindings for the main JWT class.
*
* @return void
*/
protected function registerJWT()
{
$this->app->singleton('tymon.jwt', function ($app) {
return (new JWT(
$app['tymon.jwt.manager'],
$app['tymon.jwt.parser']
))->lockSubject($this->config('lock_subject'));
});
}
/**
* Register the bindings for the main JWTAuth class.
*
* @return void
*/
protected function registerJWTAuth()
{
$this->app->singleton('tymon.jwt.auth', function ($app) {
return (new JWTAuth(
$app['tymon.jwt.manager'],
$app['tymon.jwt.provider.auth'],
$app['tymon.jwt.parser']
))->lockSubject($this->config('lock_subject'));
});
}
/**
* Register the bindings for the Blacklist.
*
* @return void
*/
protected function registerJWTBlacklist()
{
$this->app->singleton('tymon.jwt.blacklist', function ($app) {
$instance = new Blacklist($app['tymon.jwt.provider.storage']);
return $instance->setGracePeriod($this->config('blacklist_grace_period'))
->setRefreshTTL($this->config('refresh_ttl'));
});
}
/**
* Register the bindings for the payload validator.
*
* @return void
*/
protected function registerPayloadValidator()
{
$this->app->singleton('tymon.jwt.validators.payload', function () {
return (new PayloadValidator)
->setRefreshTTL($this->config('refresh_ttl'))
->setRequiredClaims($this->config('required_claims'));
});
}
/**
* Register the bindings for the Claim Factory.
*
* @return void
*/
protected function registerClaimFactory()
{
$this->app->singleton('tymon.jwt.claim.factory', function ($app) {
$factory = new ClaimFactory($app['request']);
$app->refresh('request', $factory, 'setRequest');
return $factory->setTTL($this->config('ttl'))
->setLeeway($this->config('leeway'));
});
}
/**
* Register the bindings for the Payload Factory.
*
* @return void
*/
protected function registerPayloadFactory()
{
$this->app->singleton('tymon.jwt.payload.factory', function ($app) {
return new Factory(
$app['tymon.jwt.claim.factory'],
$app['tymon.jwt.validators.payload']
);
});
}
/**
* Register the Artisan command.
*
* @return void
*/
protected function registerJWTCommand()
{
$this->app->singleton('tymon.jwt.secret', function () {
return new JWTGenerateSecretCommand;
});
}
/**
* Helper to get the config values.
*
* @param string $key
* @param string $default
* @return mixed
*/
protected function config($key, $default = null)
{
return config("jwt.$key", $default);
}
/**
* Get an instantiable configuration instance.
*
* @param string $key
* @return mixed
*/
protected function getConfigInstance($key)
{
$instance = $this->config($key);
if (is_string($instance)) {
return $this->app->make($instance);
}
return $instance;
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Providers/Storage/Illuminate.php | src/Providers/Storage/Illuminate.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Providers\Storage;
use BadMethodCallException;
use Illuminate\Contracts\Cache\Repository as CacheContract;
use Psr\SimpleCache\CacheInterface as PsrCacheInterface;
use Tymon\JWTAuth\Contracts\Providers\Storage;
class Illuminate implements Storage
{
/**
* The cache repository contract.
*
* @var \Illuminate\Contracts\Cache\Repository
*/
protected $cache;
/**
* The used cache tag.
*
* @var string
*/
protected $tag = 'tymon.jwt';
/**
* @var bool
*/
protected $supportsTags;
/**
* @var string|null
*/
protected $laravelVersion;
/**
* Constructor.
*
* @param \Illuminate\Contracts\Cache\Repository $cache
* @return void
*/
public function __construct(CacheContract $cache)
{
$this->cache = $cache;
}
/**
* Add a new item into storage.
*
* @param string $key
* @param mixed $value
* @param int $minutes
* @return void
*/
public function add($key, $value, $minutes)
{
// If the laravel version is 5.8 or higher then convert minutes to seconds.
if ($this->laravelVersion !== null
&& is_int($minutes)
&& version_compare($this->laravelVersion, '5.8', '>=')
) {
$minutes = $minutes * 60;
}
$this->cache()->put($key, $value, $minutes);
}
/**
* Add a new item into storage forever.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function forever($key, $value)
{
$this->cache()->forever($key, $value);
}
/**
* Get an item from storage.
*
* @param string $key
* @return mixed
*/
public function get($key)
{
return $this->cache()->get($key);
}
/**
* Remove an item from storage.
*
* @param string $key
* @return bool
*/
public function destroy($key)
{
return $this->cache()->forget($key);
}
/**
* Remove all items associated with the tag.
*
* @return void
*/
public function flush()
{
$this->cache()->flush();
}
/**
* Return the cache instance with tags attached.
*
* @return \Illuminate\Contracts\Cache\Repository
*/
protected function cache()
{
if ($this->supportsTags === null) {
$this->determineTagSupport();
}
if ($this->supportsTags) {
return $this->cache->tags($this->tag);
}
return $this->cache;
}
/**
* Set the laravel version.
*/
public function setLaravelVersion($version)
{
$this->laravelVersion = $version;
return $this;
}
/**
* Detect as best we can whether tags are supported with this repository & store,
* and save our result on the $supportsTags flag.
*
* @return void
*/
protected function determineTagSupport()
{
// Laravel >= 5.1.28
if (method_exists($this->cache, 'tags') || $this->cache instanceof PsrCacheInterface) {
try {
// Attempt the repository tags command, which throws exceptions when unsupported
$this->cache->tags($this->tag);
$this->supportsTags = true;
} catch (BadMethodCallException $ex) {
$this->supportsTags = false;
}
} else {
// Laravel <= 5.1.27
if (method_exists($this->cache, 'getStore')) {
// Check for the tags function directly on the store
$this->supportsTags = method_exists($this->cache->getStore(), 'tags');
} else {
// Must be using custom cache repository without getStore(), and all bets are off,
// or we are mocking the cache contract (in testing), which will not create a getStore method
$this->supportsTags = false;
}
}
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Providers/Auth/Illuminate.php | src/Providers/Auth/Illuminate.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Providers\Auth;
use Illuminate\Contracts\Auth\Guard as GuardContract;
use Tymon\JWTAuth\Contracts\Providers\Auth;
class Illuminate implements Auth
{
/**
* The authentication guard.
*
* @var \Illuminate\Contracts\Auth\Guard
*/
protected $auth;
/**
* Constructor.
*
* @param \Illuminate\Contracts\Auth\Guard $auth
* @return void
*/
public function __construct(GuardContract $auth)
{
$this->auth = $auth;
}
/**
* Check a user's credentials.
*
* @param array $credentials
* @return bool
*/
public function byCredentials(array $credentials)
{
return $this->auth->once($credentials);
}
/**
* Authenticate a user via the id.
*
* @param mixed $id
* @return bool
*/
public function byId($id)
{
return $this->auth->onceUsingId($id);
}
/**
* Get the currently authenticated user.
*
* @return mixed
*/
public function user()
{
return $this->auth->user();
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Providers/JWT/Provider.php | src/Providers/JWT/Provider.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Providers\JWT;
use Illuminate\Support\Arr;
abstract class Provider
{
const ALGO_HS256 = 'HS256';
const ALGO_HS384 = 'HS384';
const ALGO_HS512 = 'HS512';
const ALGO_RS256 = 'RS256';
const ALGO_RS384 = 'RS384';
const ALGO_RS512 = 'RS512';
const ALGO_ES256 = 'ES256';
const ALGO_ES384 = 'ES384';
const ALGO_ES512 = 'ES512';
/**
* The secret.
*
* @var string
*/
protected $secret;
/**
* The array of keys.
*
* @var array
*/
protected $keys;
/**
* The used algorithm.
*
* @var string
*/
protected $algo;
/**
* Constructor.
*
* @param string $secret
* @param string $algo
* @param array $keys
* @return void
*/
public function __construct($secret, $algo, array $keys)
{
$this->secret = $secret;
$this->algo = $algo;
$this->keys = $keys;
}
/**
* Set the algorithm used to sign the token.
*
* @param string $algo
* @return $this
*/
public function setAlgo($algo)
{
$this->algo = $algo;
return $this;
}
/**
* Get the algorithm used to sign the token.
*
* @return string
*/
public function getAlgo()
{
return $this->algo;
}
/**
* Set the secret used to sign the token.
*
* @param string $secret
* @return $this
*/
public function setSecret($secret)
{
$this->secret = $secret;
return $this;
}
/**
* Get the secret used to sign the token.
*
* @return string
*/
public function getSecret()
{
return $this->secret;
}
/**
* Set the keys used to sign the token.
*
* @param array $keys
* @return $this
*/
public function setKeys(array $keys)
{
$this->keys = $keys;
return $this;
}
/**
* Get the array of keys used to sign tokens with an asymmetric algorithm.
*
* @return array
*/
public function getKeys()
{
return $this->keys;
}
/**
* Get the public key used to sign tokens with an asymmetric algorithm.
*
* @return string|null
*/
public function getPublicKey()
{
return Arr::get($this->keys, 'public');
}
/**
* Get the private key used to sign tokens with an asymmetric algorithm.
*
* @return string|null
*/
public function getPrivateKey()
{
return Arr::get($this->keys, 'private');
}
/**
* Get the passphrase used to sign tokens
* with an asymmetric algorithm.
*
* @return string|null
*/
public function getPassphrase()
{
return Arr::get($this->keys, 'passphrase');
}
/**
* Get the key used to sign the tokens.
*
* @return string|null
*/
protected function getSigningKey()
{
return $this->isAsymmetric() ? $this->getPrivateKey() : $this->getSecret();
}
/**
* Get the key used to verify the tokens.
*
* @return string|null
*/
protected function getVerificationKey()
{
return $this->isAsymmetric() ? $this->getPublicKey() : $this->getSecret();
}
/**
* Determine if the algorithm is asymmetric, and thus requires a public/private key combo.
*
* @return bool
*/
abstract protected function isAsymmetric();
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/src/Providers/JWT/Lcobucci.php | src/Providers/JWT/Lcobucci.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Providers\JWT;
use DateTimeImmutable;
use DateTimeInterface;
use Exception;
use Illuminate\Support\Collection;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Ecdsa;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Rsa;
use Lcobucci\JWT\Token\Builder;
use Lcobucci\JWT\Token\RegisteredClaims;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Tymon\JWTAuth\Contracts\Providers\JWT;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
class Lcobucci extends Provider implements JWT
{
/**
* \Lcobucci\JWT\Signer.
*/
protected $signer;
/**
* \Lcobucci\JWT\Configuration.
*/
protected $config;
/**
* Create the Lcobucci provider.
*
* @param string $secret
* @param string $algo
* @param array $keys
* @param \Lcobucci\JWT\Configuration|null $config
* @return void
*/
public function __construct($secret, $algo, array $keys, $config = null)
{
parent::__construct($secret, $algo, $keys);
$this->signer = $this->getSigner();
$this->config = $config ?: $this->buildConfig();
}
/**
* Signers that this provider supports.
*
* @var array
*/
protected $signers = [
self::ALGO_HS256 => Signer\Hmac\Sha256::class,
self::ALGO_HS384 => Signer\Hmac\Sha384::class,
self::ALGO_HS512 => Signer\Hmac\Sha512::class,
self::ALGO_RS256 => Signer\Rsa\Sha256::class,
self::ALGO_RS384 => Signer\Rsa\Sha384::class,
self::ALGO_RS512 => Signer\Rsa\Sha512::class,
self::ALGO_ES256 => Signer\Ecdsa\Sha256::class,
self::ALGO_ES384 => Signer\Ecdsa\Sha384::class,
self::ALGO_ES512 => Signer\Ecdsa\Sha512::class,
];
/**
* Create a JSON Web Token.
*
* @param array $payload
* @return string
*
* @throws \Tymon\JWTAuth\Exceptions\JWTException
*/
public function encode(array $payload)
{
$builder = $this->getBuilderFromClaims($payload);
try {
return $builder
->getToken($this->config->signer(), $this->config->signingKey())
->toString();
} catch (Exception $e) {
throw new JWTException('Could not create token: '.$e->getMessage(), $e->getCode(), $e);
}
}
/**
* Decode a JSON Web Token.
*
* @param string $token
* @return array
*
* @throws \Tymon\JWTAuth\Exceptions\JWTException
*/
public function decode($token)
{
try {
/** @var \Lcobucci\JWT\Token\Plain */
$token = $this->config->parser()->parse($token);
} catch (Exception $e) {
throw new TokenInvalidException('Could not decode token: '.$e->getMessage(), $e->getCode(), $e);
}
if (! $this->config->validator()->validate($token, ...$this->config->validationConstraints())) {
throw new TokenInvalidException('Token Signature could not be verified.');
}
return Collection::wrap($token->claims()->all())
->map(function ($claim) {
if ($claim instanceof DateTimeInterface) {
return $claim->getTimestamp();
}
return is_object($claim) && method_exists($claim, 'getValue')
? $claim->getValue()
: $claim;
})
->toArray();
}
/**
* Create an instance of the builder with all of the claims applied.
*
* @param array $payload
* @return \Lcobucci\JWT\Token\Builder
*/
protected function getBuilderFromClaims(array $payload): Builder
{
$builder = $this->config->builder();
foreach ($payload as $key => $value) {
switch ($key) {
case RegisteredClaims::ID:
$builder->identifiedBy($value);
break;
case RegisteredClaims::EXPIRATION_TIME:
$builder->expiresAt(DateTimeImmutable::createFromFormat('U', $value));
break;
case RegisteredClaims::NOT_BEFORE:
$builder->canOnlyBeUsedAfter(DateTimeImmutable::createFromFormat('U', $value));
break;
case RegisteredClaims::ISSUED_AT:
$builder->issuedAt(DateTimeImmutable::createFromFormat('U', $value));
break;
case RegisteredClaims::ISSUER:
$builder->issuedBy($value);
break;
case RegisteredClaims::AUDIENCE:
$builder->permittedFor($value);
break;
case RegisteredClaims::SUBJECT:
$builder->relatedTo($value);
break;
default:
$builder->withClaim($key, $value);
}
}
return $builder;
}
/**
* Build the configuration.
*
* @return \Lcobucci\JWT\Configuration
*/
protected function buildConfig(): Configuration
{
$config = $this->isAsymmetric()
? Configuration::forAsymmetricSigner(
$this->signer,
$this->getSigningKey(),
$this->getVerificationKey()
)
: Configuration::forSymmetricSigner($this->signer, $this->getSigningKey());
$config->setValidationConstraints(
new SignedWith($this->signer, $this->getVerificationKey())
);
return $config;
}
/**
* Get the signer instance.
*
* @return \Lcobucci\JWT\Signer
*
* @throws \Tymon\JWTAuth\Exceptions\JWTException
*/
protected function getSigner()
{
if (! array_key_exists($this->algo, $this->signers)) {
throw new JWTException('The given algorithm could not be found');
}
$signer = $this->signers[$this->algo];
if (is_subclass_of($signer, Ecdsa::class)) {
return $signer::create();
}
return new $signer();
}
/**
* {@inheritdoc}
*/
protected function isAsymmetric()
{
return is_subclass_of($this->signer, Rsa::class)
|| is_subclass_of($this->signer, Ecdsa::class);
}
/**
* {@inheritdoc}
*
* @return \Lcobucci\JWT\Signer\Key
*
* @throws \Tymon\JWTAuth\Exceptions\JWTException
*/
protected function getSigningKey()
{
if ($this->isAsymmetric()) {
if (! $privateKey = $this->getPrivateKey()) {
throw new JWTException('Private key is not set.');
}
return $this->getKey($privateKey, $this->getPassphrase() ?? '');
}
if (! $secret = $this->getSecret()) {
throw new JWTException('Secret is not set.');
}
return $this->getKey($secret);
}
/**
* {@inheritdoc}
*
* @return \Lcobucci\JWT\Signer\Key
*
* @throws \Tymon\JWTAuth\Exceptions\JWTException
*/
protected function getVerificationKey()
{
if ($this->isAsymmetric()) {
if (! $public = $this->getPublicKey()) {
throw new JWTException('Public key is not set.');
}
return $this->getKey($public);
}
if (! $secret = $this->getSecret()) {
throw new JWTException('Secret is not set.');
}
return $this->getKey($secret);
}
/**
* Get the signing key instance.
*/
protected function getKey(string $contents, string $passphrase = ''): Key
{
return InMemory::plainText($contents, $passphrase);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/JWTAuthTest.php | tests/JWTAuthTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test;
use Illuminate\Http\Request;
use Mockery;
use stdClass;
use Tymon\JWTAuth\Contracts\Providers\Auth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Factory;
use Tymon\JWTAuth\Http\Parser\Parser;
use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\Manager;
use Tymon\JWTAuth\Payload;
use Tymon\JWTAuth\Test\Stubs\UserStub;
use Tymon\JWTAuth\Token;
class JWTAuthTest extends AbstractTestCase
{
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\Manager
*/
protected $manager;
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\Contracts\Providers\Auth
*/
protected $auth;
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\Http\Parser\Parser
*/
protected $parser;
/**
* @var \Tymon\JWTAuth\JWTAuth
*/
protected $jwtAuth;
public function setUp(): void
{
$this->manager = Mockery::mock(Manager::class);
$this->auth = Mockery::mock(Auth::class);
$this->parser = Mockery::mock(Parser::class);
$this->jwtAuth = new JWTAuth($this->manager, $this->auth, $this->parser);
}
/** @test */
public function it_should_return_a_token_when_passing_a_user()
{
$payloadFactory = Mockery::mock(Factory::class);
$payloadFactory->shouldReceive('make')->andReturn(Mockery::mock(Payload::class));
$this->manager
->shouldReceive('getPayloadFactory->customClaims')
->once()
->with(['sub' => 1, 'prv' => sha1('Tymon\JWTAuth\Test\Stubs\UserStub'), 'foo' => 'bar', 'role' => 'admin'])
->andReturn($payloadFactory);
$this->manager->shouldReceive('encode->get')->once()->andReturn('foo.bar.baz');
$token = $this->jwtAuth->fromUser(new UserStub);
$this->assertSame($token, 'foo.bar.baz');
}
/** @test */
public function it_should_pass_provider_check_if_hash_matches()
{
$payloadFactory = Mockery::mock(Factory::class);
$payloadFactory->shouldReceive('make')->andReturn(Mockery::mock(Payload::class));
$payloadFactory->shouldReceive('get')
->with('prv')
->andReturn(sha1('Tymon\JWTAuth\Test\Stubs\UserStub'));
$this->manager->shouldReceive('decode')->once()->andReturn($payloadFactory);
$this->assertTrue($this->jwtAuth->setToken('foo.bar.baz')->checkSubjectModel('Tymon\JWTAuth\Test\Stubs\UserStub'));
}
/** @test */
public function it_should_pass_provider_check_if_hash_matches_when_provider_is_null()
{
$payloadFactory = Mockery::mock(Factory::class);
$payloadFactory->shouldReceive('make')->andReturn(Mockery::mock(Payload::class));
$payloadFactory->shouldReceive('get')
->with('prv')
->andReturnNull();
$this->manager->shouldReceive('decode')->once()->andReturn($payloadFactory);
$this->assertTrue($this->jwtAuth->setToken('foo.bar.baz')->checkSubjectModel('Tymon\JWTAuth\Test\Stubs\UserStub'));
}
/** @test */
public function it_should_not_pass_provider_check_if_hash_not_match()
{
$payloadFactory = Mockery::mock(Factory::class);
$payloadFactory->shouldReceive('make')->andReturn(Mockery::mock(Payload::class));
$payloadFactory->shouldReceive('get')
->with('prv')
->andReturn(sha1('Tymon\JWTAuth\Test\Stubs\UserStub1'));
$this->manager->shouldReceive('decode')->once()->andReturn($payloadFactory);
$this->assertFalse($this->jwtAuth->setToken('foo.bar.baz')->checkSubjectModel('Tymon\JWTAuth\Test\Stubs\UserStub'));
}
/** @test */
public function it_should_return_a_token_when_passing_valid_credentials_to_attempt_method()
{
$payloadFactory = Mockery::mock(Factory::class);
$payloadFactory->shouldReceive('make')->andReturn(Mockery::mock(Payload::class));
$this->manager
->shouldReceive('getPayloadFactory->customClaims')
->once()
->with(['sub' => 1, 'prv' => sha1('Tymon\JWTAuth\Test\Stubs\UserStub'), 'foo' => 'bar', 'role' => 'admin'])
->andReturn($payloadFactory);
$this->manager->shouldReceive('encode->get')->once()->andReturn('foo.bar.baz');
$this->auth->shouldReceive('byCredentials')->once()->andReturn(true);
$this->auth->shouldReceive('user')->once()->andReturn(new UserStub);
$token = $this->jwtAuth->attempt(['foo' => 'bar']);
$this->assertSame($token, 'foo.bar.baz');
}
/** @test */
public function it_should_return_false_when_passing_invalid_credentials_to_attempt_method()
{
$this->manager->shouldReceive('encode->get')->never();
$this->auth->shouldReceive('byCredentials')->once()->andReturn(false);
$this->auth->shouldReceive('user')->never();
$token = $this->jwtAuth->attempt(['foo' => 'bar']);
$this->assertFalse($token);
}
/** @test */
public function it_should_throw_an_exception_when_not_providing_a_token()
{
$this->expectException(JWTException::class);
$this->expectExceptionMessage('A token is required');
$this->jwtAuth->toUser();
}
/** @test */
public function it_should_return_the_owning_user_from_a_token_containing_an_existing_user()
{
$payload = Mockery::mock(Payload::class);
$payload->shouldReceive('get')->once()->with('sub')->andReturn(1);
$this->manager->shouldReceive('decode')->once()->andReturn($payload);
$this->auth->shouldReceive('byId')->once()->with(1)->andReturn(true);
$this->auth->shouldReceive('user')->once()->andReturn((object) ['id' => 1]);
$user = $this->jwtAuth->setToken('foo.bar.baz')->customClaims(['foo' => 'bar'])->authenticate();
$this->assertSame($user->id, 1);
}
/** @test */
public function it_should_return_false_when_passing_a_token_not_containing_an_existing_user()
{
$payload = Mockery::mock(Payload::class);
$payload->shouldReceive('get')->once()->with('sub')->andReturn(1);
$this->manager->shouldReceive('decode')->once()->andReturn($payload);
$this->auth->shouldReceive('byId')->once()->with(1)->andReturn(false);
$this->auth->shouldReceive('user')->never();
$user = $this->jwtAuth->setToken('foo.bar.baz')->authenticate();
$this->assertFalse($user);
}
/** @test */
public function it_should_refresh_a_token()
{
$newToken = Mockery::mock(Token::class);
$newToken->shouldReceive('get')->once()->andReturn('baz.bar.foo');
$this->manager->shouldReceive('customClaims->refresh')->once()->andReturn($newToken);
$result = $this->jwtAuth->setToken('foo.bar.baz')->refresh();
$this->assertSame($result, 'baz.bar.foo');
}
/** @test */
public function it_should_invalidate_a_token()
{
$token = new Token('foo.bar.baz');
$this->manager->shouldReceive('invalidate')->once()->with($token, false)->andReturn(true);
$this->jwtAuth->setToken($token)->invalidate();
}
/** @test */
public function it_should_force_invalidate_a_token_forever()
{
$token = new Token('foo.bar.baz');
$this->manager->shouldReceive('invalidate')->once()->with($token, true)->andReturn(true);
$this->jwtAuth->setToken($token)->invalidate(true);
}
/** @test */
public function it_should_retrieve_the_token_from_the_request()
{
$this->parser->shouldReceive('parseToken')->andReturn('foo.bar.baz');
$this->assertInstanceOf(Token::class, $this->jwtAuth->parseToken()->getToken());
$this->assertEquals($this->jwtAuth->getToken(), 'foo.bar.baz');
}
/** @test */
public function it_should_get_the_authenticated_user()
{
$manager = $this->jwtAuth->manager();
$this->assertInstanceOf(Manager::class, $manager);
}
/** @test */
public function it_should_return_false_if_the_token_is_invalid()
{
$this->parser->shouldReceive('parseToken')->andReturn('foo.bar.baz');
$this->manager->shouldReceive('decode')->once()->andThrow(new TokenInvalidException);
$this->assertFalse($this->jwtAuth->parseToken()->check());
}
/** @test */
public function it_should_return_true_if_the_token_is_valid()
{
$payload = Mockery::mock(Payload::class);
$this->parser->shouldReceive('parseToken')->andReturn('foo.bar.baz');
$this->manager->shouldReceive('decode')->once()->andReturn($payload);
$this->assertTrue($this->jwtAuth->parseToken()->check());
}
/** @test */
public function it_should_throw_an_exception_when_token_not_present_in_request()
{
$this->expectException(JWTException::class);
$this->expectExceptionMessage('The token could not be parsed from the request');
$this->parser->shouldReceive('parseToken')->andReturn(false);
$this->jwtAuth->parseToken();
}
/** @test */
public function it_should_return_false_when_no_token_is_set()
{
$this->parser->shouldReceive('parseToken')->andReturn(false);
$this->assertNull($this->jwtAuth->getToken());
}
/** @test */
public function it_should_magically_call_the_manager()
{
$this->manager->shouldReceive('getBlacklist')->andReturn(new stdClass);
$blacklist = $this->jwtAuth->manager()->getBlacklist();
$this->assertInstanceOf(stdClass::class, $blacklist);
}
/** @test */
public function it_should_set_the_request()
{
$request = Request::create('/foo', 'GET', ['token' => 'some.random.token']);
$this->parser->shouldReceive('setRequest')->once()->with($request);
$this->parser->shouldReceive('parseToken')->andReturn('some.random.token');
$token = $this->jwtAuth->setRequest($request)->getToken();
$this->assertEquals('some.random.token', $token);
}
/** @test */
public function it_should_unset_the_token()
{
$this->parser->shouldReceive('parseToken')->andThrow(new JWTException);
$token = new Token('foo.bar.baz');
$this->jwtAuth->setToken($token);
$this->assertSame($this->jwtAuth->getToken(), $token);
$this->jwtAuth->unsetToken();
$this->assertNull($this->jwtAuth->getToken());
}
/** @test */
public function it_should_get_the_manager_instance()
{
$manager = $this->jwtAuth->manager();
$this->assertInstanceOf(Manager::class, $manager);
}
/** @test */
public function it_should_get_the_parser_instance()
{
$parser = $this->jwtAuth->parser();
$this->assertInstanceOf(Parser::class, $parser);
}
/** @test */
public function it_should_get_a_claim_value()
{
$payload = Mockery::mock(Payload::class);
$payload->shouldReceive('get')->once()->with('sub')->andReturn(1);
$this->manager->shouldReceive('decode')->once()->andReturn($payload);
$this->assertSame($this->jwtAuth->setToken('foo.bar.baz')->getClaim('sub'), 1);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/FactoryTest.php | tests/FactoryTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test;
use Mockery;
use Tymon\JWTAuth\Claims\Collection;
use Tymon\JWTAuth\Claims\Custom;
use Tymon\JWTAuth\Claims\Expiration;
use Tymon\JWTAuth\Claims\Factory as ClaimFactory;
use Tymon\JWTAuth\Claims\IssuedAt;
use Tymon\JWTAuth\Claims\Issuer;
use Tymon\JWTAuth\Claims\JwtId;
use Tymon\JWTAuth\Claims\NotBefore;
use Tymon\JWTAuth\Claims\Subject;
use Tymon\JWTAuth\Factory;
use Tymon\JWTAuth\Payload;
use Tymon\JWTAuth\Validators\PayloadValidator;
class FactoryTest extends AbstractTestCase
{
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\Claims\Factory
*/
protected $claimFactory;
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\Validators\PayloadValidator
*/
protected $validator;
/**
* @var \Tymon\JWTAuth\Factory
*/
protected $factory;
public function setUp(): void
{
parent::setUp();
$this->claimFactory = Mockery::mock(ClaimFactory::class);
$this->validator = Mockery::mock(PayloadValidator::class);
$this->factory = new Factory($this->claimFactory, $this->validator);
}
/** @test */
public function it_should_return_a_payload_when_passing_an_array_of_claims()
{
$expTime = $this->testNowTimestamp + 3600;
// these are added from default claims
$this->claimFactory->shouldReceive('make')->twice()->with('iss')->andReturn(new Issuer('/foo'));
$this->claimFactory->shouldReceive('make')->twice()->with('exp')->andReturn(new Expiration($expTime));
$this->claimFactory->shouldReceive('make')->twice()->with('jti')->andReturn(new JwtId('foo'));
$this->claimFactory->shouldReceive('make')->twice()->with('nbf')->andReturn(new NotBefore(123));
$this->claimFactory->shouldReceive('make')->twice()->with('iat')->andReturn(new IssuedAt(123));
// custom claims that override
$this->claimFactory->shouldReceive('get')->twice()->with('sub', 1)->andReturn(new Subject(1));
$this->claimFactory->shouldReceive('get')->twice()->with('jti', 'foo')->andReturn(new JwtId('foo'));
$this->claimFactory->shouldReceive('get')->twice()->with('nbf', 123)->andReturn(new NotBefore(123));
$this->claimFactory->shouldReceive('get')->twice()->with('iat', 123)->andReturn(new IssuedAt(123));
$this->claimFactory->shouldReceive('getTTL')->andReturn(60);
// once
$claims = $this->factory->customClaims([
'sub' => 1,
'jti' => 'foo',
'iat' => 123,
'nbf' => 123,
])->buildClaimsCollection();
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($claims);
// twice
$payload = $this->factory->claims(['sub' => 1, 'jti' => 'foo', 'iat' => 123, 'nbf' => 123])->make();
$this->assertSame($payload->get('sub'), 1);
$this->assertSame($payload->get('iat'), 123);
$this->assertSame($payload['exp'], $expTime);
$this->assertSame($payload['jti'], 'foo');
$this->assertInstanceOf(Payload::class, $payload);
}
/** @test */
public function it_should_return_a_payload_when_chaining_claim_methods()
{
$this->claimFactory->shouldReceive('get')->twice()->with('sub', 1)->andReturn(new Subject(1));
$this->claimFactory->shouldReceive('get')->twice()->with('foo', 'baz')->andReturn(new Custom('foo', 'baz'));
$this->claimFactory->shouldReceive('make')->twice()->with('iss')->andReturn(new Issuer('/foo'));
$this->claimFactory->shouldReceive('make')->twice()->with('exp')->andReturn(new Expiration($this->testNowTimestamp + 3600));
$this->claimFactory->shouldReceive('make')->twice()->with('iat')->andReturn(new IssuedAt($this->testNowTimestamp));
$this->claimFactory->shouldReceive('make')->twice()->with('jti')->andReturn(new JwtId('foo'));
$this->claimFactory->shouldReceive('make')->twice()->with('nbf')->andReturn(new NotBefore($this->testNowTimestamp));
$this->claimFactory->shouldReceive('getTTL')->andReturn(60);
// once
$claims = $this->factory->sub(1)->foo('baz')->buildClaimsCollection();
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($claims);
// twice
$payload = $this->factory->sub(1)->foo('baz')->make();
$this->assertSame($payload['sub'], 1);
$this->assertSame($payload->get('jti'), 'foo');
$this->assertSame($payload->get('foo'), 'baz');
$this->assertInstanceOf(Payload::class, $payload);
}
/** @test */
public function it_should_return_a_payload_when_passing_miltidimensional_array_as_custom_claim_to_make_method()
{
// these are added from default claims
$this->claimFactory->shouldReceive('make')->twice()->with('iss')->andReturn(new Issuer('/foo'));
$this->claimFactory->shouldReceive('make')->twice()->with('exp')->andReturn(new Expiration($this->testNowTimestamp + 3600));
$this->claimFactory->shouldReceive('make')->twice()->with('jti')->andReturn(new JwtId('foo'));
$this->claimFactory->shouldReceive('make')->twice()->with('nbf')->andReturn(new NotBefore(123));
$this->claimFactory->shouldReceive('make')->twice()->with('iat')->andReturn(new IssuedAt(123));
// custom claims that override
$this->claimFactory->shouldReceive('get')->twice()->with('sub', 1)->andReturn(new Subject(1));
$this->claimFactory->shouldReceive('get')->twice()->with('foo', ['bar' => [0, 0, 0]])->andReturn(new Custom('foo', ['bar' => [0, 0, 0]]));
$this->claimFactory->shouldReceive('getTTL')->andReturn(60);
// once
$claims = $this->factory->sub(1)->foo(['bar' => [0, 0, 0]])->buildClaimsCollection();
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($claims);
// twice
$payload = $this->factory->sub(1)->foo(['bar' => [0, 0, 0]])->make();
$this->assertSame($payload->get('sub'), 1);
$this->assertSame($payload->get('jti'), 'foo');
$this->assertSame($payload->get('foo'), ['bar' => [0, 0, 0]]);
$this->assertSame($payload->get('foo.bar'), [0, 0, 0]);
$this->assertInstanceOf(Payload::class, $payload);
}
/** @test */
public function it_should_exclude_the_exp_claim_when_setting_ttl_to_null()
{
// these are added from default claims
$this->claimFactory->shouldReceive('make')->twice()->with('iss')->andReturn(new Issuer('/foo'));
$this->claimFactory->shouldReceive('make')->twice()->with('jti')->andReturn(new JwtId('foo'));
$this->claimFactory->shouldReceive('make')->twice()->with('nbf')->andReturn(new NotBefore(123));
$this->claimFactory->shouldReceive('make')->twice()->with('iat')->andReturn(new IssuedAt(123));
// custom claims that override
$this->claimFactory->shouldReceive('get')->twice()->with('sub', 1)->andReturn(new Subject(1));
$this->claimFactory->shouldReceive('setTTL')->with(null)->andReturn($this->claimFactory);
$this->claimFactory->shouldReceive('getTTL')->andReturn(null);
// once
$claims = $this->factory->setTTL(null)->sub(1)->buildClaimsCollection();
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($claims);
// twice
$payload = $this->factory->setTTL(null)->sub(1)->make();
$this->assertNull($payload->get('exp'));
$this->assertInstanceOf(Payload::class, $payload);
}
/** @test */
public function it_should_exclude_claims_from_previous_payloads()
{
$validator = new PayloadValidator();
$factory = new Factory($this->claimFactory, $validator);
$fooClaim = new Custom('foo', 'bar');
$barClaim = new Custom('baz', 'qux');
$this->claimFactory->shouldReceive('getTTL')->andReturn(60);
$this->claimFactory->shouldReceive('get')->with('foo', 'bar')->twice()->andReturn($fooClaim);
$this->claimFactory->shouldReceive('get')->with('baz', 'qux')->once()->andReturn($barClaim);
$validator->setRequiredClaims([]);
$payload = $factory->setDefaultClaims([])
->customClaims([
'foo' => 'bar',
'baz' => 'qux',
])->make();
$this->assertSame($payload->get('foo'), 'bar');
$this->assertSame($payload->get('baz'), 'qux');
$payload = $factory->setDefaultClaims([])->customClaims(['foo' => 'bar'])->make(true);
$this->assertSame($payload->get('foo'), 'bar');
$this->assertFalse($payload->hasKey('baz'));
}
/** @test */
public function it_should_set_the_default_claims()
{
$this->factory->setDefaultClaims(['sub', 'iat']);
$this->assertSame($this->factory->getDefaultClaims(), ['sub', 'iat']);
}
/** @test */
public function it_should_get_payload_with_a_predefined_collection_of_claims()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = $this->factory->withClaims($collection);
$this->assertInstanceOf(Payload::class, $payload);
$this->assertSame($payload->get('sub'), 1);
}
/** @test */
public function it_should_get_the_validator()
{
$this->assertInstanceOf(PayloadValidator::class, $this->factory->validator());
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/ManagerTest.php | tests/ManagerTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test;
use Mockery;
use Tymon\JWTAuth\Blacklist;
use Tymon\JWTAuth\Claims\Collection;
use Tymon\JWTAuth\Claims\Expiration;
use Tymon\JWTAuth\Claims\IssuedAt;
use Tymon\JWTAuth\Claims\Issuer;
use Tymon\JWTAuth\Claims\JwtId;
use Tymon\JWTAuth\Claims\NotBefore;
use Tymon\JWTAuth\Claims\Subject;
use Tymon\JWTAuth\Contracts\Providers\JWT;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Factory;
use Tymon\JWTAuth\Manager;
use Tymon\JWTAuth\Payload;
use Tymon\JWTAuth\Token;
use Tymon\JWTAuth\Validators\PayloadValidator;
class ManagerTest extends AbstractTestCase
{
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\Contracts\Providers\JWT
*/
protected $jwt;
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\Blacklist
*/
protected $blacklist;
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\Factory
*/
protected $factory;
/**
* @var \Tymon\JWTAuth\Manager
*/
protected $manager;
/**
* @var \Mockery\MockInterface
*/
protected $validator;
public function setUp(): void
{
parent::setUp();
$this->jwt = Mockery::mock(JWT::class);
$this->blacklist = Mockery::mock(Blacklist::class);
$this->factory = Mockery::mock(Factory::class);
$this->manager = new Manager($this->jwt, $this->blacklist, $this->factory);
$this->validator = Mockery::mock(PayloadValidator::class);
}
/** @test */
public function it_should_encode_a_payload()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$this->jwt->shouldReceive('encode')->with($payload->toArray())->andReturn('foo.bar.baz');
$token = $this->manager->encode($payload);
$this->assertEquals($token, 'foo.bar.baz');
}
/** @test */
public function it_should_decode_a_token()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$token = new Token('foo.bar.baz');
$this->jwt->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload->toArray());
$this->factory->shouldReceive('setRefreshFlow')->andReturn($this->factory);
$this->factory->shouldReceive('customClaims')->andReturn($this->factory);
$this->factory->shouldReceive('make')->andReturn($payload);
$this->blacklist->shouldReceive('has')->with($payload)->andReturn(false);
$payload = $this->manager->decode($token);
$this->assertInstanceOf(Payload::class, $payload);
$this->assertSame($payload->count(), 6);
}
/** @test */
public function it_should_throw_exception_when_token_is_blacklisted()
{
$this->expectException(TokenBlacklistedException::class);
$this->expectExceptionMessage('The token has been blacklisted');
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$token = new Token('foo.bar.baz');
$this->jwt->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload->toArray());
$this->factory->shouldReceive('setRefreshFlow')->andReturn($this->factory);
$this->factory->shouldReceive('customClaims')->with($payload->toArray())->andReturn($this->factory);
$this->factory->shouldReceive('make')->andReturn($payload);
$this->blacklist->shouldReceive('has')->with($payload)->andReturn(true);
$this->manager->decode($token);
}
/** @test */
public function it_should_refresh_a_token()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp - 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$token = new Token('foo.bar.baz');
$this->jwt->shouldReceive('decode')->twice()->with('foo.bar.baz')->andReturn($payload->toArray());
$this->jwt->shouldReceive('encode')->with($payload->toArray())->andReturn('baz.bar.foo');
$this->factory->shouldReceive('setRefreshFlow')->with(true)->andReturn($this->factory);
$this->factory->shouldReceive('customClaims')->andReturn($this->factory);
$this->factory->shouldReceive('make')->andReturn($payload);
$this->blacklist->shouldReceive('has')->with($payload)->andReturn(false);
$this->blacklist->shouldReceive('add')->once()->with($payload);
$token = $this->manager->refresh($token);
// $this->assertArrayHasKey('ref', $payload);
$this->assertInstanceOf(Token::class, $token);
$this->assertEquals('baz.bar.foo', $token);
}
/** @test */
public function it_should_invalidate_a_token()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$token = new Token('foo.bar.baz');
$this->jwt->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload->toArray());
$this->factory->shouldReceive('setRefreshFlow')->andReturn($this->factory);
$this->factory->shouldReceive('customClaims')->with($payload->toArray())->andReturn($this->factory);
$this->factory->shouldReceive('make')->andReturn($payload);
$this->blacklist->shouldReceive('has')->with($payload)->andReturn(false);
$this->blacklist->shouldReceive('add')->with($payload)->andReturn(true);
$this->manager->invalidate($token);
}
/** @test */
public function it_should_force_invalidate_a_token_forever()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$token = new Token('foo.bar.baz');
$this->jwt->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload->toArray());
$this->factory->shouldReceive('setRefreshFlow')->andReturn($this->factory);
$this->factory->shouldReceive('customClaims')->with($payload->toArray())->andReturn($this->factory);
$this->factory->shouldReceive('make')->andReturn($payload);
$this->blacklist->shouldReceive('has')->with($payload)->andReturn(false);
$this->blacklist->shouldReceive('addForever')->with($payload)->andReturn(true);
$this->manager->invalidate($token, true);
}
/** @test */
public function it_should_throw_an_exception_when_enable_blacklist_is_set_to_false()
{
$this->expectException(JWTException::class);
$this->expectExceptionMessage('You must have the blacklist enabled to invalidate a token.');
$token = new Token('foo.bar.baz');
$this->manager->setBlacklistEnabled(false)->invalidate($token);
}
/** @test */
public function it_should_get_the_payload_factory()
{
$this->assertInstanceOf(Factory::class, $this->manager->getPayloadFactory());
}
/** @test */
public function it_should_get_the_jwt_provider()
{
$this->assertInstanceOf(JWT::class, $this->manager->getJWTProvider());
}
/** @test */
public function it_should_get_the_blacklist()
{
$this->assertInstanceOf(Blacklist::class, $this->manager->getBlacklist());
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/AbstractTestCase.php | tests/AbstractTestCase.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test;
use Carbon\Carbon;
use Mockery;
use PHPUnit\Framework\TestCase;
abstract class AbstractTestCase extends TestCase
{
/**
* @var int
*/
protected $testNowTimestamp;
public function setUp(): void
{
parent::setUp();
Carbon::setTestNow($now = Carbon::now());
$this->testNowTimestamp = $now->getTimestamp();
}
public function tearDown(): void
{
Carbon::setTestNow();
Mockery::close();
parent::tearDown();
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/PayloadTest.php | tests/PayloadTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test;
use BadMethodCallException;
use Mockery;
use Tymon\JWTAuth\Claims\Audience;
use Tymon\JWTAuth\Claims\Claim;
use Tymon\JWTAuth\Claims\Collection;
use Tymon\JWTAuth\Claims\Expiration;
use Tymon\JWTAuth\Claims\IssuedAt;
use Tymon\JWTAuth\Claims\Issuer;
use Tymon\JWTAuth\Claims\JwtId;
use Tymon\JWTAuth\Claims\NotBefore;
use Tymon\JWTAuth\Claims\Subject;
use Tymon\JWTAuth\Exceptions\PayloadException;
use Tymon\JWTAuth\Payload;
use Tymon\JWTAuth\Validators\PayloadValidator;
class PayloadTest extends AbstractTestCase
{
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\Validators\PayloadValidator
*/
protected $validator;
/**
* @var \Tymon\JWTAuth\Payload
*/
protected $payload;
public function setUp(): void
{
parent::setUp();
$this->payload = $this->getTestPayload();
}
/**
* @param array $extraClaims
* @return \Tymon\JWTAuth\Payload
*/
private function getTestPayload(array $extraClaims = [])
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
if ($extraClaims) {
$claims = array_merge($claims, $extraClaims);
}
$collection = Collection::make($claims);
$this->validator = Mockery::mock(PayloadValidator::class);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
return new Payload($collection, $this->validator);
}
/** @test */
public function it_should_throw_an_exception_when_trying_to_add_to_the_payload()
{
$this->expectException(PayloadException::class);
$this->expectExceptionMessage('The payload is immutable');
$this->payload['foo'] = 'bar';
}
/** @test */
public function it_should_throw_an_exception_when_trying_to_remove_a_key_from_the_payload()
{
$this->expectException(PayloadException::class);
$this->expectExceptionMessage('The payload is immutable');
unset($this->payload['foo']);
}
/** @test */
public function it_should_cast_the_payload_to_a_string_as_json()
{
$this->assertSame((string) $this->payload, json_encode($this->payload->get(), JSON_UNESCAPED_SLASHES));
$this->assertJsonStringEqualsJsonString((string) $this->payload, json_encode($this->payload->get()));
}
/** @test */
public function it_should_allow_array_access_on_the_payload()
{
$this->assertTrue(isset($this->payload['iat']));
$this->assertSame($this->payload['sub'], 1);
$this->assertArrayHasKey('exp', $this->payload);
}
/** @test */
public function it_should_get_properties_of_payload_via_get_method()
{
$this->assertIsArray($this->payload->get());
$this->assertSame($this->payload->get('sub'), 1);
$this->assertSame(
$this->payload->get(function () {
return 'jti';
}),
'foo'
);
}
/** @test */
public function it_should_get_multiple_properties_when_passing_an_array_to_the_get_method()
{
$values = $this->payload->get(['sub', 'jti']);
$sub = $values[0];
$jti = $values[1];
$this->assertIsArray($values);
$this->assertSame($sub, 1);
$this->assertSame($jti, 'foo');
}
/** @test */
public function it_should_determine_whether_the_payload_has_a_claim()
{
$this->assertTrue($this->payload->has(new Subject(1)));
$this->assertFalse($this->payload->has(new Audience(1)));
}
/** @test */
public function it_should_magically_get_a_property()
{
$sub = $this->payload->getSubject();
$jti = $this->payload->getJwtId();
$iss = $this->payload->getIssuer();
$this->assertSame($sub, 1);
$this->assertSame($jti, 'foo');
$this->assertSame($iss, 'http://example.com');
}
/** @test */
public function it_should_invoke_the_instance_as_a_callable()
{
$payload = $this->payload;
$sub = $payload('sub');
$jti = $payload('jti');
$iss = $payload('iss');
$this->assertSame($sub, 1);
$this->assertSame($jti, 'foo');
$this->assertSame($iss, 'http://example.com');
$this->assertSame($payload(), $this->payload->toArray());
}
/** @test */
public function it_should_throw_an_exception_when_magically_getting_a_property_that_does_not_exist()
{
$this->expectException(BadMethodCallException::class);
$this->expectExceptionMessage('The claim [Foo] does not exist on the payload');
$this->payload->getFoo();
}
/** @test */
public function it_should_get_the_claims()
{
$claims = $this->payload->getClaims();
$this->assertInstanceOf(Expiration::class, $claims['exp']);
$this->assertInstanceOf(JwtId::class, $claims['jti']);
$this->assertInstanceOf(Subject::class, $claims['sub']);
$this->assertContainsOnlyInstancesOf(Claim::class, $claims);
}
/** @test */
public function it_should_get_the_object_as_json()
{
$this->assertJsonStringEqualsJsonString(json_encode($this->payload), $this->payload->toJson());
}
/** @test */
public function it_should_count_the_claims()
{
$this->assertSame(6, $this->payload->count());
$this->assertCount(6, $this->payload);
}
/** @test */
public function it_should_match_values()
{
$values = $this->payload->toArray();
$values['sub'] = (string) $values['sub'];
$this->assertTrue($this->payload->matches($values));
}
/** @test */
public function it_should_match_strict_values()
{
$values = $this->payload->toArray();
$this->assertTrue($this->payload->matchesStrict($values));
$this->assertTrue($this->payload->matches($values, true));
}
/** @test */
public function it_should_not_match_empty_values()
{
$this->assertFalse($this->payload->matches([]));
}
/** @test */
public function it_should_not_match_values()
{
$values = $this->payload->toArray();
$values['sub'] = 'dummy_subject';
$this->assertFalse($this->payload->matches($values));
}
/** @test */
public function it_should_not_match_strict_values()
{
$values = $this->payload->toArray();
$values['sub'] = (string) $values['sub'];
$this->assertFalse($this->payload->matchesStrict($values));
$this->assertFalse($this->payload->matches($values, true));
}
/** @test */
public function it_should_not_match_a_non_existing_claim()
{
$values = ['foo' => 'bar'];
$this->assertFalse($this->payload->matches($values));
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/JWTGuardTest.php | tests/JWTGuardTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Http\Request;
use Mockery;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\UserNotDefinedException;
use Tymon\JWTAuth\Factory;
use Tymon\JWTAuth\JWT;
use Tymon\JWTAuth\JWTGuard;
use Tymon\JWTAuth\Payload;
use Tymon\JWTAuth\Test\Stubs\LaravelUserStub;
class JWTGuardTest extends AbstractTestCase
{
/**
* @var \Tymon\JWTAuth\JWT|\Mockery\MockInterface
*/
protected $jwt;
/**
* @var \Illuminate\Contracts\Auth\UserProvider|\Mockery\MockInterface
*/
protected $provider;
/**
* @var \Tymon\JWTAuth\JWTGuard|\Mockery\MockInterface
*/
protected $guard;
public function setUp(): void
{
parent::setUp();
$this->jwt = Mockery::mock(JWT::class);
$this->provider = Mockery::mock(EloquentUserProvider::class);
$this->guard = new JWTGuard($this->jwt, $this->provider, Request::create('/foo', 'GET'));
}
/** @test */
public function it_should_get_the_request()
{
$this->assertInstanceOf(Request::class, $this->guard->getRequest());
}
/** @test */
public function it_should_get_the_authenticated_user_if_a_valid_token_is_provided()
{
$payload = Mockery::mock(Payload::class);
$payload->shouldReceive('offsetGet')->once()->with('sub')->andReturn(1);
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->once()->andReturn('foo.bar.baz');
$this->jwt->shouldReceive('check')->once()->with(true)->andReturn($payload);
$this->jwt->shouldReceive('checkSubjectModel')
->once()
->with('\Tymon\JWTAuth\Test\Stubs\LaravelUserStub')
->andReturn(true);
$this->provider->shouldReceive('getModel')
->once()
->andReturn('\Tymon\JWTAuth\Test\Stubs\LaravelUserStub');
$this->provider->shouldReceive('retrieveById')
->once()
->with(1)
->andReturn((object) ['id' => 1]);
$this->assertSame(1, $this->guard->user()->id);
// check that the user is stored on the object next time round
$this->assertSame(1, $this->guard->user()->id);
$this->assertTrue($this->guard->check());
// also make sure userOrFail does not fail
$this->assertSame(1, $this->guard->userOrFail()->id);
}
/** @test */
public function it_should_get_the_authenticated_user_if_a_valid_token_is_provided_and_not_throw_an_exception()
{
$payload = Mockery::mock(Payload::class);
$payload->shouldReceive('offsetGet')->once()->with('sub')->andReturn(1);
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->once()->andReturn('foo.bar.baz');
$this->jwt->shouldReceive('check')->once()->with(true)->andReturn($payload);
$this->jwt->shouldReceive('checkSubjectModel')
->once()
->with('\Tymon\JWTAuth\Test\Stubs\LaravelUserStub')
->andReturn(true);
$this->provider->shouldReceive('getModel')
->once()
->andReturn('\Tymon\JWTAuth\Test\Stubs\LaravelUserStub');
$this->provider->shouldReceive('retrieveById')
->once()
->with(1)
->andReturn((object) ['id' => 1]);
$this->assertSame(1, $this->guard->userOrFail()->id);
// check that the user is stored on the object next time round
$this->assertSame(1, $this->guard->userOrFail()->id);
$this->assertTrue($this->guard->check());
}
/** @test */
public function it_should_return_null_if_an_invalid_token_is_provided()
{
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->twice()->andReturn('invalid.token.here');
$this->jwt->shouldReceive('check')->twice()->andReturn(false);
$this->jwt->shouldReceive('getPayload->get')->never();
$this->provider->shouldReceive('retrieveById')->never();
$this->assertNull($this->guard->user()); // once
$this->assertFalse($this->guard->check()); // twice
}
/** @test */
public function it_should_return_null_if_no_token_is_provided()
{
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->andReturn(false);
$this->jwt->shouldReceive('check')->never();
$this->jwt->shouldReceive('getPayload->get')->never();
$this->provider->shouldReceive('retrieveById')->never();
$this->assertNull($this->guard->user());
$this->assertFalse($this->guard->check());
}
/** @test */
public function it_should_throw_an_exception_if_an_invalid_token_is_provided()
{
$this->expectException(UserNotDefinedException::class);
$this->expectExceptionMessage('An error occurred');
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->twice()->andReturn('invalid.token.here');
$this->jwt->shouldReceive('check')->twice()->andReturn(false);
$this->jwt->shouldReceive('getPayload->get')->never();
$this->provider->shouldReceive('retrieveById')->never();
$this->assertFalse($this->guard->check()); // once
$this->guard->userOrFail(); // twice, throws the exception
}
/** @test */
public function it_should_throw_an_exception_if_no_token_is_provided()
{
$this->expectException(UserNotDefinedException::class);
$this->expectExceptionMessage('An error occurred');
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->andReturn(false);
$this->jwt->shouldReceive('check')->never();
$this->jwt->shouldReceive('getPayload->get')->never();
$this->provider->shouldReceive('retrieveById')->never();
$this->assertFalse($this->guard->check());
$this->guard->userOrFail(); // throws the exception
}
/** @test */
public function it_should_return_a_token_if_credentials_are_ok_and_user_is_found()
{
$credentials = ['foo' => 'bar', 'baz' => 'bob'];
$user = new LaravelUserStub;
$this->provider->shouldReceive('retrieveByCredentials')
->once()
->with($credentials)
->andReturn($user);
$this->provider->shouldReceive('validateCredentials')
->once()
->with($user, $credentials)
->andReturn(true);
$this->jwt->shouldReceive('fromUser')
->once()
->with($user)
->andReturn('foo.bar.baz');
$this->jwt->shouldReceive('setToken')
->once()
->with('foo.bar.baz')
->andReturnSelf();
$this->jwt->shouldReceive('claims')
->once()
->with(['foo' => 'bar'])
->andReturnSelf();
$token = $this->guard->claims(['foo' => 'bar'])->attempt($credentials);
$this->assertSame($this->guard->getLastAttempted(), $user);
$this->assertSame($token, 'foo.bar.baz');
}
/** @test */
public function it_should_return_true_if_credentials_are_ok_and_user_is_found_when_choosing_not_to_login()
{
$credentials = ['foo' => 'bar', 'baz' => 'bob'];
$user = new LaravelUserStub;
$this->provider->shouldReceive('retrieveByCredentials')
->twice()
->with($credentials)
->andReturn($user);
$this->provider->shouldReceive('validateCredentials')
->twice()
->with($user, $credentials)
->andReturn(true);
$this->assertTrue($this->guard->attempt($credentials, false)); // once
$this->assertTrue($this->guard->validate($credentials)); // twice
}
/** @test */
public function it_should_return_false_if_credentials_are_invalid()
{
$credentials = ['foo' => 'bar', 'baz' => 'bob'];
$user = new LaravelUserStub;
$this->provider->shouldReceive('retrieveByCredentials')
->once()
->with($credentials)
->andReturn($user);
$this->provider->shouldReceive('validateCredentials')
->once()
->with($user, $credentials)
->andReturn(false);
$this->assertFalse($this->guard->attempt($credentials));
}
/** @test */
public function it_should_magically_call_the_jwt_instance()
{
$this->jwt->shouldReceive('factory')->andReturn(Mockery::mock(Factory::class));
$this->assertInstanceOf(Factory::class, $this->guard->factory());
}
/** @test */
public function it_should_logout_the_user_by_invalidating_the_token()
{
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->once()->andReturn(true);
$this->jwt->shouldReceive('invalidate')->once()->andReturn(true);
$this->jwt->shouldReceive('unsetToken')->once();
$this->guard->logout();
$this->assertNull($this->guard->getUser());
}
/** @test */
public function it_should_refresh_the_token()
{
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->once()->andReturn(true);
$this->jwt->shouldReceive('refresh')->once()->andReturn('foo.bar.baz');
$this->assertSame($this->guard->refresh(), 'foo.bar.baz');
}
/** @test */
public function it_should_invalidate_the_token()
{
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->once()->andReturn(true);
$this->jwt->shouldReceive('invalidate')->once()->andReturn(true);
$this->assertTrue($this->guard->invalidate());
}
/** @test */
public function it_should_throw_an_exception_if_there_is_no_token_present_when_required()
{
$this->expectException(JWTException::class);
$this->expectExceptionMessage('Token could not be parsed from the request.');
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->once()->andReturn(false);
$this->jwt->shouldReceive('refresh')->never();
$this->guard->refresh();
}
/** @test */
public function it_should_generate_a_token_by_id()
{
$user = new LaravelUserStub;
$this->provider->shouldReceive('retrieveById')
->once()
->with(1)
->andReturn($user);
$this->jwt->shouldReceive('fromUser')
->once()
->with($user)
->andReturn('foo.bar.baz');
$this->assertSame('foo.bar.baz', $this->guard->tokenById(1));
}
/** @test */
public function it_should_not_generate_a_token_by_id()
{
$this->provider->shouldReceive('retrieveById')
->once()
->with(1)
->andReturn(null);
$this->assertNull($this->guard->tokenById(1));
}
/** @test */
public function it_should_authenticate_the_user_by_credentials_and_return_true_if_valid()
{
$credentials = ['foo' => 'bar', 'baz' => 'bob'];
$user = new LaravelUserStub;
$this->provider->shouldReceive('retrieveByCredentials')
->once()
->with($credentials)
->andReturn($user);
$this->provider->shouldReceive('validateCredentials')
->once()
->with($user, $credentials)
->andReturn(true);
$this->assertTrue($this->guard->once($credentials));
}
/** @test */
public function it_should_attempt_to_authenticate_the_user_by_credentials_and_return_false_if_invalid()
{
$credentials = ['foo' => 'bar', 'baz' => 'bob'];
$user = new LaravelUserStub;
$this->provider->shouldReceive('retrieveByCredentials')
->once()
->with($credentials)
->andReturn($user);
$this->provider->shouldReceive('validateCredentials')
->once()
->with($user, $credentials)
->andReturn(false);
$this->assertFalse($this->guard->once($credentials));
}
/** @test */
public function it_should_authenticate_the_user_by_id_and_return_boolean()
{
$user = new LaravelUserStub;
$this->provider->shouldReceive('retrieveById')
->twice()
->with(1)
->andReturn($user);
$this->assertTrue($this->guard->onceUsingId(1)); // once
$this->assertTrue($this->guard->byId(1)); // twice
}
/** @test */
public function it_should_not_authenticate_the_user_by_id_and_return_false()
{
$this->provider->shouldReceive('retrieveById')
->twice()
->with(1)
->andReturn(null);
$this->assertFalse($this->guard->onceUsingId(1)); // once
$this->assertFalse($this->guard->byId(1)); // twice
}
/** @test */
public function it_should_create_a_token_from_a_user_object()
{
$user = new LaravelUserStub;
$this->jwt->shouldReceive('fromUser')
->once()
->with($user)
->andReturn('foo.bar.baz');
$this->jwt->shouldReceive('setToken')
->once()
->with('foo.bar.baz')
->andReturnSelf();
$token = $this->guard->login($user);
$this->assertSame('foo.bar.baz', $token);
}
/** @test */
public function it_should_get_the_payload()
{
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->once()->andReturn('foo.bar.baz');
$this->jwt->shouldReceive('getPayload')->once()->andReturn(Mockery::mock(Payload::class));
$this->assertInstanceOf(Payload::class, $this->guard->payload());
}
/** @test */
public function it_should_be_macroable()
{
$this->guard->macro('foo', function () {
return 'bar';
});
$this->assertEquals('bar', $this->guard->foo());
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/BlacklistTest.php | tests/BlacklistTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test;
use Mockery;
use Tymon\JWTAuth\Blacklist;
use Tymon\JWTAuth\Claims\Collection;
use Tymon\JWTAuth\Claims\Expiration;
use Tymon\JWTAuth\Claims\IssuedAt;
use Tymon\JWTAuth\Claims\Issuer;
use Tymon\JWTAuth\Claims\JwtId;
use Tymon\JWTAuth\Claims\NotBefore;
use Tymon\JWTAuth\Claims\Subject;
use Tymon\JWTAuth\Contracts\Providers\Storage;
use Tymon\JWTAuth\Payload;
use Tymon\JWTAuth\Validators\PayloadValidator;
class BlacklistTest extends AbstractTestCase
{
/**
* @var \Tymon\JWTAuth\Contracts\Providers\Storage|\Mockery\MockInterface
*/
protected $storage;
/**
* @var \Tymon\JWTAuth\Blacklist
*/
protected $blacklist;
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\Validators\Validator
*/
protected $validator;
public function setUp(): void
{
parent::setUp();
$this->storage = Mockery::mock(Storage::class);
$this->blacklist = new Blacklist($this->storage);
$this->validator = Mockery::mock(PayloadValidator::class);
}
/** @test */
public function it_should_add_a_valid_token_to_the_blacklist()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$refreshTTL = 20161;
$this->storage->shouldReceive('get')
->with('foo')
->once()
->andReturn([]);
$this->storage->shouldReceive('add')
->with('foo', ['valid_until' => $this->testNowTimestamp], $refreshTTL + 1)
->once();
$this->blacklist->setRefreshTTL($refreshTTL)->add($payload);
}
/** @test */
public function it_should_add_a_token_with_no_exp_to_the_blacklist_forever()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$this->storage->shouldReceive('forever')->with('foo', 'forever')->once();
$this->blacklist->add($payload);
}
/** @test */
public function it_should_return_true_when_adding_an_expired_token_to_the_blacklist()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp - 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator, true);
$refreshTTL = 20161;
$this->storage->shouldReceive('get')
->with('foo')
->once()
->andReturn([]);
$this->storage->shouldReceive('add')
->with('foo', ['valid_until' => $this->testNowTimestamp], $refreshTTL + 1)
->once();
$this->assertTrue($this->blacklist->setRefreshTTL($refreshTTL)->add($payload));
}
/** @test */
public function it_should_return_true_early_when_adding_an_item_and_it_already_exists()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp - 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator, true);
$refreshTTL = 20161;
$this->storage->shouldReceive('get')
->with('foo')
->once()
->andReturn(['valid_until' => $this->testNowTimestamp]);
$this->storage->shouldReceive('add')
->with('foo', ['valid_until' => $this->testNowTimestamp], $refreshTTL + 1)
->never();
$this->assertTrue($this->blacklist->setRefreshTTL($refreshTTL)->add($payload));
}
/** @test */
public function it_should_check_whether_a_token_has_been_blacklisted()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foobar'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$this->storage->shouldReceive('get')->with('foobar')->once()->andReturn(['valid_until' => $this->testNowTimestamp]);
$this->assertTrue($this->blacklist->has($payload));
}
public function blacklist_provider()
{
return [
[null],
[0],
[''],
[[]],
[['valid_until' => strtotime('+1day')]],
];
}
/**
* @test
*
* @dataProvider blacklist_provider
*
* @param mixed $result
*/
public function it_should_check_whether_a_token_has_not_been_blacklisted($result)
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foobar'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$this->storage->shouldReceive('get')->with('foobar')->once()->andReturn($result);
$this->assertFalse($this->blacklist->has($payload));
}
/** @test */
public function it_should_check_whether_a_token_has_been_blacklisted_forever()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foobar'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$this->storage->shouldReceive('get')->with('foobar')->once()->andReturn('forever');
$this->assertTrue($this->blacklist->has($payload));
}
/** @test */
public function it_should_check_whether_a_token_has_been_blacklisted_when_the_token_is_not_blacklisted()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foobar'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$this->storage->shouldReceive('get')->with('foobar')->once()->andReturn(null);
$this->assertFalse($this->blacklist->has($payload));
}
/** @test */
public function it_should_remove_a_token_from_the_blacklist()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foobar'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$this->storage->shouldReceive('destroy')->with('foobar')->andReturn(true);
$this->assertTrue($this->blacklist->remove($payload));
}
/** @test */
public function it_should_set_a_custom_unique_key_for_the_blacklist()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foobar'),
];
$collection = Collection::make($claims);
$this->validator->shouldReceive('setRefreshFlow->check')->andReturn($collection);
$payload = new Payload($collection, $this->validator);
$this->storage->shouldReceive('get')->with(1)->once()->andReturn(['valid_until' => $this->testNowTimestamp]);
$this->assertTrue($this->blacklist->setKey('sub')->has($payload));
$this->assertSame(1, $this->blacklist->getKey($payload));
}
/** @test */
public function it_should_empty_the_blacklist()
{
$this->storage->shouldReceive('flush');
$this->assertTrue($this->blacklist->clear());
}
/** @test */
public function it_should_set_and_get_the_blacklist_grace_period()
{
$this->assertInstanceOf(Blacklist::class, $this->blacklist->setGracePeriod(15));
$this->assertSame(15, $this->blacklist->getGracePeriod());
}
/** @test */
public function it_should_set_and_get_the_blacklist_refresh_ttl()
{
$this->assertInstanceOf(Blacklist::class, $this->blacklist->setRefreshTTL(15));
$this->assertSame(15, $this->blacklist->getRefreshTTL());
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/TokenTest.php | tests/TokenTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test;
use Tymon\JWTAuth\Token;
class TokenTest extends AbstractTestCase
{
/**
* @var \Tymon\JWTAuth\Token
*/
protected $token;
public function setUp(): void
{
parent::setUp();
$this->token = new Token('foo.bar.baz');
}
/** @test */
public function it_should_return_the_token_when_casting_to_a_string()
{
$this->assertEquals((string) $this->token, $this->token);
}
/** @test */
public function it_should_return_the_token_when_calling_get_method()
{
$this->assertIsString($this->token->get());
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/Http/ParserTest.php | tests/Http/ParserTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test\Http;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Crypt;
use Mockery;
use Tymon\JWTAuth\Contracts\Http\Parser as ParserContract;
use Tymon\JWTAuth\Http\Parser\AuthHeaders;
use Tymon\JWTAuth\Http\Parser\Cookies;
use Tymon\JWTAuth\Http\Parser\InputSource;
use Tymon\JWTAuth\Http\Parser\LumenRouteParams;
use Tymon\JWTAuth\Http\Parser\Parser;
use Tymon\JWTAuth\Http\Parser\QueryString;
use Tymon\JWTAuth\Http\Parser\RouteParams;
use Tymon\JWTAuth\Test\AbstractTestCase;
class ParserTest extends AbstractTestCase
{
/** @test */
public function it_should_return_the_token_from_the_authorization_header()
{
$request = Request::create('foo', 'POST');
$request->headers->set('Authorization', 'Bearer foobar');
$parser = new Parser($request);
$parser->setChain([
new QueryString,
new InputSource,
new AuthHeaders,
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_the_prefixed_authentication_header()
{
$request = Request::create('foo', 'POST');
$request->headers->set('Authorization', 'Custom foobar');
$parser = new Parser($request);
$parser->setChain([
new QueryString,
new InputSource,
(new AuthHeaders)->setHeaderPrefix('Custom'),
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_the_custom_authentication_header()
{
$request = Request::create('foo', 'POST');
$request->headers->set('custom_authorization', 'Bearer foobar');
$parser = new Parser($request);
$parser->setChain([
new QueryString,
new InputSource,
(new AuthHeaders)->setHeaderName('custom_authorization'),
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_the_alt_authorization_headers()
{
$request1 = Request::create('foo', 'POST');
$request1->server->set('HTTP_AUTHORIZATION', 'Bearer foobar');
$request2 = Request::create('foo', 'POST');
$request2->server->set('REDIRECT_HTTP_AUTHORIZATION', 'Bearer foobarbaz');
$parser = new Parser($request1, [
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
$parser->setRequest($request2);
$this->assertSame($parser->parseToken(), 'foobarbaz');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_ignore_non_bearer_tokens()
{
$request = Request::create('foo', 'POST');
$request->headers->set('Authorization', 'Basic OnBhc3N3b3Jk');
$parser = new Parser($request);
$parser->setChain([
new QueryString,
new InputSource,
new AuthHeaders,
new RouteParams,
]);
$this->assertNull($parser->parseToken());
$this->assertFalse($parser->hasToken());
}
/** @test */
public function it_should_not_strip_trailing_hyphens_from_the_authorization_header()
{
$request = Request::create('foo', 'POST');
$request->headers->set('Authorization', 'Bearer foobar--');
$parser = new Parser($request);
$parser->setChain([
new QueryString,
new InputSource,
new AuthHeaders,
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar--');
$this->assertTrue($parser->hasToken());
}
/**
* @test
*
* @dataProvider whitespaceProvider
*/
public function it_should_handle_excess_whitespace_from_the_authorization_header($whitespace)
{
$request = Request::create('foo', 'POST');
$request->headers->set('Authorization', "Bearer{$whitespace}foobar{$whitespace}");
$parser = new Parser($request);
$parser->setChain([
new QueryString,
new InputSource,
new AuthHeaders,
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
public function whitespaceProvider()
{
return [
'space' => [' '],
'multiple spaces' => [' '],
'tab' => ["\t"],
'multiple tabs' => ["\t\t\t"],
'new line' => ["\n"],
'multiple new lines' => ["\n\n\n"],
'carriage return' => ["\r"],
'carriage returns' => ["\r\r\r"],
'mixture of whitespace' => ["\t \n \r \t \n"],
];
}
/** @test */
public function it_should_return_the_token_from_query_string()
{
$request = Request::create('foo', 'GET', ['token' => 'foobar']);
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_the_custom_query_string()
{
$request = Request::create('foo', 'GET', ['custom_token_key' => 'foobar']);
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
(new QueryString)->setKey('custom_token_key'),
new InputSource,
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_the_query_string_not_the_input_source()
{
$request = Request::create('foo?token=foobar', 'POST', [], [], [], [], json_encode(['token' => 'foobarbaz']));
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_the_custom_query_string_not_the_custom_input_source()
{
$request = Request::create('foo?custom_token_key=foobar', 'POST', [], [], [], [], json_encode(['custom_token_key' => 'foobarbaz']));
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
(new QueryString)->setKey('custom_token_key'),
(new InputSource)->setKey('custom_token_key'),
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_input_source()
{
$request = Request::create('foo', 'POST', [], [], [], [], json_encode(['token' => 'foobar']));
$request->headers->set('Content-Type', 'application/json');
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_the_custom_input_source()
{
$request = Request::create('foo', 'POST', [], [], [], [], json_encode(['custom_token_key' => 'foobar']));
$request->headers->set('Content-Type', 'application/json');
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
(new InputSource)->setKey('custom_token_key'),
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_an_unencrypted_cookie()
{
$request = Request::create('foo', 'POST', [], ['token' => 'foobar']);
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
new Cookies(false),
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_a_crypted_cookie()
{
Crypt::shouldReceive('encrypt')
->with('foobar')
->once()
->andReturn('cryptedFoobar');
$request = Request::create('foo', 'POST', [], ['token' => Crypt::encrypt('foobar')]);
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
new Cookies(true),
]);
Crypt::shouldReceive('decrypt')
->with('cryptedFoobar')
->times(2)
->andReturn('foobar');
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_route()
{
$request = Request::create('foo', 'GET', ['foo' => 'bar']);
$request->setRouteResolver(function () {
return $this->getRouteMock('foobar');
});
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_the_token_from_route_with_a_custom_param()
{
$request = Request::create('foo', 'GET', ['foo' => 'bar']);
$request->setRouteResolver(function () {
return $this->getRouteMock('foobar', 'custom_route_param');
});
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
(new RouteParams)->setKey('custom_route_param'),
]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_ignore_routeless_requests()
{
$request = Request::create('foo', 'GET', ['foo' => 'bar']);
$request->setRouteResolver(function () {
//
});
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
]);
$this->assertNull($parser->parseToken());
$this->assertFalse($parser->hasToken());
}
/** @test */
public function it_should_ignore_lumen_request_arrays()
{
$request = Request::create('foo', 'GET', ['foo' => 'bar']);
$request->setRouteResolver(function () {
return [false, ['uses' => 'someController'], ['token' => 'foobar']];
});
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
]);
$this->assertNull($parser->parseToken());
$this->assertFalse($parser->hasToken());
}
/** @test */
public function it_should_accept_lumen_request_arrays_with_special_class()
{
$request = Request::create('foo', 'GET', ['foo' => 'bar']);
$request->setRouteResolver(function () {
return [false, ['uses' => 'someController'], ['token' => 'foo.bar.baz']];
});
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
new LumenRouteParams,
]);
$this->assertSame($parser->parseToken(), 'foo.bar.baz');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_return_null_if_no_token_in_request()
{
$request = Request::create('foo', 'GET', ['foo' => 'bar']);
$request->setRouteResolver(function () {
return $this->getRouteMock();
});
$parser = new Parser($request);
$parser->setChain([
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
]);
$this->assertNull($parser->parseToken());
$this->assertFalse($parser->hasToken());
}
/** @test */
public function it_should_retrieve_the_chain()
{
$chain = [
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
];
$parser = new Parser(Mockery::mock(Request::class));
$parser->setChain($chain);
$this->assertSame($parser->getChain(), $chain);
}
/** @test */
public function it_should_retrieve_the_chain_with_alias()
{
$chain = [
new AuthHeaders,
new QueryString,
new InputSource,
new RouteParams,
];
/* @var \Illuminate\Http\Request $request */
$request = Mockery::mock(Request::class);
$parser = new Parser($request);
$parser->setChainOrder($chain);
$this->assertSame($parser->getChain(), $chain);
}
/** @test */
public function it_should_set_the_cookie_key()
{
$cookies = (new Cookies)->setKey('test');
$this->assertInstanceOf(Cookies::class, $cookies);
}
/** @test */
public function it_should_add_custom_parser()
{
$request = Request::create('foo', 'GET', ['foo' => 'bar']);
$customParser = Mockery::mock(ParserContract::class);
$customParser->shouldReceive('parse')->with($request)->andReturn('foobar');
$parser = new Parser($request);
$parser->addParser($customParser);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
/** @test */
public function it_should_add_multiple_custom_parser()
{
$request = Request::create('foo', 'GET', ['foo' => 'bar']);
$customParser1 = Mockery::mock(ParserContract::class);
$customParser1->shouldReceive('parse')->with($request)->andReturn(false);
$customParser2 = Mockery::mock(ParserContract::class);
$customParser2->shouldReceive('parse')->with($request)->andReturn('foobar');
$parser = new Parser($request);
$parser->addParser([$customParser1, $customParser2]);
$this->assertSame($parser->parseToken(), 'foobar');
$this->assertTrue($parser->hasToken());
}
protected function getRouteMock($expectedParameterValue = null, $expectedParameterName = 'token')
{
return Mockery::mock(Route::class)
->shouldReceive('parameter')
->with($expectedParameterName)
->andReturn($expectedParameterValue)
->getMock();
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/Fixtures/Foo.php | tests/Fixtures/Foo.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test\Fixtures;
use Tymon\JWTAuth\Claims\Claim;
class Foo extends Claim
{
/**
* {@inheritdoc}
*/
protected $name = 'foo';
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/Middleware/AbstractMiddlewareTest.php | tests/Middleware/AbstractMiddlewareTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test\Middleware;
use Illuminate\Http\Request;
use Mockery;
use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\Test\AbstractTestCase;
abstract class AbstractMiddlewareTest extends AbstractTestCase
{
/**
* @var \Mockery\MockInterface|\Tymon\JWTAuth\JWTAuth
*/
protected $auth;
/**
* @var \Mockery\MockInterface|\Illuminate\Http\Request
*/
protected $request;
public function setUp(): void
{
parent::setUp();
$this->auth = Mockery::mock(JWTAuth::class);
$this->request = Mockery::mock(Request::class);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/Middleware/CheckTest.php | tests/Middleware/CheckTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test\Middleware;
use Mockery;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Http\Middleware\Check;
use Tymon\JWTAuth\Http\Parser\Parser;
use Tymon\JWTAuth\Test\Stubs\UserStub;
class CheckTest extends AbstractMiddlewareTest
{
/**
* @var \Tymon\JWTAuth\Http\Middleware\Check
*/
protected $middleware;
public function setUp(): void
{
parent::setUp();
$this->middleware = new Check($this->auth);
}
/** @test */
public function it_should_authenticate_a_user_if_a_token_is_present()
{
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(true);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->auth->shouldReceive('parseToken->authenticate')->once()->andReturn(new UserStub);
$this->middleware->handle($this->request, function () {
//
});
}
/** @test */
public function it_should_unset_the_exception_if_a_token_is_present()
{
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(true);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->auth->shouldReceive('parseToken->authenticate')->once()->andThrow(new TokenInvalidException);
$this->middleware->handle($this->request, function () {
//
});
}
/** @test */
public function it_should_do_nothing_if_a_token_is_not_present()
{
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(false);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->auth->shouldReceive('parseToken->authenticate')->never();
$this->middleware->handle($this->request, function () {
//
});
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/Middleware/AuthenticateAndRenewTest.php | tests/Middleware/AuthenticateAndRenewTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test\Middleware;
use Illuminate\Http\Response;
use Mockery;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Http\Middleware\AuthenticateAndRenew;
use Tymon\JWTAuth\Http\Parser\Parser;
use Tymon\JWTAuth\Test\Stubs\UserStub;
class AuthenticateAndRenewTest extends AbstractMiddlewareTest
{
/**
* @var \Tymon\JWTAuth\Http\Middleware\Authenticate|\Tymon\JWTAuth\Http\Middleware\AuthenticateAndRenew
*/
protected $middleware;
public function setUp(): void
{
parent::setUp();
$this->middleware = new AuthenticateAndRenew($this->auth);
}
/** @test */
public function it_should_authenticate_a_user_and_return_a_new_token()
{
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(true);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->auth->shouldReceive('parseToken->authenticate')->once()->andReturn(new UserStub);
$this->auth->shouldReceive('refresh')->once()->andReturn('foo.bar.baz');
$response = $this->middleware->handle($this->request, function () {
return new Response;
});
$this->assertSame($response->headers->get('authorization'), 'Bearer foo.bar.baz');
}
/** @test */
public function it_should_throw_an_unauthorized_exception_if_token_not_provided()
{
$this->expectException(UnauthorizedHttpException::class);
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(false);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->middleware->handle($this->request, function () {
//
});
}
/** @test */
public function it_should_throw_an_unauthorized_exception_if_token_invalid()
{
$this->expectException(UnauthorizedHttpException::class);
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(true);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->auth->shouldReceive('parseToken->authenticate')->once()->andThrow(new TokenInvalidException);
$this->middleware->handle($this->request, function () {
//
});
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/Middleware/AuthenticateTest.php | tests/Middleware/AuthenticateTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test\Middleware;
use Mockery;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Http\Middleware\Authenticate;
use Tymon\JWTAuth\Http\Parser\Parser;
use Tymon\JWTAuth\Test\Stubs\UserStub;
class AuthenticateTest extends AbstractMiddlewareTest
{
/**
* @var \Tymon\JWTAuth\Http\Middleware\Authenticate
*/
protected $middleware;
public function setUp(): void
{
parent::setUp();
$this->middleware = new Authenticate($this->auth);
}
/** @test */
public function it_should_authenticate_a_user()
{
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(true);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->auth->shouldReceive('parseToken->authenticate')->once()->andReturn(new UserStub);
$this->middleware->handle($this->request, function () {
//
});
}
/** @test */
public function it_should_throw_an_unauthorized_exception_if_token_not_provided()
{
$this->expectException(UnauthorizedHttpException::class);
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(false);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->middleware->handle($this->request, function () {
//
});
}
/** @test */
public function it_should_throw_an_unauthorized_exception_if_token_invalid()
{
$this->expectException(UnauthorizedHttpException::class);
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(true);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->auth->shouldReceive('parseToken->authenticate')->once()->andThrow(new TokenInvalidException);
$this->middleware->handle($this->request, function () {
//
});
}
/** @test */
public function it_should_throw_an_unauthorized_exception_if_user_not_found()
{
$this->expectException(UnauthorizedHttpException::class);
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(true);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->auth->shouldReceive('parseToken->authenticate')->once()->andReturn(false);
$this->middleware->handle($this->request, function () {
//
});
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/Middleware/RefreshTokenTest.php | tests/Middleware/RefreshTokenTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test\Middleware;
use Illuminate\Http\Response;
use Mockery;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Http\Middleware\RefreshToken;
use Tymon\JWTAuth\Http\Parser\Parser;
class RefreshTokenTest extends AbstractMiddlewareTest
{
/**
* @var \Tymon\JWTAuth\Http\Middleware\RefreshToken
*/
protected $middleware;
public function setUp(): void
{
parent::setUp();
$this->middleware = new RefreshToken($this->auth);
}
/** @test */
public function it_should_refresh_a_token()
{
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(true);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->auth->shouldReceive('parseToken->refresh')->once()->andReturn('foo.bar.baz');
$response = $this->middleware->handle($this->request, function () {
return new Response;
});
$this->assertSame($response->headers->get('authorization'), 'Bearer foo.bar.baz');
}
/** @test */
public function it_should_throw_an_unauthorized_exception_if_token_not_provided()
{
$this->expectException(UnauthorizedHttpException::class);
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(false);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->middleware->handle($this->request, function () {
//
});
}
/** @test */
public function it_should_throw_an_unauthorized_exception_if_token_invalid()
{
$this->expectException(UnauthorizedHttpException::class);
$parser = Mockery::mock(Parser::class);
$parser->shouldReceive('hasToken')->once()->andReturn(true);
$this->auth->shouldReceive('parser')->andReturn($parser);
$this->auth->parser()->shouldReceive('setRequest')->once()->with($this->request)->andReturn($this->auth->parser());
$this->auth->shouldReceive('parseToken->refresh')->once()->andThrow(new TokenInvalidException);
$this->middleware->handle($this->request, function () {
//
});
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/Validators/TokenValidatorTest.php | tests/Validators/TokenValidatorTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test\Validators;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Test\AbstractTestCase;
use Tymon\JWTAuth\Validators\TokenValidator;
class TokenValidatorTest extends AbstractTestCase
{
/**
* @var \Tymon\JWTAuth\Validators\TokenValidator
*/
protected $validator;
public function setUp(): void
{
parent::setUp();
$this->validator = new TokenValidator;
}
/** @test */
public function it_should_return_true_when_providing_a_well_formed_token()
{
$this->assertTrue($this->validator->isValid('one.two.three'));
}
/**
* @test
*
* @dataProvider \Tymon\JWTAuth\Test\Validators\TokenValidatorTest::dataProviderMalformedTokens
*
* @param string $token
*/
public function it_should_return_false_when_providing_a_malformed_token($token)
{
$this->assertFalse($this->validator->isValid($token));
}
/**
* @test
*
* @dataProvider \Tymon\JWTAuth\Test\Validators\TokenValidatorTest::dataProviderMalformedTokens
*/
public function it_should_throw_an_exception_when_providing_a_malformed_token($token)
{
$this->expectException(TokenInvalidException::class);
$this->expectExceptionMessage('Malformed token');
$this->validator->check($token);
}
/**
* @test
*
* @dataProvider \Tymon\JWTAuth\Test\Validators\TokenValidatorTest::dataProviderTokensWithWrongSegmentsNumber
*/
public function it_should_return_false_when_providing_a_token_with_wrong_segments_number($token)
{
$this->assertFalse($this->validator->isValid($token));
}
/**
* @test
*
* @dataProvider \Tymon\JWTAuth\Test\Validators\TokenValidatorTest::dataProviderTokensWithWrongSegmentsNumber
*/
public function it_should_throw_an_exception_when_providing_a_malformed_token_with_wrong_segments_number($token)
{
$this->expectException(TokenInvalidException::class);
$this->expectExceptionMessage('Wrong number of segments');
$this->validator->check($token);
}
public function dataProviderMalformedTokens()
{
return [
['one.two.'],
['.two.'],
['.two.three'],
['one..three'],
['..'],
[' . . '],
[' one . two . three '],
];
}
public function dataProviderTokensWithWrongSegmentsNumber()
{
return [
['one.two'],
['one.two.three.four'],
['one.two.three.four.five'],
];
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
tymondesigns/jwt-auth | https://github.com/tymondesigns/jwt-auth/blob/152f571c1a7f76528b03c9843baad3ebd2a2185f/tests/Validators/PayloadValidatorTest.php | tests/Validators/PayloadValidatorTest.php | <?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Test\Validators;
use Tymon\JWTAuth\Claims\Collection;
use Tymon\JWTAuth\Claims\Expiration;
use Tymon\JWTAuth\Claims\IssuedAt;
use Tymon\JWTAuth\Claims\Issuer;
use Tymon\JWTAuth\Claims\JwtId;
use Tymon\JWTAuth\Claims\NotBefore;
use Tymon\JWTAuth\Claims\Subject;
use Tymon\JWTAuth\Exceptions\InvalidClaimException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Test\AbstractTestCase;
use Tymon\JWTAuth\Validators\PayloadValidator;
class PayloadValidatorTest extends AbstractTestCase
{
/**
* @var \Tymon\JWTAuth\Validators\PayloadValidator
*/
protected $validator;
public function setUp(): void
{
parent::setUp();
$this->validator = new PayloadValidator;
}
/** @test */
public function it_should_return_true_when_providing_a_valid_payload()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 3600),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->assertTrue($this->validator->isValid($collection));
}
/** @test */
public function it_should_throw_an_exception_when_providing_an_expired_payload()
{
$this->expectException(TokenExpiredException::class);
$this->expectExceptionMessage('Token has expired');
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp - 1440),
new NotBefore($this->testNowTimestamp - 3660),
new IssuedAt($this->testNowTimestamp - 3660),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->check($collection);
}
/** @test */
public function it_should_throw_an_exception_when_providing_an_invalid_nbf_claim()
{
$this->expectException(TokenInvalidException::class);
$this->expectExceptionMessage('Not Before (nbf) timestamp cannot be in the future');
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 1440),
new NotBefore($this->testNowTimestamp + 3660),
new IssuedAt($this->testNowTimestamp - 3660),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->check($collection);
}
/** @test */
public function it_should_throw_an_exception_when_providing_an_invalid_iat_claim()
{
$this->expectException(InvalidClaimException::class);
$this->expectExceptionMessage('Invalid value provided for claim [iat]');
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp + 1440),
new NotBefore($this->testNowTimestamp - 3660),
new IssuedAt($this->testNowTimestamp + 3660),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->check($collection);
}
/** @test */
public function it_should_throw_an_exception_when_providing_an_invalid_payload()
{
$this->expectException(TokenInvalidException::class);
$this->expectExceptionMessage('JWT payload does not contain the required claims');
$claims = [
new Subject(1),
new Issuer('http://example.com'),
];
$collection = Collection::make($claims);
$this->validator->check($collection);
}
/** @test */
public function it_should_throw_an_exception_when_providing_an_invalid_expiry()
{
$this->expectException(InvalidClaimException::class);
$this->expectExceptionMessage('Invalid value provided for claim [exp]');
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration('foo'),
new NotBefore($this->testNowTimestamp - 3660),
new IssuedAt($this->testNowTimestamp + 3660),
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->check($collection);
}
/** @test */
public function it_should_set_the_required_claims()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
];
$collection = Collection::make($claims);
$this->assertTrue($this->validator->setRequiredClaims(['iss', 'sub'])->isValid($collection));
}
/** @test */
public function it_should_check_the_token_in_the_refresh_context()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp - 1000),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp - 2600), // this is LESS than the refresh ttl at 1 hour
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->assertTrue(
$this->validator->setRefreshFlow()->setRefreshTTL(60)->isValid($collection)
);
}
/** @test */
public function it_should_return_true_if_the_refresh_ttl_is_null()
{
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp - 1000),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp - 2600), // this is LESS than the refresh ttl at 1 hour
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->assertTrue(
$this->validator->setRefreshFlow()->setRefreshTTL(null)->isValid($collection)
);
}
/** @test */
public function it_should_throw_an_exception_if_the_token_cannot_be_refreshed()
{
$this->expectException(TokenExpiredException::class);
$this->expectExceptionMessage('Token has expired and can no longer be refreshed');
$claims = [
new Subject(1),
new Issuer('http://example.com'),
new Expiration($this->testNowTimestamp),
new NotBefore($this->testNowTimestamp),
new IssuedAt($this->testNowTimestamp - 5000), // this is MORE than the refresh ttl at 1 hour, so is invalid
new JwtId('foo'),
];
$collection = Collection::make($claims);
$this->validator->setRefreshFlow()->setRefreshTTL(60)->check($collection);
}
}
| php | MIT | 152f571c1a7f76528b03c9843baad3ebd2a2185f | 2026-01-04T15:04:24.804405Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.