Unverified Commit 431752cf authored by Viral Solani's avatar Viral Solani Committed by GitHub

Merge pull request #379 from viralsolani/develop

Added version change of generator
parents 1227624c 8e8f320b
......@@ -16,6 +16,7 @@ Thumbs.db
_ide_helper.php
composer.phar
error.log
access.log
Todo.rtf
.vagrant
/.vagrant
......
......@@ -107,8 +107,9 @@ You can now access the server at http://localhost:8000
npm run development
php artisan storage:link
php artisan key:generate
php artisan jwt:secret
php artisan vendor:publish --tag=lfm_public
php artisan migrate
php artisan passport:install
## Please note
......
This diff is collapsed.
......@@ -90,11 +90,6 @@ class Handler extends ExceptionHandler
switch (get_class($exception->getPrevious())) {
case \App\Exceptions\Handler::class:
return $this->setStatusCode($exception->getStatusCode())->respondWithError('Token has not been provided.');
case \Tymon\JWTAuth\Exceptions\TokenExpiredException::class:
return $this->setStatusCode($exception->getStatusCode())->respondWithError('Token has expired.');
case \Tymon\JWTAuth\Exceptions\TokenInvalidException::class:
case \Tymon\JWTAuth\Exceptions\TokenBlacklistedException::class:
return $this->setStatusCode($exception->getStatusCode())->respondWithError('Token is invalid.');
}
}
}
......
......@@ -2,10 +2,8 @@
namespace App\Http\Controllers\Api\V1;
use App\Models\Access\User\User;
use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\Auth;
use Validator;
class AuthController extends APIController
......@@ -31,10 +29,19 @@ class AuthController extends APIController
$credentials = $request->only(['email', 'password']);
try {
if (!$token = JWTAuth::attempt($credentials)) {
if (!Auth::attempt($credentials)) {
return $this->throwValidation(trans('api.messages.login.failed'));
}
} catch (JWTException $e) {
$user = $request->user();
$passportToken = $user->createToken('API Access Token');
// Save generated token
$passportToken->token->save();
$token = $passportToken->accessToken;
} catch (\Exception $e) {
return $this->respondInternalError($e->getMessage());
}
......@@ -45,49 +52,30 @@ class AuthController extends APIController
}
/**
* Log the user out (Invalidate the token).
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
public function me()
{
try {
$token = JWTAuth::getToken();
if ($token) {
JWTAuth::invalidate($token);
}
} catch (JWTException $e) {
return $this->respondInternalError($e->getMessage());
}
return $this->respond([
'message' => trans('api.messages.logout.success'),
]);
return response()->json($this->guard()->user());
}
/**
* Refresh a token.
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
public function logout(Request $request)
{
$token = JWTAuth::getToken();
if (!$token) {
$this->respondUnauthorized(trans('api.messages.refresh.token.not_provided'));
}
try {
$refreshedToken = JWTAuth::refresh($token);
} catch (JWTException $e) {
$request->user()->token()->revoke();
} catch (\Exception $e) {
return $this->respondInternalError($e->getMessage());
}
return $this->respond([
'status' => trans('api.messages.refresh.status'),
'token' => $refreshedToken,
'message' => trans('api.messages.logout.success'),
]);
}
}
......@@ -2,11 +2,9 @@
namespace App\Http\Controllers\Api\V1;
use App\Models\User\User;
use App\Repositories\Frontend\Access\User\UserRepository;
use Config;
use Illuminate\Http\Request;
use JWTAuth;
use Validator;
class RegisterController extends APIController
......@@ -53,7 +51,12 @@ class RegisterController extends APIController
]);
}
$token = JWTAuth::fromUser($user);
$passportToken = $user->createToken('API Access Token');
// Save generated token
$passportToken->token->save();
$token = $passportToken->accessToken;
return $this->respondCreated([
'message' => trans('api.messages.registeration.success'),
......
......@@ -3,8 +3,6 @@
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Tymon\JWTAuth\Middleware\GetUserFromToken;
use Tymon\JWTAuth\Middleware\RefreshToken;
/**
* Class Kernel.
......@@ -76,7 +74,5 @@ class Kernel extends HttpKernel
*/
'access.routeNeedsRole' => \App\Http\Middleware\RouteNeedsRole::class,
'access.routeNeedsPermission' => \App\Http\Middleware\RouteNeedsPermission::class,
'jwt.auth' => GetUserFromToken::class,
'jwt.refresh' => RefreshToken::class,
];
}
......@@ -27,7 +27,6 @@ class ManageRoleRequest extends Request
public function rules()
{
return [
//
];
}
}
......@@ -10,12 +10,12 @@ use App\Models\Access\User\Traits\UserSendPasswordReset;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Laravel\Passport\HasApiTokens;
/**
* Class User.
*/
class User extends Authenticatable implements JWTSubject
class User extends Authenticatable
{
use UserScope,
UserAccess,
......@@ -23,7 +23,8 @@ class User extends Authenticatable implements JWTSubject
SoftDeletes,
UserAttribute,
UserRelationship,
UserSendPasswordReset;
UserSendPasswordReset,
HasApiTokens;
/**
* The database table used by the model.
*
......@@ -78,6 +79,18 @@ class User extends Authenticatable implements JWTSubject
return $this->getKey();
}
/**
* Set password attribute.
*
* @param [string] $password
*/
public function setPasswordAttribute($password)
{
if (!empty($password)) {
$this->attributes['password'] = bcrypt($password);
}
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
......
......@@ -58,20 +58,6 @@ class AppServiceProvider extends ServiceProvider
* Sets third party service providers that are only needed on local/testing environments
*/
if ($this->app->environment() != 'production') {
/**
* Loader for registering facades.
*/
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
/*
* Load third party local providers
*/
$this->app->register(\Barryvdh\Debugbar\ServiceProvider::class);
/*
* Load third party local aliases
*/
$loader->alias('Debugbar', \Barryvdh\Debugbar\Facade::class);
}
}
}
......@@ -3,6 +3,7 @@
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;
/**
* Class AuthServiceProvider.
......@@ -27,6 +28,6 @@ class AuthServiceProvider extends ServiceProvider
{
$this->registerPolicies();
//
Passport::routes();
}
}
......@@ -20,14 +20,14 @@ class BladeServiceProvider extends ServiceProvider
/**
* Register any misc. blade extensions.
*/
public function register()
public function boot()
{
/*
* The block of code inside this directive indicates
* the chosen language requests RTL support.
*/
Blade::directive('langRTL', function () {
return "<?php if (session()->has('lang-rtl')): ?>";
Blade::if('langrtl', function ($session_identifier = 'lang-rtl') {
return session()->has($session_identifier);
});
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
......@@ -147,7 +146,6 @@ return [
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
......@@ -200,8 +198,8 @@ return [
App\Providers\TelescopeServiceProvider::class,
App\Providers\HistoryServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
Bvipul\Generator\Provider\CrudGeneratorServiceProvider::class,
Laravel\Passport\PassportServiceProvider::class,
],
/*
......@@ -216,7 +214,6 @@ return [
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
......@@ -261,9 +258,6 @@ return [
'Gravatar' => Creativeorange\Gravatar\Facades\Gravatar::class,
'Html' => Collective\Html\HtmlFacade::class,
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
//'Datatables' => Yajra\DataTables\Facades\DataTables::class
],
];
......@@ -44,7 +44,7 @@ return [
],
'api' => [
'driver' => 'jwt',
'driver' => 'passport',
'provider' => 'users',
],
],
......
<?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.
*/
return [
/*
|--------------------------------------------------------------------------
| JWT Authentication Secret
|--------------------------------------------------------------------------
|
| Don't forget to set this in your .env file, as it will be used to sign
| your tokens. A helper command is provided for this:
| `php artisan jwt:secret`
|
| Note: This will be used for Symmetric algorithms only (HMAC),
| since RSA and ECDSA use a private/public key combo (See below).
|
*/
'secret' => env('JWT_SECRET'),
/*
|--------------------------------------------------------------------------
| JWT Authentication Keys
|--------------------------------------------------------------------------
|
| The algorithm you are using, will determine whether your tokens are
| signed with a random string (defined in `JWT_SECRET`) or using the
| following public & private keys.
|
| Symmetric Algorithms:
| HS256, HS384 & HS512 will use `JWT_SECRET`.
|
| Asymmetric Algorithms:
| RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
|
*/
'keys' => [
/*
|--------------------------------------------------------------------------
| Public Key
|--------------------------------------------------------------------------
|
| A path or resource to your public key.
|
| E.g. 'file://path/to/public/key'
|
*/
'public' => env('JWT_PUBLIC_KEY'),
/*
|--------------------------------------------------------------------------
| Private Key
|--------------------------------------------------------------------------
|
| A path or resource to your private key.
|
| E.g. 'file://path/to/private/key'
|
*/
'private' => env('JWT_PRIVATE_KEY'),
/*
|--------------------------------------------------------------------------
| Passphrase
|--------------------------------------------------------------------------
|
| The passphrase for your private key. Can be null if none set.
|
*/
'passphrase' => env('JWT_PASSPHRASE'),
],
/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour.
|
| You can also set this to null, to yield a never expiring token.
| Some people may want this behaviour for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
|
*/
'ttl' => env('JWT_TTL', 60),
/*
|--------------------------------------------------------------------------
| Refresh time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token can be refreshed
| within. I.E. The user can refresh their token within a 2 week window of
| the original token being created until they must re-authenticate.
| Defaults to 2 weeks.
|
| You can also set this to null, to yield an infinite refresh time.
| Some may want this instead of never expiring tokens for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
|
*/
'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),
/*
|--------------------------------------------------------------------------
| JWT hashing algorithm
|--------------------------------------------------------------------------
|
| Specify the hashing algorithm that will be used to sign the token.
|
| See here: https://github.com/namshi/jose/tree/master/src/Namshi/JOSE/Signer/OpenSSL
| for possible values.
|
*/
'algo' => env('JWT_ALGO', 'HS256'),
/*
|--------------------------------------------------------------------------
| Required Claims
|--------------------------------------------------------------------------
|
| Specify the required claims that must exist in any token.
| A TokenInvalidException will be thrown if any of these claims are not
| present in the payload.
|
*/
'required_claims' => [
'iss',
'iat',
'exp',
'nbf',
'sub',
'jti',
],
/*
|--------------------------------------------------------------------------
| Persistent Claims
|--------------------------------------------------------------------------
|
| Specify the claim keys to be persisted when refreshing a token.
| `sub` and `iat` will automatically be persisted, in
| addition to the these claims.
|
| Note: If a claim does not exist then it will be ignored.
|
*/
'persistent_claims' => [
// 'foo',
// 'bar',
],
/*
|--------------------------------------------------------------------------
| Blacklist Enabled
|--------------------------------------------------------------------------
|
| In order to invalidate tokens, you must have the blacklist enabled.
| If you do not want or need this functionality, then set this to false.
|
*/
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),
/*
| -------------------------------------------------------------------------
| Blacklist Grace Period
| -------------------------------------------------------------------------
|
| When multiple concurrent requests are made with the same JWT,
| it is possible that some of them fail, due to token regeneration
| on every request.
|
| Set grace period in seconds to prevent parallel request failure.
|
*/
'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),
/*
|--------------------------------------------------------------------------
| Cookies encryption
|--------------------------------------------------------------------------
|
| By default Laravel encrypt cookies for security reason.
| If you decide to not decrypt cookies, you will have to configure Laravel
| to not encrypt your cookie token by adding its name into the $except
| array available in the middleware "EncryptCookies" provided by Laravel.
| see https://laravel.com/docs/master/responses#cookies-and-encryption
| for details.
|
| Set it to false if you don't want to decrypt cookies.
|
*/
'decrypt_cookies' => true,
/*
|--------------------------------------------------------------------------
| Providers
|--------------------------------------------------------------------------
|
| Specify the various providers used throughout the package.
|
*/
'providers' => [
/*
|--------------------------------------------------------------------------
| JWT Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to create and decode the tokens.
|
*/
'jwt' => Tymon\JWTAuth\Providers\JWT\Namshi::class,
/*
|--------------------------------------------------------------------------
| Authentication Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to authenticate users.
|
*/
'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,
/*
|--------------------------------------------------------------------------
| Storage Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to store tokens in the blacklist.
|
*/
'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
],
];
......@@ -97,7 +97,7 @@ RUN chown -R 777 /var/www/html/
RUN composer install
RUN php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
#RUN php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
......
This diff is collapsed.
......@@ -68,6 +68,12 @@
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var dataTable = $('#permissions-table').dataTable({
processing: true,
serverSide: true,
......
......@@ -70,12 +70,19 @@
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var dataTable = $('#roles-table').dataTable({
processing: true,
serverSide: true,
ajax: {
url: '{{ route("admin.access.role.get") }}',
type: 'post'
type: 'post',
},
columns: [
{data: 'name', name: '{{config('access.roles_table')}}.name'},
......
......@@ -65,6 +65,11 @@
{{ Html::script(mix('js/dataTable.js')) }}
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(function() {
var dataTable = $('#blogcategories-table').dataTable({
processing: true,
......
......@@ -68,6 +68,12 @@
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var dataTable = $('#blogs-table').dataTable({
processing: true,
serverSide: true,
......
......@@ -66,6 +66,12 @@
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var dataTable = $('#blogtags-table').dataTable({
processing: true,
serverSide: true,
......
......@@ -70,6 +70,12 @@
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var dataTable = $('#faqs-table').dataTable({
processing: true,
serverSide: true,
......
......@@ -19,11 +19,12 @@
<!-- Check if the language is set to RTL, so apply the RTL layouts -->
<!-- Otherwise apply the normal LTR layouts -->
@langRTL
@langrtl
{{ Html::style(getRtlCss(mix('css/backend.css'))) }}
@else
{{ Html::style(mix('css/backend.css')) }}
@endif
@endlangrtl
{{ Html::style(mix('css/backend-custom.css')) }}
@yield('after-styles')
......
......@@ -67,6 +67,13 @@
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var dataTable = $('#menus-table').dataTable({
processing: true,
serverSide: true,
......
......@@ -66,6 +66,12 @@
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var dataTable = $('#pages-table').dataTable({
processing: true,
serverSide: true,
......
......@@ -20,11 +20,12 @@
<!-- Check if the language is set to RTL, so apply the RTL layouts -->
<!-- Otherwise apply the normal LTR layouts -->
@langRTL
@langrtl
{{ Html::style(getRtlCss(mix('css/frontend.css'))) }}
@else
{{ Html::style(mix('css/frontend.css')) }}
@endif
@endlangrtl
{!! Html::style('js/select2/select2.min.css') !!}
@yield('after-styles')
......
......@@ -13,11 +13,11 @@
<!-- Check if the language is set to RTL, so apply the RTL layouts -->
<!-- Otherwise apply the normal LTR layouts -->
@langRTL
@langrtl
{{ Html::style(getRtlCss(mix('css/backend.css'))) }}
@else
{{ Html::style(mix('css/backend.css')) }}
@endif
@endlangrtl
{!! Html::style('css/custom-style.css') !!}
@yield('after-styles-end')
......
......@@ -18,7 +18,7 @@ Route::group(['namespace' => 'Api\V1', 'prefix' => 'v1', 'as' => 'v1.'], functio
Route::post('login', 'AuthController@login');
});
Route::group(['middleware' => ['jwt.auth']], function () {
Route::group(['middleware' => ['auth:api']], function () {
Route::group(['prefix' => 'auth'], function () {
Route::post('logout', 'AuthController@logout');
Route::post('refresh', 'AuthController@refresh');
......
......@@ -50,7 +50,7 @@ abstract class BrowserKitTestCase extends BaseTestCase
*/
protected $userRole;
public function setUp()
public function setUp(): void
{
parent::setUp();
......@@ -76,7 +76,7 @@ abstract class BrowserKitTestCase extends BaseTestCase
$this->userRole = Role::find(3);
}
public function tearDown()
public function tearDown(): void
{
$this->beforeApplicationDestroyed(function () {
DB::disconnect();
......
<?php
namespace Tests\Feature\Api\V1;
use Illuminate\Support\Facades\Auth;
use Tests\TestCase;
class LoginTest extends TestCase
{
/** @test */
public function users_can_login_through_api()
{
$res = $this->json('POST', '/api/v1/auth/login', [
'email' => $this->user->email,
'password' => '1234',
])
->assertStatus(200)
->assertJsonStructure([
'message',
'token',
]);
}
}
<?php
namespace Tests\Feature\Api\V1;
use App\Models\Access\User\User;
use App\Models\Page\Page;
use JWTAuth;
use Tests\TestCase;
class PageTest extends TestCase
{
public $token = '';
public $headers = '';
public $user = '';
public function setUp()
{
parent::setUp();
$this->user = User::find(1);
$this->token = JWTAuth::fromUser($this->user);
$this->headers = ['Authorization' => 'Bearer '.$this->token];
}
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$this->assertTrue(true);
}
/**
* A basic test to get response form pages api.
*
* @return void
*/
/** @test */
public function Get_records_from_pages()
{
$payload = [];
$response = $this->json('GET', '/api/v1/pages', $payload, $this->headers);
$response
->assertStatus(200)
->assertJsonStructure([
'data'=> [
[
'id',
'title',
'status_label',
'status',
'created_at',
'created_by',
],
],
'links',
'meta',
]);
}
/**
* A basic test to get response form pages api.
*
* @return void
*/
/** @test */
public function get_one_created_page_from_db()
{
$page = create(Page::class);
$payload = [];
$response = $this->json('GET', '/api/v1/pages/'.$page->id, $payload, $this->headers);
$response
->assertStatus(200)
->assertJson([
'data'=> [
'id' => $page->id,
'title' => $page->title,
'status_label' => $page->status_label,
'status' => ($page->isActive()) ? 'Active' : 'InActive',
'created_by' => $page->created_by,
],
]);
}
/**
* Author: Indra Shastri
* Date:03-03-2018
* A basic test to update a page from api.
*
*
* @return void
*/
/** @test */
public function update_a_page_in_db_and_get_response()
{
$page = make(Page::class);
$payload = [
'title' => $page->title,
'description' => $page->description,
'cannonical_link' => $page->cannonical_link,
'seo_title' => 'some tittle',
'seo_keyword' => 'some keywords',
'seo_description' => '<p>&nbsp;</p>↵<h1>SEO Description</h1>↵<p>some seco desctription</p>↵<p>askdsaj;ldsjfd</p>',
'status' => '1',
];
$response = '';
$response = $this->json('PUT', '/api/v1/pages/1', $payload, $this->headers);
$response->assertStatus(200);
$response->assertJson([
'data'=> [
'title' => $page->title,
'status_label' => $page->status_label,
'status' => ($page->isActive()) ? 'Active' : 'InActive',
'created_by' => ''.$this->user->id,
],
]);
}
/**
* Author: Indra Shastri
* Date:03-03-2018
* A basic test to create a page from api.
*
* @return void
*/
/** @test */
public function create_a_new_page_in_db_and_get_response()
{
$page = make(Page::class);
$payload = [
'title' => $page->title,
'description' => $page->description,
'cannonical_link' => $page->cannonical_link,
'seo_title' => 'some tittle',
'seo_keyword' => 'some keywords',
'seo_description' => '<p>&nbsp;</p>↵<h1>SEO Description</h1>↵<p>some seco desctription</p>↵<p>askdsaj;ldsjfd</p>',
'status' => '1',
];
$response = '';
$response = $this->json('POST', '/api/v1/pages', $payload, $this->headers);
$response->assertStatus(201);
$response->assertJson([
'data' => [
'title' => $page->title,
'status_label' => $page->status_label,
'status' => ($page->isActive()) ? 'Active' : 'InActive',
'created_by' => $this->user->first_name,
'created_at' => (\Carbon\Carbon::now())->toDateString(),
],
]);
}
/**
* Author: Indra Shastri
* Date:03-03-2018
* A basic test to create a page from api.
*
* @return void
*/
/** @test */
public function delete_page_in_db_and_get_response()
{
$page = create(Page::class);
$payload = [];
$response = $this->json('DELETE', '/api/v1/pages/'.$page->id, $payload, $this->headers);
$response->assertStatus(200)
->assertJson([
'message'=> 'The Page was successfully deleted.',
]);
}
}
<?php
namespace Tests\Feature\Auth;
use App\Events\Frontend\Auth\UserLoggedIn;
use App\Models\Access\User\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Tests\BrowserKitTestCase;
class LoginTest extends BrowserKitTestCase
{
/** @test */
public function login_page_loads_properly()
{
$this->visit('/login')
->see('Email')
->see('Password')
->see('Login')
->dontSee('You are logged in!');
}
/** @test */
public function login_fails_when_a_required_field_is_not_filled_in()
{
$this->visit('/login')
->type('', 'email')
->type('', 'password')
->press('Login')
->seePageIs('/login')
->see('The email field is required.')
->see('The password field is required.');
}
/** @test */
public function login_fails_when_password_is_incorrect()
{
$this->visit('/login')
->type('admin@admin.com', 'email')
->type('invalidpass', 'password')
->press('Login')
->seePageIs('/login')
->see('These credentials do not match our records.');
}
/** @test */
public function login_failure_with_wrong_inputs()
{
$this->visit('/login')
->type('wrongusername@wrongpassword.com', 'email')
->type('wrongpassword', 'password')
->press('Login')
->seePageIs('/login')
->see('These credentials do not match our records.');
}
/** @test */
public function unconfirmed_users_can_not_logIn()
{
Auth::logout();
config(['access.users.requires_approval' => false]);
// Create default user to test with
$unconfirmed = factory(User::class)->states('unconfirmed')->create();
$unconfirmed->attachRole(3); //User
$this->visit('/login')
->type($unconfirmed->email, 'email')
->type('secret', 'password')
->press('Login')
->seePageIs('/login')
->see('Your account is not confirmed.');
}
/** @test **/
public function inactive_users_can_not_login()
{
Auth::logout();
// Create default user to test with
$inactive = factory(User::class)->states('confirmed', 'inactive')->create();
$inactive->attachRole(3); //User
$this->visit('/login')
->type($inactive->email, 'email')
->type('secret', 'password')
->press('Login')
->seePageIs('/login')
->see('Your account has been deactivated.');
}
/** @test */
public function users_can_login()
{
// Make sure our events are fired
Event::fake();
Auth::logout();
//User Test
$this->visit('/login')
->type($this->user->email, 'email')
->type('1234', 'password')
->press('Login')
->see($this->user->name)
->seePageIs('/dashboard');
$this->assertLoggedIn();
Auth::logout();
//Admin Test
$this->visit('/login')
->type($this->admin->email, 'email')
->type('1234', 'password')
->press('Login')
->seePageIs('/admin/dashboard')
->see($this->admin->first_name)
->see('Access Management');
$this->assertLoggedIn();
Event::assertDispatched(UserLoggedIn::class);
}
}
<?php
namespace Tests\Feature\Auth;
use App\Events\Frontend\Auth\UserRegistered;
use App\Models\Access\User\User;
use App\Notifications\Frontend\Auth\UserNeedsConfirmation;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Notification;
use Tests\BrowserKitTestCase;
class RegistrationTest extends BrowserKitTestCase
{
/** @test */
public function registration_page_loads_properly()
{
$this->visit('/register')
->see('first_name')
->see('last_name')
->see('email')
->see('password')
->see('is_term_accept')
->see('Register');
}
/** @test */
public function registration_fails_when_a_required_field_is_not_filled_in()
{
$this->visit('/register')
->type('', 'first_name')
->type('', 'last_name')
->type('', 'email')
->type('', 'password')
->press('Register')
->seePageIs('/register')
->see('The first name field is required.')
->see('The last name field is required.')
->see('The email field is required.')
->see('The password field is required.')
->see('The is term accept field is required.');
}
/**
* Test the registration form
* Test it works with confirming email on or off, and that the confirm email notification is sent
* Note: Captcha is disabled by default in phpunit.xml.
*/
/** @test */
public function user_can_register()
{
// Make sure our events are fired
Event::fake();
config(['access.users.confirm_email' => false]);
config(['access.users.requires_approval' => false]);
$this->visit('/register')
->type('John', 'first_name')
->type('Doe', 'last_name')
->type('john.doe@example.com', 'email')
->type('Viral@1234', 'password')
->type('Viral@1234', 'password_confirmation')
->check('is_term_accept')
->press('Register')
->seePageIs('/')
->seeInDatabase(config('access.users_table'),
[
'email' => 'john.doe@example.com',
'first_name' => 'John',
'last_name' => 'Doe',
'confirmed' => 1,
]);
Event::assertDispatched(UserRegistered::class);
}
/**
* Test the registration form when account are set to be pending an approval
* ensure they are registered but not confirmed.
*/
/** @test */
public function registration_for_pending_approval()
{
Event::fake();
Notification::fake();
// Set registration to pending approval
config(['access.users.confirm_email' => false]);
config(['access.users.requires_approval' => true]);
$this->visit('/register')
->type('first name', 'first_name')
->type('last name', 'last_name')
->type('test@example.com', 'email')
->type('Viral@1234', 'password')
->type('Viral@1234', 'password_confirmation')
->check('is_term_accept')
->press('Register')
->see('Your account was successfully created and is pending approval. An e-mail will be sent when your account is approved.')
->see('Login')
->seePageIs('/')
->seeInDatabase(config('access.users_table'),
[
'email' => 'test@example.com',
'first_name' => 'first name',
'last_name' => 'last name',
'confirmed' => 0,
]);
// Get the user that was inserted into the database
$user = User::where('email', 'test@example.com')->first();
Notification::assertNotSentTo([$user], UserNeedsConfirmation::class);
Event::assertDispatched(UserRegistered::class);
}
}
<?php
namespace Tests\Feature\Auth;
use App\Notifications\Frontend\Auth\UserNeedsPasswordReset;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Notification;
use Tests\BrowserKitTestCase;
class ResetPasswordTest extends BrowserKitTestCase
{
/** @test */
public function forgot_password_page_loads_properly()
{
$this->visit('/password/reset')
->see('Email')
->see('Reset Password');
}
/** @test **/
public function forgot_password_fails_when_a_required_field_is_not_filled_in()
{
$this->visit('/password/reset')
->type('', 'email')
->press('Send Password Reset Link')
->seePageIs('/password/reset')
->see('The email field is required.');
}
/** @test **/
public function users_can_request_a_password_reset_link()
{
Notification::fake();
$this->visit('password/reset')
->type($this->user->email, 'email')
->press('Send Password Reset Link')
->seePageIs('password/reset')
->see('We have e-mailed your password reset link!')
->seeInDatabase('password_resets', ['email' => $this->user->email]);
Notification::assertSentTo(
[$this->user],
UserNeedsPasswordReset::class
);
}
/** @test **/
public function reset_password_fails_when_a_required_field_is_not_filled_in()
{
$token = $this->app->make('auth.password.broker')->createToken($this->user);
$this->visit('password/reset/'.$token)
->see($this->user->email)
->type('', 'password')
->type('', 'password_confirmation')
->press('Reset Password')
->see('The password field is required.');
}
/** @test **/
public function users_can_reset_password()
{
$token = $this->app->make('auth.password.broker')->createToken($this->user);
$this->visit('password/reset/'.$token)
->see($this->user->email)
->type('12345678', 'password')
->type('12345678', 'password_confirmation')
->press('Reset Password')
->see($this->user->first_name);
}
}
<?php
namespace Tests\Feature\Backend;
use App\Events\Backend\Access\User\UserPasswordChanged;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
class ChangePasswordTest extends TestCase
{
/** @test */
public function a_user_require_old_password_to_change_password()
{
$data = [];
$data['old_password'] = '12345';
$data['password'] = 'Viral@1234';
$data['password_confirmation'] = 'Viral@1234';
$this->withExceptionHandling()
->actingAs($this->admin)
->patch(route('admin.access.user.change-password', $this->admin), $data)
->assertSessionHas(['flash_danger' => trans('exceptions.backend.access.users.change_mismatch')]);
}
/** @test */
/*public function a_user_require_strong_password_to_change_password()
{
$data = [];
$data['old_password'] = '1234';
$data['password'] = '12345678';
$data['password_confirmation'] = '12345678';
$this->withExceptionHandling()
->actingAs($this->executive)
->patch(route('admin.access.user.change-password', $this->executive), $data)
->assertSessionHas('The given data was invalid.');
}*/
/** @test */
public function a_user_can_change_password()
{
Event::fake();
$data = [];
$data['old_password'] = '1234';
$data['password'] = 'Viral@1234';
$data['password_confirmation'] = 'Viral@1234';
$this->actingAs($this->admin)
->patch(route('admin.access.user.change-password', $this->admin), $data)
->assertSessionHas(['flash_success' => trans('alerts.backend.users.updated_password')]);
Event::assertDispatched(UserPasswordChanged::class);
}
}
<?php
namespace Tests\Feature\Backend\History;
use Tests\BrowserKitTestCase;
/**
* Class HistoryLogTest.
*/
class HistoryLogTest extends BrowserKitTestCase
{
/** @test **/
public function history_log_by_type_name_function()
{
$this->actingAs($this->admin);
history()
->withType('User')
->withText(trans('history.backend.users.created').$this->user->name)
->withEntity($this->user->id)
->withIcon('plus')
->withClass('bg-green')
->log();
$this->seeInDatabase('history',
[
'type_id' => 1,
'user_id' => $this->admin->id,
'entity_id' => $this->user->id,
'icon' => 'plus',
'class' => 'bg-green',
'text' => trans('history.backend.users.created').$this->user->name,
])
->visit('/admin/dashboard')
->see('<strong>'.$this->admin->name.'</strong> '.trans('history.backend.users.created').$this->user->name);
}
/** @test **/
public function history_log_By_TypeId_Function()
{
$this->actingAs($this->admin);
history()
->withType(1)
->withText(trans('history.backend.users.created').$this->user->name)
->withEntity($this->user->id)
->withIcon('plus')
->withClass('bg-green')
->log();
$this->seeInDatabase('history',
[
'type_id' => 1,
'user_id' => $this->admin->id,
'entity_id' => $this->user->id,
'icon' => 'plus',
'class' => 'bg-green',
'text' => trans('history.backend.users.created').$this->user->name,
])
->visit('/admin/dashboard')
->see('<strong>'.$this->admin->name.'</strong> '.trans('history.backend.users.created').$this->user->name);
}
}
<?php
namespace Tests\Feature\Backend\History;
use App\Models\Access\User\User;
use Tests\BrowserKitTestCase;
/**
* Class HistoryRenderEntityTest.
*/
class HistoryRenderEntityTest extends BrowserKitTestCase
{
/** @test **/
public function users_can_see_history_of_entity()
{
$this->actingAs($this->admin);
$test_user = factory(User::class)->create();
history()
->withType('User')
->withText('trans("history.backend.users.created") '.$this->user->name)
->withEntity($this->user->id)
->withIcon('plus')
->withClass('bg-green')
->log();
history()
->withType('User')
->withText('trans("history.backend.users.updated") '.$this->user->name)
->withEntity($this->user->id)
->withIcon('pencil')
->withClass('bg-blue')
->log();
history()
->withType('User')
->withText('trans("history.backend.users.deleted") '.$this->user->name)
->withEntity($this->user->id)
->withIcon('trash')
->withClass('bg-red')
->log();
history()
->withType('User')
->withText('trans("history.backend.roles.created") '.$test_user->name)
->withEntity($test_user->id)
->withIcon('plus')
->withClass('bg-red')
->log();
history()
->withType('User')
->withText('trans("history.backend.roles.updated") '.$test_user->name)
->withEntity($test_user->id)
->withIcon('pencil')
->withClass('bg-red')
->log();
history()
->withType('User')
->withText('trans("history.backend.roles.deleted") '.$test_user->name)
->withEntity($test_user->id)
->withIcon('trash')
->withClass('bg-red')
->log();
$this->visit('/admin/access/user/'.$this->user->id)
->see('<strong>'.$this->admin->name.'</strong> created user '.$this->user->name)
->see('<strong>'.$this->admin->name.'</strong> updated user '.$this->user->name)
->see('<strong>'.$this->admin->name.'</strong> deleted user '.$this->user->name)
->dontSee('<strong>'.$this->admin->name.'</strong> created user '.$test_user->name)
->dontSee('<strong>'.$this->admin->name.'</strong> updated user '.$test_user->name)
->dontSee('<strong>'.$this->admin->name.'</strong> deleted user '.$test_user->name);
}
}
<?php
namespace Tests\Feature\Backend\History;
use Tests\BrowserKitTestCase;
/**
* Class HistoryRenderTest.
*/
class HistoryRenderTest extends BrowserKitTestCase
{
/** @test **/
public function admin_users_can_see_history_on_dashboard()
{
$this->actingAs($this->admin);
history()
->withType('User')
->withText(trans('history.backend.users.created').$this->user->name)
->withEntity($this->user->id)
->withIcon('plus')
->withClass('bg-green')
->log();
$this->visit('/admin/dashboard')
->see('<strong>'.$this->admin->name.'</strong> '.trans('history.backend.users.created').$this->user->name);
}
/** @test **/
public function admin_users_can_see_history_on_user_show_page()
{
$this->actingAs($this->admin);
history()
->withType('User')
->withText(trans('history.backend.users.created').$this->user->name)
->withEntity($this->user->id)
->withIcon('plus')
->withClass('bg-green')
->log();
$this->visit('/admin/access/user/3')
->see('<strong>'.$this->admin->name.'</strong> '.trans('history.backend.users.created').$this->user->name);
}
}
<?php
namespace Tests\Feature\Backend;
use Tests\BrowserKitTestCase;
/**
* Class LogViewerRouteTest.
*/
class LogViewerRouteTest extends BrowserKitTestCase
{
/** @test **/
public function admin_users_can_see_logviewer_dashboard()
{
$this->actingAs($this->admin)
->visit('/admin/log-viewer')
->see('LogViewer');
}
/** @test **/
public function admin_users_can_see_logviewer_list()
{
$this->actingAs($this->admin)
->visit('/admin/log-viewer/logs')
->see('Logs');
}
/* @test **/
/*public function admin_users_can_see_logviewer_single_date()
{
$this->actingAs($this->admin)
->visit('/admin/log-viewer/logs/'.date('Y-m-d'))
->see('Log ['.date('Y-m-d').']');
}*/
/* @test **/
/*public function admin_users_can_see_logviewer_single_date_type()
{
$this->actingAs($this->admin)
->visit('/admin/log-viewer/logs/'.date('Y-m-d').'/error')
->see('Log ['.date('Y-m-d').']');
}*/
}
<?php
namespace Tests\Feature\Backend;
use App\Models\BlogCategories\BlogCategory;
use Tests\TestCase;
class ManageBlogCategoriesTest extends TestCase
{
/** @test */
public function a_user_can_view_blog_categories_index_page()
{
$this->actingAs($this->admin)
->get(route('admin.blogCategories.index'))
->assertViewIs('backend.blogcategories.index')
->assertSee(trans('labels.backend.blogcategories.management'))
->assertSee(trans('labels.backend.blogcategories.table.title'))
->assertSee(trans('labels.backend.blogcategories.table.status'))
->assertSee('Action');
}
/** @test */
public function a_user_can_create_a_blog_category()
{
$this->actingAs($this->admin);
$category = make(BlogCategory::class);
$this->post(route('admin.blogCategories.store'), $category->toArray());
$this->assertDatabaseHas(config('module.blog_categories.table'), ['name' => $category->name]);
}
/** @test */
public function a_blog_category_requires_a_name_while_creating()
{
$this->actingAs($this->admin)->withExceptionHandling();
$category = make(BlogCategory::class, ['name' => '']);
$this->post(route('admin.blogCategories.store'), $category->toArray())
->assertSessionHasErrors('name');
}
/** @test */
public function a_blog_category_requires_a_name_while_updating()
{
$this->actingAs($this->admin)->withExceptionHandling();
$category = create(BlogCategory::class);
$this->patch(route('admin.blogCategories.update', $category), ['name' => ''])
->assertSessionHasErrors('name');
}
/** @test */
public function a_user_can_update_a_blog_category()
{
$this->actingAs($this->admin);
$category = create(BlogCategory::class);
$this->patch(route('admin.blogCategories.update', $category), ['name' => 'New Category']);
$this->assertDatabaseHas(config('module.blog_categories.table'), ['name' => 'New Category', 'id' => $category->id]);
}
/** @test */
public function a_user_can_delete_a_blog_category()
{
$this->actingAs($this->admin);
$category = create(BlogCategory::class);
$this->delete(route('admin.blogCategories.destroy', $category));
$this->assertDatabaseMissing(config('module.blog_categories.table'), ['name' => $category->name, 'id' => $category->id, 'deleted_at' => null]);
}
/** @test */
public function a_user_can_not_update_a_blog_category_with_same_name()
{
$this->actingAs($this->admin)->withExceptionHandling();
$catCategory = create(BlogCategory::class, ['name' => 'Cat']);
$dogCategory = create(BlogCategory::class, ['name' => 'Dog']);
$this->patch(route('admin.blogCategories.update', $dogCategory),
['name' => 'Cat']
)->assertSessionHasErrors('name');
}
}
<?php
namespace Tests\Feature\Backend;
use App\Models\BlogTags\BlogTag;
use Tests\TestCase;
class ManageBlogTagsTest extends TestCase
{
/** @test */
public function a_user_can_view_blog_tags_index_page()
{
$this->actingAs($this->admin)
->get(route('admin.blogTags.index'))
->assertViewIs('backend.blogtags.index')
->assertSee(trans('labels.backend.blogtags.management'))
->assertSee(trans('labels.backend.blogtags.table.title'))
->assertSee(trans('labels.backend.blogtags.table.status'))
->assertSee('Action');
}
/** @test */
public function a_user_can_create_a_blog_tag()
{
$this->actingAs($this->admin);
$tag = make(BlogTag::class);
$this->post(route('admin.blogTags.store'), $tag->toArray());
$this->assertDatabaseHas(config('module.blog_tags.table'), ['name' => $tag->name]);
}
/** @test */
public function a_blog_tag_requires_a_name_while_creating()
{
$this->actingAs($this->admin)->withExceptionHandling();
$tag = make(BlogTag::class, ['name' => '']);
$this->post(route('admin.blogTags.store'), $tag->toArray())
->assertSessionHasErrors('name');
}
/** @test */
public function a_blog_tag_requires_a_name_while_updating()
{
$this->actingAs($this->admin)->withExceptionHandling();
$tag = create(BlogTag::class);
$this->patch(route('admin.blogTags.update', $tag), ['name' => ''])
->assertSessionHasErrors('name');
}
/** @test */
public function a_user_can_update_a_blog_tag()
{
$this->actingAs($this->admin);
$tag = create(BlogTag::class);
$this->patch(route('admin.blogTags.update', $tag), ['name' => 'New Tag']);
$this->assertDatabaseHas(config('module.blog_tags.table'), ['name' => 'New Tag', 'id' => $tag->id]);
}
/** @test */
public function a_user_can_delete_a_blog_tag()
{
$this->actingAs($this->admin);
$tag = create(BlogTag::class);
$this->delete(route('admin.blogTags.destroy', $tag));
$this->assertDatabaseMissing(config('module.blog_tags.table'), ['name' => $tag->name, 'id' => $tag->id, 'deleted_at' => null]);
}
/** @test */
public function a_user_can_not_update_a_blog_tag_with_same_name()
{
$this->actingAs($this->admin)->withExceptionHandling();
$catTag = create(BlogTag::class, ['name' => 'Cat']);
$dogTag = create(BlogTag::class, ['name' => 'Dog']);
$this->patch(route('admin.blogTags.update', $dogTag),
['name' => 'Cat']
)->assertSessionHasErrors('name');
}
}
<?php
namespace Tests\Feature\Backend;
use App\Models\Blogs\Blog;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class ManageBlogsTest extends TestCase
{
use WithFaker;
protected $blog;
protected $categories;
protected $tags;
public function setUp()
{
parent::setUp();
$this->actingAs($this->admin);
$this->blog = create(Blog::class);
$this->categories = [$this->faker->word, $this->faker->word];
$this->tags = [$this->faker->word, $this->faker->word];
}
/** @test */
public function a_user_can_view_blogs_index_page()
{
$this->actingAs($this->admin)
->get(route('admin.blogs.index'))
->assertViewIs('backend.blogs.index')
->assertSee(trans('labels.backend.blogs.management'))
->assertSee(trans('labels.backend.blogs.table.title'))
->assertSee(trans('labels.backend.blogs.table.publish'))
->assertSee(trans('labels.backend.blogs.table.createdby'))
->assertSee(trans('labels.backend.blogs.table.createdat'))
->assertSee(trans('labels.backend.blogs.table.status'))
->assertSee('Action');
}
/** @test */
public function a_user_can_create_a_blog()
{
$blog = make(Blog::class, [
'featured_image' => UploadedFile::fake()->image('logo.jpg'),
'categories' => $this->categories,
'tags' => $this->tags,
]);
$this->post(route('admin.blogs.store'), $blog->toArray());
$this->assertDatabaseHas(config('module.blogs.table'), ['name' => $blog->name, 'status' => $blog->status]);
//Assert Tags have been saved
$this->assertDatabaseHas(config('module.blog_tags.table'), ['name' => $this->tags[0]]);
$this->assertDatabaseHas(config('module.blog_tags.table'), ['name' => $this->tags[1]]);
//Assert Categories have been saved
$this->assertDatabaseHas(config('module.blog_categories.table'), ['name' => $this->categories[0]]);
$this->assertDatabaseHas(config('module.blog_categories.table'), ['name' => $this->categories[1]]);
}
public function makeBlog($overrides = [])
{
$this->withExceptionHandling();
$blog = make(Blog::class, $overrides);
return $blog;
}
/** @test */
public function it_requires_name_while_creating()
{
$blog = $this->makeBlog(['name' => '']);
$this->post(route('admin.blogs.store'), $blog->toArray())
->assertSessionHasErrors('name');
}
/** @test */
public function it_requires_content_while_creating()
{
$blog = $this->makeBlog(['content' => '']);
$this->post(route('admin.blogs.store'), $blog->toArray())
->assertSessionHasErrors('content');
}
/** @test */
public function it_requires_featured_image_while_creating()
{
$blog = $this->makeBlog(['featured_image' => '']);
$this->post(route('admin.blogs.store'), $blog->toArray())
->assertSessionHasErrors('featured_image');
}
/** @test */
public function it_requires_publish_datetime_while_creating()
{
$blog = $this->makeBlog();
unset($blog->publish_datetime);
$this->post(route('admin.blogs.store'), $blog->toArray())
->assertSessionHasErrors('publish_datetime');
}
/** @test */
public function it_requires_categories_while_creating()
{
$blog = $this->makeBlog(['categories' => '']);
$this->post(route('admin.blogs.store'), $blog->toArray())
->assertSessionHasErrors('categories');
}
/** @test */
public function it_requires_tags_while_creating()
{
$blog = $this->makeBlog(['tags' => '']);
$this->post(route('admin.blogs.store'), $blog->toArray())
->assertSessionHasErrors('tags');
}
/** @test */
public function it_can_store_featured_image()
{
$blog = make(Blog::class, [
'featured_image' => UploadedFile::fake()->image('logo.jpg'),
'categories' => $this->categories,
'tags' => $this->tags,
]);
$this->post(route('admin.blogs.store'), $blog->toArray());
$stored_blog = Blog::find(2);
Storage::disk('public')->assertExists('img/blog/'.$stored_blog->featured_image);
}
/** @test */
public function it_requires_name_while_updating()
{
$this->withExceptionHandling();
$this->blog->name = '';
$this->patch(route('admin.blogs.update', $this->blog), $this->blog->toArray())
->assertSessionHasErrors('name');
}
/** @test */
public function it_requires_content_while_updating()
{
$this->withExceptionHandling();
$this->blog->content = '';
$this->patch(route('admin.blogs.update', $this->blog), $this->blog->toArray())
->assertSessionHasErrors('content');
}
/** @test */
public function it_requires_publish_datetime_while_updating()
{
$this->withExceptionHandling();
unset($this->blog->publish_datetime);
$this->patch(route('admin.blogs.update', $this->blog), $this->blog->toArray())
->assertSessionHasErrors('publish_datetime');
}
/** @test */
public function it_requires_categories_while_updating()
{
$this->withExceptionHandling();
$this->patch(route('admin.blogs.update', $this->blog), $this->blog->toArray())
->assertSessionHasErrors('categories');
}
/** @test */
public function it_requires_tags_while_updating()
{
$this->withExceptionHandling();
$this->patch(route('admin.blogs.update', $this->blog), $this->blog->toArray())
->assertSessionHasErrors('tags');
}
/** @test */
public function a_user_can_update_blog()
{
$blog = make(Blog::class, [
'featured_image' => UploadedFile::fake()->image('logo.jpg'),
'name' => 'Changed Name',
'categories' => $this->categories,
'tags' => $this->tags,
]);
$this->patch(route('admin.blogs.update', $this->blog), $blog->toArray());
$this->assertDatabaseHas(config('module.blogs.table'), ['id' => $this->blog->id, 'name' => 'Changed Name']);
}
/** @test */
public function a_user_can_delete_a_blog()
{
$this->delete(route('admin.blogs.destroy', $this->blog));
$this->assertDatabaseMissing(config('module.blogs.table'), ['id' => $this->blog->id, 'deleted_at' => null]);
}
/** @test */
public function a_user_can_not_update_a_blog_with_same_name()
{
$this->actingAs($this->admin)->withExceptionHandling();
$catCategory = create(Blog::class, ['name' => 'Cat']);
$dogCategory = create(Blog::class, ['name' => 'Dog']);
$this->patch(route('admin.blogs.update', $dogCategory),
['name' => 'Cat']
)->assertSessionHasErrors('name');
}
}
<?php
namespace Tests\Feature\Backend;
use App\Models\Faqs\Faq;
use Tests\TestCase;
class ManageFaqsTest extends TestCase
{
/** @test */
public function a_user_can_view_faqs_index_page()
{
$this->actingAs($this->admin)
->get(route('admin.faqs.index'))
->assertViewIs('backend.faqs.index')
->assertSee(trans('labels.backend.faqs.management'))
->assertSee(trans('labels.backend.faqs.table.question'))
->assertSee(trans('labels.backend.faqs.table.answer'))
->assertSee(trans('labels.backend.faqs.table.status'))
->assertSee('Action');
}
/** @test */
public function a_user_can_create_faq()
{
$faq = make(Faq::class);
$this->actingAs($this->admin)
->post(route('admin.faqs.store'), $faq->toArray());
$this->assertDatabaseHas(config('module.faqs.table'), ['question' => $faq->question, 'answer' => $faq->answer]);
}
/** @test */
public function it_requires_question_while_creating()
{
$faq = make(Faq::class, ['question' => '']);
$this->actingAs($this->admin)
->withExceptionHandling()
->post(route('admin.faqs.store'), $faq->toArray())
->assertSessionHasErrors('question');
}
/** @test */
public function it_requires_answer_while_creating()
{
$faq = make(Faq::class, ['answer' => '']);
$this->actingAs($this->admin)
->withExceptionHandling()
->post(route('admin.faqs.store'), $faq->toArray())
->assertSessionHasErrors('answer');
}
/** @test */
public function it_requires_question_while_updating()
{
$faq = create(Faq::class);
$this->actingAs($this->admin)
->withExceptionHandling()
->patch(route('admin.faqs.update', $faq), ['question' => '', 'answer' => $faq->answer])
->assertSessionHasErrors('question');
}
/** @test */
public function it_requires_answer_while_updating()
{
$faq = create(Faq::class);
$this->actingAs($this->admin)
->withExceptionHandling()
->patch(route('admin.faqs.update', $faq), ['question' => $faq->question, 'answer' => ''])
->assertSessionHasErrors('answer');
}
/** @test */
public function a_user_can_update_faq()
{
$faq = create(Faq::class);
$changed_question = 'What is Life?';
$changed_answer = $faq->answer;
$this->actingAs($this->admin)
->patch(route('admin.faqs.update', $faq), ['question' => $changed_question, 'answer' => $changed_answer]);
$this->assertDatabaseHas(config('module.faqs.table'), ['id' => $faq->id, 'question' => $changed_question, 'answer' => $changed_answer]);
}
/** @test */
public function a_user_can_delete_faq()
{
$faq = create(Faq::class);
$this->actingAs($this->admin)
->delete(route('admin.faqs.destroy', $faq));
$this->assertDatabaseMissing(config('module.faqs.table'), ['id' => $faq->id, 'deleted_at' => null]);
}
}
<?php
namespace Tests\Feature\Backend;
use App\Models\Page\Page;
use Tests\TestCase;
class ManagePagesTest extends TestCase
{
/** @test */
public function a_user_can_view_pages()
{
$this->actingAs($this->admin)
->get(route('admin.pages.index'))
->assertSee(trans('labels.backend.pages.management'))
->assertSee(trans('labels.backend.pages.table.title'))
->assertSee(trans('labels.backend.pages.table.status'))
->assertSee($this->admin->name);
}
/** @test */
public function test_create_and_edit_page_has_all_fields()
{
$this->actingAs($this->admin)
->get(route('admin.pages.create'))
->assertSee(trans('validation.attributes.backend.pages.title'))
->assertSee(trans('validation.attributes.backend.pages.description'))
->assertSee(trans('validation.attributes.backend.pages.cannonical_link'))
->assertSee(trans('validation.attributes.backend.pages.seo_title'))
->assertSee(trans('validation.attributes.backend.pages.seo_keyword'))
->assertSee(trans('validation.attributes.backend.pages.seo_description'))
->assertSee(trans('validation.attributes.backend.pages.is_active'));
$page = create(Page::class);
$this->actingAs($this->admin)
->get(route('admin.pages.edit', $page))
->assertSee(trans('validation.attributes.backend.pages.title'))
->assertSee(trans('validation.attributes.backend.pages.description'))
->assertSee(trans('validation.attributes.backend.pages.cannonical_link'))
->assertSee(trans('validation.attributes.backend.pages.seo_title'))
->assertSee(trans('validation.attributes.backend.pages.seo_keyword'))
->assertSee(trans('validation.attributes.backend.pages.seo_description'))
->assertSee(trans('validation.attributes.backend.pages.is_active'));
}
/** @test */
public function a_user_can_create_page()
{
$page = make(Page::class);
$this->actingAs($this->admin)
->post(route('admin.pages.store'), $page->toArray())
->assertRedirect(route('admin.pages.index'));
$this->assertDatabaseHas('pages', ['title' => $page->title, 'description' => $page->description]);
}
/** @test */
public function it_requires_title_on_create()
{
$page = make(Page::class, ['title' => '']);
$this->withExceptionHandling()
->actingAs($this->admin)
->post(route('admin.pages.store'), $page->toArray())
->assertSessionHasErrors('title');
}
/** @test */
public function it_requires_description_while_create()
{
$page = make(Page::class, ['description' => '']);
$this->withExceptionHandling()
->actingAs($this->admin)
->post(route('admin.pages.store'), $page->toArray())
->assertSessionHasErrors('description');
}
/** @test */
public function a_user_can_update_page()
{
$page = create(Page::class);
$title = 'Changed title';
$slug = str_slug($title);
$description = 'Changed Description';
$this->actingAs($this->admin)
->patch(route('admin.pages.update', $page), ['title' => $title, 'description' => $description]);
$this->assertDatabaseHas('pages', ['id' => $page->id, 'title' => $title, 'page_slug' => $slug, 'description' => $description]);
}
/** @test */
public function it_requires_title_on_update()
{
$page = create(Page::class);
$page1 = $page->toArray();
$page1['title'] = '';
$this->withExceptionHandling()
->actingAs($this->admin)
->patch(route('admin.pages.update', $page), $page1)
->assertSessionHasErrors('title');
}
/** @test */
public function it_requires_description_while_update()
{
$page = create(Page::class);
$page1 = $page->toArray();
$page1['description'] = '';
$this->withExceptionHandling()
->actingAs($this->admin)
->patch(route('admin.pages.update', $page), $page1)
->assertSessionHasErrors('description');
}
/** @test */
public function a_user_can_delete_a_page()
{
$this->actingAs($this->admin);
$page = create(Page::class);
$this->delete(route('admin.pages.destroy', $page));
$this->assertDatabaseMissing(config('module.pages.table'), ['name' => $page->name, 'id' => $page->id, 'deleted_at' => null]);
}
}
<?php
namespace Tests\Feature\Backend;
use App\Events\Backend\Access\Permission\PermissionCreated;
use App\Events\Backend\Access\Permission\PermissionDeleted;
use App\Events\Backend\Access\Permission\PermissionUpdated;
use App\Models\Access\Permission\Permission;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
class ManagePermissionsTest extends TestCase
{
/** @test */
public function a_user_can_view_permissions()
{
$this->actingAs($this->admin)
->get(route('admin.access.permission.index'))
->assertViewIs('backend.access.permissions.index')
->assertSee(trans('labels.backend.access.permissions.management'))
->assertSee('Action');
}
/** @test */
public function a_permission_requires_a_name()
{
$permission = make(Permission::class, ['name' => null])->toArray();
return $this->withExceptionHandling()
->actingAs($this->admin)
->post(route('admin.access.permission.store'), $permission)
->assertSessionHasErrors('name');
}
/** @test */
public function a_permission_requires_a_display_name()
{
$permission = make(Permission::class, ['display_name' => null])->toArray();
return $this->withExceptionHandling()
->actingAs($this->admin)
->post(route('admin.access.permission.store'), $permission)
->assertSessionHasErrors('display_name');
}
/** @test */
public function a_user_can_create_new_permission()
{
// Make sure our events are fired
Event::fake();
$permission = make(Permission::class, ['name' => 'test permission'])->toArray();
$this->actingAs($this->admin)
->post(route('admin.access.permission.store'), $permission)
->assertRedirect(route('admin.access.permission.index'))
->assertSessionHas(['flash_success' => trans('alerts.backend.permissions.created')]);
$this->assertDatabaseHas(config('access.permissions_table'), [
'name' => $permission['name'],
]);
Event::assertDispatched(PermissionCreated::class);
}
/** @test */
public function it_fails_for_validation_on_update_permission()
{
$permission = create(Permission::class);
$data = $permission->toArray();
$data['name'] = '';
$this->withExceptionHandling()
->actingAs($this->admin)
->patch(route('admin.access.permission.update', $permission), $data)
->assertSessionHasErrors(['name']);
}
/** @test */
public function a_user_can_update_permission()
{
Event::fake();
$permission = create(Permission::class);
$data = $permission->toArray();
$data['name'] = 'Updated Permission Name';
$this->withExceptionHandling()
->actingAs($this->admin)
->patch(route('admin.access.permission.update', $permission), $data)
->assertRedirect(route('admin.access.permission.index'))
->assertSessionHas(['flash_success' => trans('alerts.backend.permissions.updated')]);
$this->assertDatabaseHas(config('access.permissions_table'), [
'name' => $data['name'],
]);
Event::assertDispatched(PermissionUpdated::class);
}
/** @test */
public function a_user_can_delete_a_permission()
{
Event::fake();
$permission = create(Permission::class);
$this->actingAs($this->admin)
->delete(route('admin.access.permission.destroy', $permission))
->assertStatus(302)
->assertSessionHas(['flash_success' => trans('alerts.backend.permissions.deleted')]);
/*$this->assertDatabaseMissing('permissions', [
'name' => $permission->name, 'id' => $permission->id
]);*/
Event::assertDispatched(PermissionDeleted::class);
}
}
<?php
namespace Tests\Feature\Backend;
use App\Events\Backend\Access\Role\RoleCreated;
use App\Events\Backend\Access\Role\RoleDeleted;
use App\Events\Backend\Access\Role\RoleUpdated;
use App\Exceptions\GeneralException;
use App\Models\Access\Permission\Permission;
use App\Models\Access\Role\Role;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
class ManageRolesTest extends TestCase
{
/** @test */
public function a_user_can_view_roles()
{
$this->actingAs($this->admin)
->get(route('admin.access.role.index'))
->assertViewIs('backend.access.roles.index')
->assertSee(trans('labels.backend.access.roles.management'))
->assertSee('Action');
}
/** @test */
public function a_role_requires_a_name()
{
$role = make(Role::class, ['name' => null])->toArray();
return $this->withExceptionHandling()
->actingAs($this->admin)
->post(route('admin.access.role.store'), $role)
->assertSessionHasErrors('name');
}
/** @test */
public function a_role_requires_a_permission_if_associated_permissions_is_not_set_to_all()
{
$role = make(Role::class)->toArray();
$role['associated_permissions'] = 'custom';
return $this->withExceptionHandling()
->actingAs($this->admin)
->post(route('admin.access.role.store'), $role)
->assertSessionHasErrors('permissions');
}
/** @test */
/*public function a_role_can_not_create_if_name_is_already_exists()
{
$role = make(Role::class, ['name' => $this->adminRole->name])->toArray();
return $this->withExceptionHandling()
->actingAs($this->admin)
->post(route('admin.access.role.store'), $role);
$this->assertSessionHas(['flash_danger' => trans('exceptions.backend.access.roles.already_exists')]);
$this->expectException(GeneralException::class);
}*/
/** @test */
public function a_user_can_create_new_role()
{
// Make sure our events are fired
Event::fake();
$role = make(Role::class, ['name' => 'test Role'])->toArray();
$role['associated_permissions'] = 'all';
$this->actingAs($this->admin)
->post(route('admin.access.role.store'), $role)
->assertRedirect(route('admin.access.role.index'))
->assertSessionHas(['flash_success' => trans('alerts.backend.roles.created')]);
$this->assertDatabaseHas(config('access.roles_table'), [
'name' => $role['name'],
]);
Event::assertDispatched(RoleCreated::class);
}
/** @test */
public function a_user_can_create_new_role_with_permissions()
{
// Make sure our events are fired
Event::fake();
$role = make(Role::class, ['name' => 'test Role'])->toArray();
$permission = create(Permission::class);
$role['associated_permissions'] = 'custom';
$role['permissions'] = [$permission->id];
$this->actingAs($this->admin)
->post(route('admin.access.role.store'), $role)
->assertRedirect(route('admin.access.role.index'))
->assertSessionHas(['flash_success' => trans('alerts.backend.roles.created')]);
$this->assertDatabaseHas(config('access.roles_table'), [
'name' => $role['name'],
]);
$this->assertDatabaseHas(config('access.permissions_table'), ['name' => $permission->name]);
$this->assertDatabaseHas(config('access.permission_role_table'), ['permission_id' => $permission->id]);
Event::assertDispatched(RoleCreated::class);
}
/** @test */
public function it_fails_for_validation_on_update_role()
{
$role = create(Role::class);
$data = $role->toArray();
$data['name'] = '';
$this->withExceptionHandling()
->actingAs($this->admin)
->patch(route('admin.access.role.update', $role), $data)
->assertSessionHasErrors(['name']);
}
/** @test */
public function a_user_can_update_role()
{
Event::fake();
$role = create(Role::class);
$permission = create(Permission::class);
$data = $role->toArray();
$data['associated_permissions'] = 'custom';
$data['permissions'] = [$permission->id];
$data['name'] = 'Updated Role Name';
$this->withExceptionHandling()
->actingAs($this->admin)
->patch(route('admin.access.role.update', $role), $data)
->assertRedirect(route('admin.access.role.index'))
->assertSessionHas(['flash_success' => trans('alerts.backend.roles.updated')]);
$this->assertDatabaseHas(config('access.roles_table'), [
'name' => $data['name'],
]);
$this->assertDatabaseHas(config('access.permissions_table'), ['name' => $permission->name]);
$this->assertDatabaseHas(config('access.permission_role_table'), ['permission_id' => $permission->id]);
Event::assertDispatched(RoleUpdated::class);
}
/** @test */
public function a_user_can_delete_a_role()
{
Event::fake();
$role = create(Role::class);
$this->actingAs($this->admin)
->delete(route('admin.access.role.destroy', $role))
->assertStatus(302)
->assertSessionHas(['flash_success' => trans('alerts.backend.roles.deleted')]);
/*$this->assertDatabaseMissing(config('access.roles_table'), [
'name' => $role->name,
'id' => $role->id
]);*/
Event::assertDispatched(RoleDeleted::class);
}
}
<?php
namespace Tests\Feature\Backend;
use App\Models\Settings\Setting;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class ManageSettingsTest extends TestCase
{
protected $setting;
public function setUp()
{
parent::setUp();
$this->setting = Setting::find(1);
$this->actingAs($this->admin);
}
/** @test */
public function setting_page_shows_different_tabs()
{
$this->get(route('admin.settings.edit', $this->setting))
->assertSee(__('labels.backend.settings.seo'))
->assertSee(__('labels.backend.settings.companydetails'))
->assertSee(__('labels.backend.settings.mail'))
->assertSee(__('labels.backend.settings.footer'))
->assertSee(__('labels.backend.settings.terms'))
->assertSee(__('labels.backend.settings.google'));
}
/** @test */
public function it_can_update_a_valid_site_logo()
{
$this->patch(route('admin.settings.update', $this->setting), [
'logo' => UploadedFile::fake()->image('logo.jpg', 226, 48),
]);
Storage::disk('public')->assertExists('img/logo/'.$this->setting->logo);
}
/** @test */
public function it_throws_error_for_valid_site_logo()
{
$this->withExceptionHandling();
$this->patch(route('admin.settings.update', $this->setting), [
'logo' => UploadedFile::fake()->image('logo.jpg', 200, 500),
])
->assertSessionHasErrors('logo');
}
/** @test */
public function it_can_update_site_favicon()
{
$this->patch(route('admin.settings.update', $this->setting), [
'favicon' => UploadedFile::fake()->image('favicon.jpg', 16, 16),
]);
Storage::disk('public')->assertExists('img/favicon/'.$this->setting->favicon);
}
/** @test */
public function it_throws_error_for_valid_site_favicon()
{
$this->withExceptionHandling();
$this->patch(route('admin.settings.update', $this->setting), [
'favicon' => UploadedFile::fake()->image('favicon.jpg', 200, 500),
])
->assertSessionHasErrors('favicon');
}
}
This diff is collapsed.
<?php
namespace Tests\Feature\Frontend;
use App\Events\Frontend\Auth\UserLoggedOut;
use Illuminate\Support\Facades\Event;
use Tests\BrowserKitTestCase;
/**
* Class LoggedInRouteTest.
*/
class LoggedInRouteTest extends BrowserKitTestCase
{
/**
* Test the homepage works and the dashboard button appears.
*/
public function testHomePageLoggedIn()
{
$this->actingAs($this->user)->visit('/')->see('Dashboard')->see($this->user->name)->dontSee('Administration');
}
/**
* Test the dashboard page works and displays the users information.
*/
/** @test */
public function dashboard_page_loads_properly()
{
$this->actingAs($this->user)
->visit('/dashboard')
->see($this->user->email)
->see('Joined')
->dontSee('Administration');
}
/**
* Test the account page works and displays the users information.
*/
/** @test */
public function account_page_loads_properly()
{
$this->actingAs($this->user)
->visit('/account')
->see('My Account')
->see('Profile')
->see('Update Information')
->see('Change Password')
->dontSee('Administration');
}
/** @test */
public function users_can_logout()
{
// Make sure our events are fired
Event::fake();
$this->actingAs($this->user)->visit('/logout')->see('Login')->see('Register');
Event::assertDispatched(UserLoggedOut::class);
}
}
<?php
namespace Tests\Feature\Frontend;
use App\Events\Frontend\Auth\UserConfirmed;
use App\Models\Access\User\User;
use App\Notifications\Frontend\Auth\UserNeedsConfirmation;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Notification;
use Tests\BrowserKitTestCase;
/**
* Class LoggedOutRouteTest.
*/
class LoggedOutRouteTest extends BrowserKitTestCase
{
/**
* User Logged Out Frontend.
*/
/** @test */
public function test_homePage()
{
$this->visit('/')->assertResponseOk();
}
/** @test */
public function testLoginPage()
{
$this->visit('/login')->see('Login');
}
/** @test */
public function testRegisterPage()
{
$this->visit('/register')->see('Register');
}
/** @test */
public function testForgotPasswordPage()
{
$this->visit('password/reset')->see('Reset Password');
}
/** @test */
public function testDashboardPageLoggedOut()
{
$this->visit('/dashboard')->seePageIs('/login');
}
/** @test */
public function testAccountPageLoggedOut()
{
$this->visit('/account')->seePageIs('/login');
}
/**
* Create an unconfirmed user and assure the user gets
* confirmed when hitting the confirmation route.
*/
/** @test */
public function confirm_account_route()
{
Event::fake();
// Create default user to test with
$unconfirmed = factory(User::class)->states('unconfirmed')->create();
$unconfirmed->attachRole(3); //User
$this->visit('/account/confirm/'.$unconfirmed->confirmation_code)
->seePageIs('/login')
->see('Your account has been successfully confirmed!')
->seeInDatabase(config('access.users_table'), ['email' => $unconfirmed->email, 'confirmed' => 1]);
Event::assertDispatched(UserConfirmed::class);
}
/**
* Assure the user gets resent a confirmation email
* after hitting the resend confirmation route.
*/
/** @test */
public function resend_confirm_account_route()
{
Notification::fake();
$this->visit('/account/confirm/resend/'.$this->user->id)
->seePageIs('/login')
->see('A new confirmation e-mail has been sent to the address on file.');
Notification::assertSentTo(
[$this->user],
UserNeedsConfirmation::class
);
}
/** @test */
public function test_404Page()
{
$response = $this->call('GET', '7g48hwbfw9eufj');
$this->assertEquals(404, $response->getStatusCode());
$this->assertContains('Page Not Found', $response->getContent());
}
}
......@@ -54,7 +54,7 @@ abstract class TestCase extends BaseTestCase
/**
* Set up tests.
*/
public function setUp()
public function setUp(): void
{
parent::setUp();
......@@ -80,7 +80,7 @@ abstract class TestCase extends BaseTestCase
$this->userRole = Role::find(3);
}
public function tearDown()
public function tearDown(): void
{
$this->beforeApplicationDestroyed(function () {
DB::disconnect();
......
const { mix } = require('laravel-mix');
const mix = require('laravel-mix');
const WebpackRTLPlugin = require('webpack-rtl-plugin');
/*
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment