Repository: moell-peng/mojito Branch: master Commit: 605804189bfe Files: 74 Total size: 106.4 KB Directory structure: gitextract_aqzc1goi/ ├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── config/ │ └── mojito.php ├── database/ │ └── migrations/ │ ├── add_custom_field_permission_tables.php │ ├── create_admin_table.php │ ├── create_menu_table.php │ └── create_permission_group_table.php ├── phpunit.xml ├── src/ │ ├── AdminUserFactory.php │ ├── Console/ │ │ └── InstallCommand.php │ ├── Contacts/ │ │ └── UserContact.php │ ├── Database/ │ │ └── MojitoTableSeeder.php │ ├── Http/ │ │ ├── Controllers/ │ │ │ ├── AdminUserController.php │ │ │ ├── CaptchaController.php │ │ │ ├── ChangePasswordController.php │ │ │ ├── Controller.php │ │ │ ├── LoginController.php │ │ │ ├── MenuController.php │ │ │ ├── PermissionController.php │ │ │ ├── PermissionGroupController.php │ │ │ └── RoleController.php │ │ ├── Middleware/ │ │ │ └── Authenticate.php │ │ ├── MojitoResponse.php │ │ └── Requests/ │ │ ├── AdminUser/ │ │ │ └── CreateOrUpdateRequest.php │ │ ├── ChangePasswordRequest.php │ │ ├── Menu/ │ │ │ └── CreateOrUpdateRequest.php │ │ ├── Permission/ │ │ │ └── CreateOrUpdateRequest.php │ │ ├── PermissionGroup/ │ │ │ └── CreateOrUpdateRequest.php │ │ └── Role/ │ │ └── CreateOrUpdateRequest.php │ ├── Models/ │ │ ├── AdminUser.php │ │ ├── Menu.php │ │ ├── Permission.php │ │ ├── PermissionGroup.php │ │ └── User.php │ ├── Providers/ │ │ └── MojitoServiceProvider.php │ ├── Resources/ │ │ ├── AdminUser.php │ │ ├── AdminUserCollection.php │ │ ├── Menu.php │ │ ├── Permission.php │ │ ├── PermissionCollection.php │ │ ├── PermissionGroup.php │ │ ├── PermissionGroupCollection.php │ │ ├── Role.php │ │ └── RoleCollection.php │ ├── helpers.php │ └── routes.php └── tests/ ├── Feature/ │ ├── AdminUserControllerTest.php │ ├── CaptchaControllerTest.php │ ├── ChangePasswordControllerTest.php │ ├── FeatureTestCase.php │ ├── MenuControllerTest.php │ ├── PermissionControllerTest.php │ ├── PermissionGroupControllerTest.php │ └── RoleControllerTest.php ├── Fixtures/ │ ├── Http/ │ │ └── Kernel.php │ └── database/ │ ├── factories/ │ │ └── AdminUserFactory.php │ └── migrations/ │ ├── 0000_00_00_000001_create_permission_test_tables.php │ ├── 0000_00_00_000002_add_custom_field_permission_test_tables.php │ ├── 0000_00_00_000003_create_admin_test_table.php │ ├── 0000_00_00_000004_create_permission_group_test_table.php │ └── 0000_00_00_000005_create_menu_test_table.php ├── TestCase.php └── Unit/ ├── AdminUserFactoryTest.php ├── Requests/ │ ├── AdminUserCreateOrUpdateRequestTest.php │ ├── ChangePasswordRequestTest.php │ ├── MenuCreateOrUpdateRequestTest.php │ ├── PermissionCreateOrUpdateRequestTest.php │ ├── PermissionGroupCreateOrUpdateRequestTest.php │ └── RoleCreateOrUpdateRequestTest.php ├── ResponseTest.php └── ServiceProviderTest.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ /tests export-ignore phpunit.xml export-ignore ================================================ FILE: .gitignore ================================================ /.idea /vendor composer.lock .phpunit.result.cache ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Mojito Mojito 是基于 Laravel 开发的 [Mojito Admin](https://github.com/moell-peng/mojito-admin) 的服务端。 3.0 版本开始, 已将原来的项目分离为两个代码库,分别为以Vue3、Element Plus、Vite 开发的前端模板 [mojito -admin](https://github.com/moell-peng/mojito-admin) 和服务端 [mojito](https://github.com/moell-peng/mojito) 。如果是需要使用 vue2 版本,请访问 [2.0](https://github.com/moell-peng/mojito/tree/2.0) 分支。 ## Mojito Admin 截图 ![mojito.png](http://ww1.sinaimg.cn/large/7a679ca1gy1gtu09c4avej21590kstdb.jpg) ## 特性 * 前后端分离,提供 [Mojito Admin](https://github.com/moell-peng/mojito-admin) 前端模板 * 基于 laravel-permission 权限管理 * 基于 sanctum 鉴权 * 提供角色,权限,用户,菜单管理等功能的API * 多个后台支持统一管理权限,菜单和角色 * 完善的PHPUnit测试 ## 要求 - Laravel >= 7.0.0 - PHP >= 7.2.0 ## 安装 首先安装laravel,并且确保你配置了正确的数据库连接。 ``` composer require moell/mojito ``` 然后运行下面的命令来发布资源: ``` php artisan mojito:install ``` 命令执行成功会生成配置文件,数据迁移和构建SPA的文件。 修改 `app/Http/Kernel.php` : ``` class Kernel extends HttpKernel { protected $routeMiddleware = [ ... 'mojito.permission' => \Moell\Mojito\Http\Middleware\Authenticate::class, ]; protected $middlewareGroups = [ ... 'api' => [ ... \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, ], ]; } ``` 执行数据迁移,数据填充 ``` php artisan migrate php artisan db:seed --class="Moell\Mojito\Database\MojitoTableSeeder" ``` 后台登录的账号 `admin` , 密码 `secret` ## 路由中间件 * auth:sanctum 用于鉴权 * mojito.permission 权限验证 ## mojito.php 可选配置 ```php return [ 'guards' => [ // laravel-permission 相对应的 guard 'admin' => [ 'model' => \Moell\Mojito\Models\AdminUser::class, //登录鉴权的模型 'login_fields' => [ // 登录验证的字段,支持多个 'username', ], 'conditions' => [ // 登录验证的额外条件 ['status', '=', 1] ] ] ], 'route_prefix' => "api", //路由前缀 'middleware' => [ 'basic' => 'api', //基础中间件 'auth' => ['auth:sanctum'], //鉴权中间件 'permission' => ['auth:sanctum', 'mojito.permission'] //包含权限检测的中间件 ] ]; ``` ## 依赖扩展包 * spatie/laravel-permission * laravel/sanctum ## 常见错误 * csrf token missing or incorrect , 请修改 sanctum.php 中的 `stateful` , 如 vite 使用的 `localhost:3000 `去除即可。更多详细请访问`laravel/sanctum`文档。 ## 打赏

## License Apache License Version 2.0 see http://www.apache.org/licenses/LICENSE-2.0.html ================================================ FILE: composer.json ================================================ { "name": "moell/mojito", "description": "Mojito admin is a component of laravel, vue, element build backend system.", "keywords": ["laravel", "admin", "vue", "element", "laravel admin", "vue admin", "element admin"], "type": "library", "license": "MIT", "authors": [ { "name": "moell", "email": "moell91@foxmail.com" } ], "require": { "php": "^7.2|^8.0", "spatie/laravel-permission": "^5.3", "laravel/sanctum": "^2.4|^3.2", "gregwar/captcha": "^1.1" }, "require-dev": { "mockery/mockery": "^1.0", "orchestra/testbench": "^5.0|^6.0|^7.0|^8.0", "dms/phpunit-arraysubset-asserts": "^0.4.0", "doctrine/dbal": "^2.8", "laravel/legacy-factories": "^1.0.4" }, "autoload": { "psr-4": { "Moell\\Mojito\\": "src/" }, "files": [ "src/helpers.php" ] }, "autoload-dev": { "psr-4": { "Moell\\Mojito\\Tests\\": "tests/" } }, "extra": { "laravel": { "providers": [ "Moell\\Mojito\\Providers\\MojitoServiceProvider" ] } }, "minimum-stability":"dev", "prefer-stable": true } ================================================ FILE: config/mojito.php ================================================ [ 'admin' => [ 'model' => \Moell\Mojito\Models\AdminUser::class, 'login_fields' => [ 'username', ], 'conditions' => [ ['status', '=', 1] ] ] ], 'route_prefix' => "api", 'middleware' => [ 'basic' => 'api', 'auth' => ['auth:sanctum'], 'permission' => ['auth:sanctum', 'mojito.permission'] ], 'captcha_cache_ttl' => 2, ]; ================================================ FILE: database/migrations/add_custom_field_permission_tables.php ================================================ integer('pg_id')->default(0); $table->string('display_name', 50)->nullable(); $table->string('icon', 30)->nullable(); $table->smallInteger('sequence')->nullable(); $table->string('created_name', 50)->nullable(); $table->string('updated_name', 50)->nullable(); $table->string('description')->nullable(); }); Schema::table($tableNames['roles'], function (Blueprint $table) { $table->string('description')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { $tableNames = config('permission.table_names'); Schema::table($tableNames['permissions'], function (Blueprint $table) { $table->dropColumn('display_name'); $table->dropColumn('icon'); $table->dropColumn('sequence'); $table->dropColumn('created_name'); $table->dropColumn('updated_name'); $table->dropColumn('description'); }); Schema::table($tableNames['roles'], function (Blueprint $table) { $table->dropColumn('description'); }); } } ================================================ FILE: database/migrations/create_admin_table.php ================================================ increments('id'); $table->string('name'); $table->string('username')->unique(); $table->string('password'); $table->boolean("status"); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('admin_users'); } } ================================================ FILE: database/migrations/create_menu_table.php ================================================ increments('id'); $table->integer('parent_id')->default(0); $table->string('icon', 50)->nullable(); $table->string('uri'); $table->tinyInteger('is_link')->default(0)->comment('0-no;1-yes'); $table->string('permission_name', 50)->nullable(); $table->string('name'); $table->string('guard_name', 30); $table->smallInteger('sequence')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('menus'); } } ================================================ FILE: database/migrations/create_permission_group_table.php ================================================ increments('id'); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('permission_groups'); } } ================================================ FILE: phpunit.xml ================================================ ./tests/Feature ./tests/Unit src/ ================================================ FILE: src/AdminUserFactory.php ================================================ * @return mixed */ public function handle() { $this->call('vendor:publish', ['--provider' => 'Spatie\Permission\PermissionServiceProvider']); $this->call('vendor:publish', ['--provider' => 'Moell\Mojito\Providers\MojitoServiceProvider']); $this->call('vendor:publish', ['--provider' => 'Laravel\Sanctum\SanctumServiceProvider']); } } ================================================ FILE: src/Contacts/UserContact.php ================================================ 'admin-user.index', 'display_name' => '列表', 'pg_id' => 1 ], [ 'name' => 'admin-user.show', 'display_name' => '详细', 'pg_id' => 1 ], [ 'name' => 'admin-user.store', 'display_name' => '添加', 'pg_id' => 1 ], [ 'name' => 'admin-user.update', 'display_name' => '修改', 'pg_id' => 1 ], [ 'name' => 'admin-user.destroy', 'display_name' => '删除', 'pg_id' => 1 ], [ 'name' => 'admin-user.roles', 'display_name' => '用户角色列表', 'pg_id' => 1 ], [ 'name' => 'admin-user.assign-roles', 'display_name' => '分配角色', 'pg_id' => 1 ], [ 'name' => 'role.index', 'display_name' => '列表', 'pg_id' => 2 ], [ 'name' => 'role.show', 'display_name' => '详细', 'pg_id' => 2 ], [ 'name' => 'role.store', 'display_name' => '添加', 'pg_id' => 2 ], [ 'name' => 'role.update', 'display_name' => '修改', 'pg_id' => 2 ], [ 'name' => 'role.destroy', 'display_name' => '删除', 'pg_id' => 2 ], [ 'name' => 'role.permissions', 'display_name' => '获取角色的权限', 'pg_id' => 2 ], [ 'name' => 'role.assign-permissions', 'display_name' => '角色分配权限', 'pg_id' => 2 ], [ 'name' => 'role.guard-name-roles', 'display_name' => '看守器对应的所有角色', 'pg_id' => 2 ], [ 'name' => 'permission.index', 'display_name' => '列表', 'pg_id' => 3 ], [ 'name' => 'permission.show', 'display_name' => '详细', 'pg_id' => 3 ], [ 'name' => 'permission.store', 'display_name' => '添加', 'pg_id' => 3 ], [ 'name' => 'permission.update', 'display_name' => '修改', 'pg_id' => 3 ], [ 'name' => 'permission.destroy', 'display_name' => '删除', 'pg_id' => 3 ], [ 'name' => 'menu.index', 'display_name' => '列表', 'pg_id' => 4 ], [ 'name' => 'menu.show', 'display_name' => '详细', 'pg_id' => 4 ], [ 'name' => 'menu.store', 'display_name' => '添加', 'pg_id' => 4 ], [ 'name' => 'menu.update', 'display_name' => '修改', 'pg_id' => 4 ], [ 'name' => 'menu.destroy', 'display_name' => '删除', 'pg_id' => 4 ], [ 'name' => 'permission-group.index', 'display_name' => '列表', 'pg_id' => 5 ], [ 'name' => 'permission-group.show', 'display_name' => '详细', 'pg_id' => 5 ], [ 'name' => 'permission-group.store', 'display_name' => '添加', 'pg_id' => 5 ], [ 'name' => 'permission-group.update', 'display_name' => '修改', 'pg_id' => 5 ], [ 'name' => 'permission-group.destroy', 'display_name' => '删除', 'pg_id' => 5 ], [ 'name' => 'permission-group.guard-name-for-permission', 'display_name' => '获取看守器权限', 'pg_id' => 5 ], [ 'name' => 'permission-group.all', 'display_name' => '所有权限组', 'pg_id' => 5 ] ]; /** * Run the database seeds. * * @author moell * @return void */ public function run() { app()['cache']->forget('spatie.permission.cache'); $this->createdAdminUser(); $this->createPermissionGroup(); $this->createRole(); $this->createPermission(); $this->createMenu(); $this->associateRolePermissions(); } /** * @author moell */ private function createdAdminUser() { AdminUserFactory::adminUser()->truncate(); AdminUserFactory::adminUser()->create([ 'name' => 'admin', 'username' => 'admin', 'status' => 1, 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret ]); } /** * @author moell */ private function createPermission() { Permission::query()->delete(); foreach ($this->permissions as $permission) { $permission['guard_name'] = 'admin'; Permission::create($permission); } } /** * @author moell */ private function createPermissionGroup() { PermissionGroup::truncate(); PermissionGroup::insert([ [ 'id' => 1, 'name' => '管理员', ], [ 'id' => 2, 'name' => '角色' ], [ 'id' => 3, 'name' => '权限' ], [ 'id' => 4, 'name' => '菜单' ], [ 'id' => 5, 'name' => '权限组' ] ]); } /** * @author moell */ private function createRole() { Role::query()->delete(); Role::create([ 'name' => 'admin', 'guard_name' => 'admin' ]); } /** * @author moell */ private function createMenu() { Menu::truncate(); Menu::insert([ [ 'id' => 1, 'parent_id' => 0, 'uri' => '/dashboard', 'name' => 'Dashboard', 'icon' => 'Orange', 'guard_name'=> 'admin' ], [ 'id' => 2, 'parent_id' => 0, 'uri' => '/admin', 'name' => '系统管理', 'icon' => 'Setting', 'guard_name'=> 'admin' ], [ 'id' => 3, 'parent_id' => 2, 'uri' => '/admin-user', 'name' => '管理员', 'icon' => '', 'guard_name'=> 'admin' ], [ 'id' => 4, 'parent_id' => 2, 'uri' => '/role', 'name' => '角色', 'icon' => '', 'guard_name'=> 'admin' ], [ 'id' => 5, 'parent_id' => 2, 'uri' => '/permission', 'name' => '权限', 'icon' => '', 'guard_name'=> 'admin' ], [ 'id' => 6, 'parent_id' => 2, 'uri' => '/menu', 'name' => '菜单', 'icon' => '', 'guard_name'=> 'admin' ], ]); } /** * @author moell */ private function associateRolePermissions() { $role = Role::first(); AdminUserFactory::adminUser()->first()->assignRole($role->name); foreach ($this->permissions as $permission) { $role->givePermissionTo($permission['name']); } } } ================================================ FILE: src/Http/Controllers/AdminUserController.php ================================================ adminUserModel = AdminUserFactory::adminUser(); } /** * @author moell * @param Request $request * @return AdminUserCollection */ public function index(Request $request) { return new AdminUserCollection($this->adminUserModel->where(request_intersect(['name', 'username']))->paginate()); } /** * @author moell * @param $id * @return AdminUserResource */ public function show($id) { return new AdminUserResource($this->adminUserModel->findOrFail($id)); } /** * @author moell * @param CreateOrUpdateRequest $request * @return Response */ public function store(CreateOrUpdateRequest $request) { $data = request_intersect([ 'name', 'username', 'password' ]); $data['status'] = $request->status ? true : false; $data['password'] = bcrypt($data['password']); $this->adminUserModel->create($data); return $this->created(); } /** * @author moell * @param CreateOrUpdateRequest $request * @param $id * @return Response */ public function update(CreateOrUpdateRequest $request, $id) { $adminUser = $this->adminUserModel->findOrFail($id); $data = $request->only([ 'name', 'status' ]); if ($request->filled('password')) { $data['password'] = bcrypt($request->password); } $adminUser->fill($data); $adminUser->save(); return $this->noContent(); } /** * @author moell * @param $id * @return Response */ public function destroy($id) { $adminUser = $this->adminUserModel->findOrFail($id); $adminUser->delete(); return $this->noContent(); } /** * @author moell * @param $id * @param $provider * @return RoleCollection */ public function roles($id, $provider) { $user = $this->getGuardModel($provider)->findOrFail($id); return new RoleCollection($user->roles); } /** * @param $id * @param $guard * @param Request $request * @return Response *@author moell */ public function assignRoles($id, $guard, Request $request) { $user = $this->getGuardModel($guard)->findOrFail($id); $user->syncRoles($request->input('roles', [])); return $this->noContent(); } /** * @param $guard * @return Illuminate\Foundation\Auth\User */ private function getGuardModel($guard) { return app(config('mojito.guards.' . $guard . '.model')); } } ================================================ FILE: src/Http/Controllers/CaptchaController.php ================================================ * @param CaptchaBuilder $captchaBuilder * @return \Illuminate\Http\JsonResponse */ public function generate(CaptchaBuilder $captchaBuilder) { $key = Str::uuid()->toString(); $captcha = $captchaBuilder->build(); $expiredAt = Carbon::now()->addMinutes(config("mojito.captcha_cache_ttl", 2)); Cache::put($key, ['code' => $captcha->getPhrase()], $expiredAt); return $this->success([ 'data' => [ 'key' => $key, 'expired_at' => $expiredAt->toDateTimeString(), 'image_content' => $captcha->inline() ] ]); } } ================================================ FILE: src/Http/Controllers/ChangePasswordController.php ================================================ old_password, $user->password)) { return $this->unprocesableEtity([ 'password' => 'Incorrect password' ]); } $user->password = bcrypt($request->password); $user->save(); return $this->noContent(); } } ================================================ FILE: src/Http/Controllers/Controller.php ================================================ guard); if (! $config) { return $this->forbidden("Undefined guard"); } $cacheCaptcha = Cache::get($request->captcha_key); if (! $cacheCaptcha) { return $this->forbidden('Verification code has expired'); } if (strtolower($cacheCaptcha['code']) != strtolower($request->captcha)) { return $this->forbidden('Please enter correct verify code'); } Cache::forget($request->captcha_key); $conditions = data_get($config, 'conditions', []); $user = app($config['model'])->where(function ($query) use ($config) { foreach ($config['login_fields'] as $field) { $query->orWhere($field, request()->get('username')); } return $query; })->when($conditions, function ($query) use ($conditions) { return $query->where($conditions); })->first(); if (! $user || ! Hash::check($request->password, $user->password)) { throw ValidationException::withMessages([ 'username' => ['The provided credentials are incorrect.'], ]); } PersonalAccessToken::query()->where("tokenable_type", $config['model']) ->where("name", $request->guard) ->where("tokenable_id", $user->id) ->delete(); return response()->json([ 'data' => [ 'token' => $user->createToken($request->guard)->plainTextToken, ] ]); } /** * logout * @return \Illuminate\Http\Response */ public function logout() { Auth::user()->currentAccessToken()->delete(); return $this->noContent(); } } ================================================ FILE: src/Http/Controllers/MenuController.php ================================================ * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function index(Request $request) { $menus = Menu::query() ->where('guard_name', $request->input('guard_name', 'admin')) ->orderBy('sequence', 'desc') ->get(); return response()->json(['data' => make_tree($menus->toArray())]); } /** * @author moell * @param CreateOrUpdateRequest $request * @return \Illuminate\Http\Response */ public function store(CreateOrUpdateRequest $request) { Menu::create($request->all()); return $this->created(); } /** * @author moell * @return \Illuminate\Http\JsonResponse */ public function my(Request $request) { $guardName = data_get(Auth::user()->currentAccessToken(), "name", "admin"); $userPermissions = Auth::user()->getAllPermissions()->pluck('name'); $menus = Menu::query() ->where('guard_name', $guardName) ->orderBy('sequence', 'desc') ->get() ->filter(function ($item) use ($userPermissions) { return !$item->permission_name || $userPermissions->contains($item->permission_name); }); return response()->json(['data' => make_tree($menus->toArray())]); } /** * @author moell * @param CreateOrUpdateRequest $request * @param $id * @return \Illuminate\Http\Response */ public function update(CreateOrUpdateRequest $request, $id) { $menu = Menu::query()->findOrFail($id); $menu->update($request->toArray()); return $this->noContent(); } /** * @author moell * @param $id * @return MenuResource */ public function show($id) { return new MenuResource(Menu::query()->findOrFail($id)); } /** * @author moell * @param $id * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response */ public function destroy($id) { $menu = Menu::query()->findOrFail($id); if (Menu::query()->where('parent_id', $menu->id)->count()) { return $this->unprocesableEtity([ 'parent_id' => 'Please delete the submenu first.' ]); } $menu->delete(); return $this->noContent(); } } ================================================ FILE: src/Http/Controllers/PermissionController.php ================================================ * @param Request $request * @return PermissionCollection */ public function index(Request $request) { $permissions =tap(Permission::latest(), function ($query) { $query->where(request_intersect([ 'name', 'guard_name', 'pg_id' ])); })->with('group')->paginate(); return new PermissionCollection($permissions); } /** * @author moell * @param $id * @return PermissionResource */ public function show($id) { return new PermissionResource(Permission::query()->findOrFail($id)); } /** * @author moell * @param CreateOrUpdateRequest $request * @return \Illuminate\Http\Response */ public function store(CreateOrUpdateRequest $request) { $attributes = $request->only([ 'pg_id', 'name', 'guard_name', 'display_name', 'icon', 'sequence', 'description' ]); $attributes['created_name'] = Auth::user()->name; Permission::create($attributes); return $this->created(); } /** * @author moell * @param CreateOrUpdateRequest $request * @param $id * @return \Illuminate\Http\Response */ public function update(CreateOrUpdateRequest $request, $id) { $permission = Permission::query()->findOrFail($id); $attributes = $request->only([ 'pg_id', 'name', 'guard_name', 'display_name', 'icon', 'sequence', 'description' ]); $attributes['updated_name'] = Auth::user()->name; $isset = Permission::query() ->where(['name' => $attributes['name'], 'guard_name' => $attributes['guard_name']]) ->where('id', '!=', $id) ->count(); if ($isset) { throw PermissionAlreadyExists::create($attributes['name'], $attributes['guard_name']); } $permission->update($attributes); return $this->noContent(); } /** * @author moell * @param $id * @return \Illuminate\Http\Response */ public function destroy($id) { permission::query()->findOrFail($id)->delete(); return $this->noContent(); } /** * @author moell * @return \Illuminate\Http\JsonResponse */ public function allUserPermission() { return response()->json(['data' => Auth::user()->getAllPermissions()->pluck('name')]); } } ================================================ FILE: src/Http/Controllers/PermissionGroupController.php ================================================ * @param Request $request * @return PermissionGroupCollection */ public function index(Request $request) { $permissionGroups = tap(PermissionGroup::latest(), function ($query) { $query->where(request_intersect(['name'])); })->paginate(); return new PermissionGroupCollection($permissionGroups); } /** * @author moell * @param Request $request * @return PermissionGroupCollection */ public function all(Request $request) { $permissionGroups = PermissionGroup::latest()->get(); return new PermissionGroupCollection($permissionGroups); } /** * @param $guardName * @return \Illuminate\Http\JsonResponse */ public function guardNameForPermissions($guardName) { $permissionGroups = PermissionGroup::query() ->with(['permission' => function ($query) use ($guardName) { $query->where('guard_name', $guardName); }]) ->get()->filter(function($item) { return count($item->permission) > 0; }); return response()->json([ 'data' => array_values($permissionGroups->toArray()) ]); } /** * @author moell * @param CreateOrUpdateRequest $request * @return \Illuminate\Http\Response */ public function store(CreateOrUpdateRequest $request) { PermissionGroup::create(request_intersect(['name'])); return $this->created(); } /** * @author moell * @param $id * @return PermissionGroupResource */ public function show($id) { return new PermissionGroupResource(PermissionGroup::findOrFail($id)); } /** * @author moell * @param CreateOrUpdateRequest $request * @param $id * @return \Illuminate\Http\Response */ public function update(CreateOrUpdateRequest $request, $id) { PermissionGroup::findOrFail($id)->update(request_intersect([ 'name' ])); return $this->noContent(); } /** * @param $id * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response */ public function destroy($id) { $permissionGroup = PermissionGroup::findOrFail($id); if (Permission::query()->where('pg_id', $permissionGroup->id)->count()) { return $this->unprocesableEtity([ 'pg_id' => 'Please move or delete the vesting permission.' ]); } $permissionGroup->delete(); return $this->noContent(); } } ================================================ FILE: src/Http/Controllers/RoleController.php ================================================ * @param Request $request * @return RoleCollection */ public function index(Request $request) { return new RoleCollection(Role::query()->where(request_intersect(['name']))->paginate()); } /** * @author moell * @param $guardName * @return RoleCollection */ public function guardNameRoles($guardName) { return new RoleCollection(Role::query()->where('guard_name', $guardName)->get()); } public function show($id) { return new RoleResource(Role::query()->findOrFail($id)); } /** * @author moell * @param CreateOrUpdateRequest $request * @return \Illuminate\Http\Response */ public function store(CreateOrUpdateRequest $request) { Role::create(request_intersect([ 'name', 'guard_name', 'description' ])); return $this->created(); } /** * @author moell * @param CreateOrUpdateRequest $request * @param $id * @return \Illuminate\Http\Response */ public function update(CreateOrUpdateRequest $request, $id) { if (Role::where(request_intersect(['name', 'guard_name']))->where('id', '!=', $id)->count()) { throw RoleAlreadyExists::create($request->name, $request->guard_name); } $role = Role::query()->findOrFail($id); $role->update(request_intersect([ 'name', 'guard_name', 'description' ])); return $this->noContent(); } /** * @author moell * @param $id * @return \Illuminate\Http\Response */ public function destroy($id) { Role::destroy($id); return $this->noContent(); } /** * @author moell * @param $id * @return PermissionCollection */ public function permissions($id) { $role = Role::query()->findOrFail($id); return new PermissionCollection($role->permissions); } /** * Assign permission * * @author moell * @param $id * @param Request $request * @return \Illuminate\Http\Response */ public function assignPermissions($id, Request $request) { $role = Role::query()->findOrFail($id); $role->syncPermissions($request->input('permissions', [])); return $this->noContent(); } } ================================================ FILE: src/Http/Middleware/Authenticate.php ================================================ * @param $request * @param \Closure $next * @return mixed */ public function handle($request, \Closure $next) { $permission = Route::currentRouteName(); if (Auth::user()->hasPermissionTo($permission)) { return $next($request); } throw UnauthorizedException::forPermissions([$permission]); } } ================================================ FILE: src/Http/MojitoResponse.php ================================================ * @param string $content * @return Response */ protected function created($content = '') { return new Response($content, Response::HTTP_CREATED); } /** * 202 * * @author moell * @return Response */ protected function accepted() { return new Response('', Response::HTTP_ACCEPTED); } /** * 204 * * @author moell * @return Response */ protected function noContent() { return new Response('', Response::HTTP_NO_CONTENT); } /** * 400 * * @author moell * @param $message * @param array $headers * @param int $options * @return \Illuminate\Http\JsonResponse */ protected function badRequest($message, array $headers = [], $options = 0) { return response()->json([ 'message' => $message ], Response::HTTP_BAD_REQUEST, $headers, $options); } /** * 401 * * @author moell * @param string $message * @param array $headers * @param int $options * @return \Illuminate\Http\JsonResponse */ protected function unauthorized($message = '', array $headers = [], $options = 0) { return response()->json([ 'message' => $message ? $message : 'Token Signature could not be verified.' ], Response::HTTP_UNAUTHORIZED, $headers, $options); } /** * 403 * * @author moell * @param string $message * @param array $headers * @param int $options * @return \Illuminate\Http\JsonResponse */ protected function forbidden($message = '', array $headers = [], $options = 0) { return response()->json([ 'message' => $message ? $message : 'Insufficient permissions.' ], Response::HTTP_FORBIDDEN, $headers, $options); } /** * 422 * * @author moell * @param array $errors * @param array $headers * @param string $message * @param int $options * @return \Illuminate\Http\JsonResponse */ protected function unprocesableEtity(array $errors = [], array $headers = [], $message = '', $options = 0) { return response()->json([ 'message' => $message ? $message : '422 Unprocessable Entity', 'errors' => $errors ], Response::HTTP_UNPROCESSABLE_ENTITY, $headers, $options); } /** * 200 * * @author moell * @param array $data * @param array $headers * @param int $options * @return \Illuminate\Http\JsonResponse */ protected function success(array $data, array $headers = [], $options = 0) { return response()->json($data, Response::HTTP_OK, $headers, $options); } } ================================================ FILE: src/Http/Requests/AdminUser/CreateOrUpdateRequest.php ================================================ * @return array */ public function rules() { $rules = [ 'name' => 'required|max:255' ]; switch ($this->method()) { case 'POST': $rules['password'] = 'required|min:6|max:32'; $rules['username'] = 'required|unique:' . AdminUserFactory::adminUser()->getTable(); break; case 'PATCH': $rules['password'] = 'nullable|min:8|max:32'; break; } return $rules; } } ================================================ FILE: src/Http/Requests/ChangePasswordRequest.php ================================================ * @return array */ public function rules() { return [ 'old_password' => 'required|min:6|max:32', 'password' => 'required|min:8|max:32|confirmed', 'password_confirmation' => 'required|min:8|max:32' ]; } } ================================================ FILE: src/Http/Requests/Menu/CreateOrUpdateRequest.php ================================================ * @return array */ public function rules() { return [ 'parent_id' => 'required|numeric', 'name' => 'required', 'guard_name' => 'required', 'is_link' => 'in:0,1', 'uri' => 'required' ]; } } ================================================ FILE: src/Http/Requests/Permission/CreateOrUpdateRequest.php ================================================ * @return array */ public function rules() { $rules = [ 'name' => 'required|max:255', 'guard_name' => 'required|max:255', 'display_name' => 'required:max:50', 'pg_id' => 'required|numeric', 'sequence' => 'numeric' ]; return $rules; } } ================================================ FILE: src/Http/Requests/PermissionGroup/CreateOrUpdateRequest.php ================================================ * @return array */ public function rules() { $rules = [ 'name' => 'required|max:255' ]; return $rules; } } ================================================ FILE: src/Http/Requests/Role/CreateOrUpdateRequest.php ================================================ * @return array */ public function rules() { $rules = [ 'name' => 'required|max:255', 'guard_name' => 'required|max:255' ]; return $rules; } } ================================================ FILE: src/Models/AdminUser.php ================================================ belongsTo(PermissionGroup::class, 'pg_id'); } } ================================================ FILE: src/Models/PermissionGroup.php ================================================ hasMany('Moell\Mojito\Models\Permission', 'pg_id'); } } ================================================ FILE: src/Models/User.php ================================================ guard_name; } } ================================================ FILE: src/Providers/MojitoServiceProvider.php ================================================ app->runningInConsole()) { $this->registerMigrations(); $this->commands([ InstallCommand::class, ]); $this->publishes([ __DIR__.'/../../config/mojito.php' => config_path('mojito.php'), ], 'config'); } $this->registerRouter(); } /** * Register any application services. * * @return void */ public function register() { // } private function registerMigrations() { $migrationsPath = __DIR__ . '/../../database/migrations/'; $items = [ 'create_admin_table.php', 'add_custom_field_permission_tables.php', 'create_menu_table.php', 'create_permission_group_table.php' ]; $paths = []; foreach ($items as $key => $name) { $paths[$migrationsPath . $name] = database_path('migrations') . "/". $this->formatTimestamp($key+1) . '_' . $name; } $this->publishes($paths, 'migrations'); } /** * @param $addition * @return false|string */ private function formatTimestamp($addition) { return date('Y_m_d_His', time() + $addition); } /** * 注册路由 * * @author moell */ private function registerRouter() { if (strpos($this->app->version(), 'Lumen') === false && !$this->app->routesAreCached()) { app('router')->middleware('api')->group(__DIR__.'/../routes.php'); } else { require __DIR__.'/../routes.php'; } } } ================================================ FILE: src/Resources/AdminUser.php ================================================ $this->id, 'name' => $this->name, 'username' => $this->username, 'status' => $this->status ? true : false, 'created_at' => (string)$this->created_at, 'updated_at' => (string)$this->updated_at ]; } } ================================================ FILE: src/Resources/AdminUserCollection.php ================================================ $this->collection ]; } } ================================================ FILE: src/Resources/Menu.php ================================================ $this->id, 'name' => $this->name, 'guard_name' => $this->guard_name, 'icon' => $this->icon, 'uri' => $this->uri, 'is_link' => $this->is_link, 'created_at' => (string)$this->created_at, 'updated_at' => (string)$this->updated_at ]; } } ================================================ FILE: src/Resources/Permission.php ================================================ $this->id, 'pg_id' => $this->pg_id, 'name' => $this->name, 'guard_name' => $this->guard_name, 'display_name' => $this->display_name, 'group' => new PermissionGroup($this->group), 'icon' => $this->icon, 'sequence' => $this->sequence, 'description' => $this->description, 'created_name' => $this->created_name, 'updated_name' => $this->updated_name, 'created_at' => (string)$this->created_at, 'updated_at' => (string)$this->created_at ]; } } ================================================ FILE: src/Resources/PermissionCollection.php ================================================ $this->collection ]; } } ================================================ FILE: src/Resources/PermissionGroup.php ================================================ $this->id, 'name' => $this->name, 'created_at' => (string)$this->created_at, 'updated_at' => (string)$this->updated_at ]; } } ================================================ FILE: src/Resources/PermissionGroupCollection.php ================================================ $this->collection ]; } } ================================================ FILE: src/Resources/Role.php ================================================ $this->id, 'name' => $this->name, 'guard_name' => $this->guard_name, 'description' => $this->description, 'created_at' => (string)$this->created_at, 'updated_at' => (string)$this->updated_at ]; } } ================================================ FILE: src/Resources/RoleCollection.php ================================================ $this->collection ]; } } ================================================ FILE: src/helpers.php ================================================ only(is_array($keys) ? $keys : func_get_args())); } } if (!function_exists('make_tree')) { /** * @param array $list * @param int $parentId * @return array */ function make_tree(array $list, $parentId = 0) { $tree = []; if (empty($list)) { return $tree; } $newList = []; foreach ($list as $k => $v) { $newList[$v['id']] = $v; } foreach ($newList as $value) { if ($parentId == $value['parent_id']) { $tree[] = &$newList[$value['id']]; } elseif (isset($newList[$value['parent_id']])) { $newList[$value['parent_id']]['children'][] = &$newList[$value['id']]; } } return $tree; } } ================================================ FILE: src/routes.php ================================================ namespace('\Moell\Mojito\Http\Controllers') ->prefix(config("mojito.route_prefix", "api")) ->middleware(config("mojito.middleware.basic", "api")) ->group(function ($router) { $router->post("auth/login", "LoginController@authenticate"); $router->get("/captcha", "CaptchaController@generate"); $router->middleware(config("mojito.middleware.auth", ['auth:sanctum']))->group(function ($router) { $router->post("auth/logout", "LoginController@logout")->name("auth.logout"); $router->get('permission-user-all', 'PermissionController@allUserPermission')->name("permission.all-user-permission"); $router->get('my-menu', 'MenuController@my')->name("menu.my"); $router->patch('user-change-password', 'ChangePasswordController@changePassword')->name("user.change-password"); }); $router->middleware(config("mojito.middleware.permission", ['auth:sanctum', 'mojito.permission'])) ->group(function ($router) { $router->apiResources([ 'role' => 'RoleController', 'permission' => 'PermissionController', 'admin-user' => 'AdminUserController', 'permission-group' => 'PermissionGroupController', 'menu' => 'MenuController', ]); $router->get('role/{id}/permissions', 'RoleController@permissions')->name('role.permissions'); $router->put('role/{id}/permissions', 'RoleController@assignPermissions')->name('role.assign-permissions'); $router->get('guard-name-roles/{guardName}', 'RoleController@guardNameRoles')->name('role.guard-name-roles'); $router->get('admin-user/{id}/roles/{guard}', 'AdminUserController@roles')->name('admin-user.roles'); $router->put('admin-user/{id}/roles/{guard}', 'AdminUserController@assignRoles')->name('admin-user.assign-roles'); $router->get('guard-name-for-permissions/{guardName}', 'PermissionGroupController@guardNameForPermissions') ->name('permission-group.guard-name-for-permission'); $router->get("permission-group-all", "PermissionGroupController@all")->name("permission-group.all"); }); }); ================================================ FILE: tests/Feature/AdminUserControllerTest.php ================================================ create(); $response = $this->get(route('admin-user.index')); $response->assertStatus(200); $data = [ 'id' => true, 'name' => true, 'username' => true ]; $response->assertJson($this->paginateResponseAssertFormat($data, AdminUser::count())); } public function test_admin_user_of_the_condition_to_be_filtered() { factory(AdminUser::class, 79)->create(); $response = $this->get(route('admin-user.index') . '/?name=admin&username=admin'); $response->assertStatus(200); $data = [ 'name' => 'admin', 'username' => 'admin' ]; $response->assertJson($this->paginateResponseAssertFormat($data, 1)); } public function test_store() { $data = [ 'name' => '111', 'username' => 'admintest', 'password' => '123446dd', 'status' => 1, ]; $response = $this->post(route('admin-user.store'), $data, $this->jsonHeader()); $response->assertStatus(201); $adminUser = AdminUser::where('username', $data['username'])->first(); $this->assertNotNull($adminUser); } public function test_show() { $adminUser = AdminUser::first(); $response = $this->get(route('admin-user.show', ['admin_user' => $adminUser->id])); $response->assertJson([ 'data' => [ 'id' => 1, 'name' => 'admin', 'username' => 'admin' ] ]); } public function test_update() { $adminUser = AdminUser::first(); $data = [ 'name' => 'admin_test' ]; $response = $this->patch(route('admin-user.update', ['admin_user' => $adminUser->id]), $data, $this->jsonHeader()); $response->assertStatus(204); $newAdminUser = AdminUser::first(); $this->assertEquals($data['name'], $newAdminUser->name); $this->assertEquals($adminUser->password, $newAdminUser->password); } public function test_destroy() { $adminUser = AdminUser::first(); $response = $this->delete(route('admin-user.destroy', ['admin_user' => $adminUser->id]), [], $this->jsonHeader()); $response->assertStatus(204); $this->assertCount(0, $adminUser->roles); $this->assertCount(0, $adminUser->permissions); } public function test_get_a_list_of_roles_based_on_ID() { $adminUser = AdminUser::first(); $route = route('admin-user.roles', ['id' => $adminUser->id, 'guard' => 'admin']); $response = $this->get($route, $this->jsonHeader()); $data = []; foreach ($adminUser->roles as $role) { array_push($data, ['name' => $role->name]); } $response->assertStatus(200) ->assertJson([ 'data' => $data ]); } public function test_user_assign_roles() { $adminUser = AdminUser::first(); $route = route('admin-user.roles', ['id' => $adminUser->id, 'guard' => 'admin']); $response = $this->put($route, ['roles' => []], $this->jsonHeader()); $response->assertStatus(204); $this->assertCount(0, $adminUser->roles); } } ================================================ FILE: tests/Feature/CaptchaControllerTest.php ================================================ get('/api/captcha', $this->jsonHeader()); $response->assertJson([ 'data' => [ 'key' => true, 'expired_at' => true, 'image_content' => true ] ]); } } ================================================ FILE: tests/Feature/ChangePasswordControllerTest.php ================================================ password = bcrypt('mojito-password'); $user->save(); $response = $this->patch(route('user.change-password'), [ 'old_password' => 'mojito-password', 'password' => $newPassword, 'password_confirmation' => $newPassword ]); $response->assertStatus(204); $user = AdminUserFactory::adminUser()->find($user->id); $this->assertTrue(Hash::check($newPassword, $user->password), $user->password); } } ================================================ FILE: tests/Feature/FeatureTestCase.php ================================================ artisan('db:seed', ['--class' => MojitoTableSeeder::class]); $user = AdminUserFactory::adminUser()->first(); Sanctum::actingAs( $user, ['*'] ); } /** * @param array $data * @param int $total * @param int $currentPage * @return array */ protected function paginateResponseAssertFormat(array $data, $total = 0, $currentPage = 1) { return [ 'data' => [ $data ], 'links' => [ "first" => true, "last" => true ], 'meta' => [ "current_page" => $currentPage > 1 ? $currentPage : true, "from" => true, "last_page" => true, "path" => true, "per_page" => true, "to" => true, "total" => $total > 0 ? $total : true ] ]; } /** * @return array */ protected function jsonHeader() { return [ 'Accept' => 'application/json' ]; } } ================================================ FILE: tests/Feature/MenuControllerTest.php ================================================ get(route('menu.index'), $this->jsonHeader()); $response ->assertStatus(200) ->assertJson([ 'data' => [ [ 'id' => 1, 'parent_id' => '0', 'name' => 'Dashboard', 'guard_name' => "admin" ], [ 'id' => 2, 'parent_id' => '0', 'name' => '系统管理', 'guard_name' => "admin", 'children' => [ [ 'id' => 3, 'parent_id' => '2', 'name' => '管理员', 'guard_name' => "admin" ] ] ] ] ]); } public function test_menu_after_user_login() { $response = $this->get(route('menu.my'), $this->jsonHeader()); $response ->assertStatus(200) ->assertJson([ 'data' => [ [ 'id' => 1, 'parent_id' => '0', 'name' => 'Dashboard', 'guard_name' => "admin" ], [ 'id' => 2, 'parent_id' => '0', 'name' => '系统管理', 'guard_name' => "admin", 'children' => [ [ 'id' => 3, 'parent_id' => '2', 'name' => '管理员', 'guard_name' => "admin" ] ] ] ] ]); } public function test_create_a_menu() { $data = [ 'parent_id' => 0, 'name' => 'home', 'icon' => 'fa fa-home', 'uri' => '/', 'is_link' => 1, 'guard_name' => 'admin', 'sequence' => 10 ]; $response = $this->post(route('menu.store'), $data, $this->jsonHeader()); $response->assertStatus(201); $menu = Menu::where('name', $data['name'])->where('guard_name', $data['guard_name'])->first()->toArray(); $this->assertArraySubset($data, $menu); } public function test_edit_a_menu() { $data = [ 'parent_id' => 0, 'name' => 'home', 'icon' => 'fa fa-home', 'uri' => '/', 'is_link' => 1, 'guard_name' => 'admin', 'sequence' => 0 ]; $menu = Menu::query()->where('parent_id', '>', 0)->first(); $response = $this->patch(route('menu.update', ['menu' => $menu->id]), $data, $this->jsonHeader()); $response->assertStatus(204); $this->assertArraySubset($data, Menu::query()->find($menu->id)->toArray()); } public function test_menu_id_for_details() { $menu = Menu::query()->first(); $response = $this->get(route('menu.show', ['menu' => $menu->id]), $this->jsonHeader()); $response ->assertStatus(200) ->assertJson([ 'data' => [ 'name' => $menu->name, 'guard_name' => $menu->guard_name ] ]); } public function test_menu_id_for_destroy() { $menu = Menu::query()->first(); $childMenu = Menu::create([ 'name' => 'test', 'guard_name' => 'test', 'parent_id' => $menu->id ]); $response = $this->delete(route('menu.destroy', ['menu' => $menu->id]), $this->jsonHeader()); $response->assertStatus(422); $childResponse = $this->delete(route('menu.destroy', ['menu' => $childMenu->id]), $this->jsonHeader()); $childResponse->assertStatus(204); } } ================================================ FILE: tests/Feature/PermissionControllerTest.php ================================================ get(route('permission.index') . '?name=admin-user.index', $this->jsonHeader()); $data = [ 'name' => 'admin-user.index' ]; $response ->assertStatus(200) ->assertJson($this->paginateResponseAssertFormat($data, 1)); } public function test_create_a_permission() { $data = [ 'pg_id' => 1, 'name' => 'permission.test', 'guard_name' => 'admin', 'display_name' => 'test', 'icon' => 'fa fa-edit', 'sequence' => '1', 'description' => 'description' ]; $response = $this->post(route('permission.store'), $data, $this->jsonHeader()); $response->assertStatus(201); $permission = Permission::query() ->where('name', $data['name']) ->where('guard_name', $data['guard_name']) ->first(); $this->assertNotNull($permission); } public function test_permission_id_for_details() { $permission = Permission::query()->first(['id', 'name', 'guard_name', 'display_name', 'icon', 'sequence', 'description']); $response = $this->get(route('permission.show', ['permission' => $permission->id]), $this->jsonHeader()); $response ->assertStatus(200) ->assertJson([ 'data' => $permission->toArray() ]); } public function test_update_a_permission() { $data = [ 'pg_id' => 1, 'name' => 'permission.test', 'guard_name' => 'admin', 'display_name' => 'test', 'icon' => 'fa fa-edit', 'sequence' => '1', 'description' => 'description' ]; $permission = Permission::query()->first(); $response = $this->patch( route('permission.update', ['permission' => $permission->id]), $data, $this->jsonHeader() ); $response->assertStatus(204); $this->assertArraySubset($data, Permission::query()->find($permission->id)->toArray()); } public function test_delete_the_specified_ID_permission() { $permission = Permission::query()->first(); $response = $this->delete( route('permission.destroy', ['permission' => $permission->id]), $this->jsonHeader() ); $response->assertStatus(204); $this->assertNull(Permission::query()->find($permission->id)); } public function test_user_all_permission() { $response = $this->get(route('permission.all-user-permission'), $this->jsonHeader()); $response->assertStatus(200); } } ================================================ FILE: tests/Feature/PermissionGroupControllerTest.php ================================================ get(route('permission-group.index'), $this->jsonHeader()); $response ->assertStatus(200) ->assertJson($this->paginateResponseAssertFormat([ 'name' => true ])); } public function test_get_permission_group_all() { $response = $this->get(route('permission-group.all'), $this->jsonHeader()); $response ->assertStatus(200) ->assertJson([ 'data' => [ [ 'id' => true, 'name' => true ] ] ]); } public function test_get_guard_name_group_permissions() { $response = $this->get(route('permission-group.guard-name-for-permission', ['guardName' => 'admin']), $this->jsonHeader()); $response ->assertStatus(200) ->assertJson([ 'data' => [ [ 'id' => true, 'name' => true, 'permission' => true ] ] ]); } public function test_create_a_permission_group() { $data = ['name' => 'test permission group']; $response = $this->post(route('permission-group.store'), $data, $this->jsonHeader()); $response->assertStatus(201); $this->assertNotNull(PermissionGroup::query()->where('name', $data['name'])->first()); } public function test_permission_group_id_for_details() { $permissionGroup = PermissionGroup::query()->first(); $response = $this->get( route('permission-group.show', ['permission_group' => $permissionGroup->id]), $this->jsonHeader() ); $response ->assertStatus(200) ->assertJson(['data' => [ 'name' => $permissionGroup->name ]]); } public function test_update_a_permission_group() { $data = ['name' => 'test permission group']; $permissionGroup = PermissionGroup::query()->first(); $response = $this->patch( route('permission-group.update', ['permission_group' => $permissionGroup->id]), $data, $this->jsonHeader() ); $response->assertStatus(204); $new = PermissionGroup::query()->find($permissionGroup->id); $this->assertEquals($new->name, $data['name']); } public function test_delete_the_specified_ID_permission_group() { $permissionGroup = PermissionGroup::query()->first(); $response = $this->delete(route('permission-group.destroy', ['permission_group' => $permissionGroup->id])); $response->assertStatus(422); $new = PermissionGroup::create([ 'name' => 'test' ]); $newResponse = $this->delete(route('permission-group.destroy', ['permission_group' => $new->id])); $newResponse->assertStatus(204); $this->assertNull(PermissionGroup::query()->find($new->id)); } } ================================================ FILE: tests/Feature/RoleControllerTest.php ================================================ get(route('role.index') . '?name=admin', $this->jsonHeader()); $response ->assertStatus(200) ->assertJson($this->paginateResponseAssertFormat([ 'name' => 'admin' ])); } public function test_create_a_role() { $data = [ 'name' => 'test', 'guard_name' => 'test', 'description' => 'test description' ]; $response = $this->post(route('role.store'), $data, $this->jsonHeader()); $response->assertStatus(201); } public function test_edit_a_role() { $role = Role::query()->first(); $data = [ 'name' => 'test', 'guard_name' => 'test' ]; $response = $this->patch(route('role.update', ['role' => $role->id]), $data, $this->jsonHeader()); $response->assertStatus(204); $role = Role::query()->first(); $this->assertEquals($data['name'], $role->name); $this->assertEquals($data['guard_name'], $role->guard_name); } public function test_role_assign_permission() { $role = Role::query()->first(); $response = $this->put(route('role.assign-permissions', ['id' => $role->id]), ['permissions' => []], $this->jsonHeader()); $response->assertStatus(204); $this->assertCount(0, $role->permissions); } public function test_guard_name_for_roels() { $response = $this->get(route('role.guard-name-roles', ['guardName' => 'admin']), $this->jsonHeader()); $response->assertStatus(200)->assertJson([ 'data' => [ ['guard_name' => 'admin'] ] ]); } public function test_get_role_permissions() { $role = Role::query()->first(); $response = $this->get(route('role.permissions', ['id' => $role->id]), $this->jsonHeader()); $count = $role->permissions()->orderBy('id')->count(); $response->assertStatus(200); $this->assertCount($count, json_decode($response->getContent())->data); } public function test_role_id_for_details() { $role = Role::query()->first(); $response = $this->get(route('role.show', ['role' => $role->id]), $this->jsonHeader()); $response ->assertStatus(200) ->assertJson([ 'data' => [ 'name' => $role->name, 'guard_name' => $role->guard_name ] ]); } public function test_role_id_for_destroy() { $role = Role::create(['name' => 'test', 'guard_name' => 'test']); $response = $this->delete(route('role.destroy', ['role' => $role->id]), $this->jsonHeader()); $response->assertStatus(204); $this->assertNull(Role::query()->find($role->id)); } } ================================================ FILE: tests/Fixtures/Http/Kernel.php ================================================ \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \Orchestra\Testbench\Http\Middleware\RedirectIfAuthenticated::class, 'mojito.permission' => \Moell\Mojito\Http\Middleware\Authenticate::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ]; protected $middlewareGroups = [ 'api' => [ 'throttle:60,1', \Illuminate\Routing\Middleware\SubstituteBindings::class, EnsureFrontendRequestsAreStateful::class, ], ]; } ================================================ FILE: tests/Fixtures/database/factories/AdminUserFactory.php ================================================ define(\Moell\Mojito\Models\AdminUser::class, function (Faker $faker) { return [ 'name' => $faker->name, 'username' => $faker->unique()->userName, 'status' => 1, 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret ]; }); ================================================ FILE: tests/Fixtures/database/migrations/0000_00_00_000001_create_permission_test_tables.php ================================================ increments('id'); $table->string('name'); $table->string('guard_name'); $table->timestamps(); }); Schema::create($tableNames['roles'], function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('guard_name'); $table->timestamps(); }); Schema::create($tableNames['model_has_permissions'], function (Blueprint $table) use ($tableNames) { $table->unsignedInteger('permission_id'); $table->morphs('model'); $table->foreign('permission_id') ->references('id') ->on($tableNames['permissions']) ->onDelete('cascade'); $table->primary(['permission_id', 'model_id', 'model_type'], 'model_has_permissions_permission_model_type_primary'); }); Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames) { $table->unsignedInteger('role_id'); $table->morphs('model'); $table->foreign('role_id') ->references('id') ->on($tableNames['roles']) ->onDelete('cascade'); $table->primary(['role_id', 'model_id', 'model_type']); }); Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames) { $table->unsignedInteger('permission_id'); $table->unsignedInteger('role_id'); $table->foreign('permission_id') ->references('id') ->on($tableNames['permissions']) ->onDelete('cascade'); $table->foreign('role_id') ->references('id') ->on($tableNames['roles']) ->onDelete('cascade'); $table->primary(['permission_id', 'role_id']); app('cache')->forget('spatie.permission.cache'); }); } /** * Reverse the migrations. * * @return void */ public function down() { $tableNames = config('permission.table_names'); Schema::drop($tableNames['role_has_permissions']); Schema::drop($tableNames['model_has_roles']); Schema::drop($tableNames['model_has_permissions']); Schema::drop($tableNames['roles']); Schema::drop($tableNames['permissions']); } } ================================================ FILE: tests/Fixtures/database/migrations/0000_00_00_000002_add_custom_field_permission_test_tables.php ================================================ integer('pg_id')->default(0); $table->string('display_name', 50)->nullable(); $table->string('icon', 30)->nullable(); $table->smallInteger('sequence')->default(0); $table->string('created_name', 50)->nullable(); $table->string('updated_name', 50)->nullable(); $table->string('description')->nullable(); }); Schema::table($tableNames['roles'], function (Blueprint $table) { $table->string('description')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { $tableNames = config('permission.table_names'); Schema::table($tableNames['permissions'], function (Blueprint $table) { $table->dropColumn([ 'pg_id', 'display_name', 'icon', 'sequence', 'created_name', 'updated_name', 'description' ]); }); Schema::table($tableNames['roles'], function (Blueprint $table) { $table->dropColumn('description'); }); } } ================================================ FILE: tests/Fixtures/database/migrations/0000_00_00_000003_create_admin_test_table.php ================================================ increments('id'); $table->string('name'); $table->string('username')->unique(); $table->string('password'); $table->boolean("status"); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('admin_users'); } } ================================================ FILE: tests/Fixtures/database/migrations/0000_00_00_000004_create_permission_group_test_table.php ================================================ increments('id'); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('permission_groups'); } } ================================================ FILE: tests/Fixtures/database/migrations/0000_00_00_000005_create_menu_test_table.php ================================================ increments('id'); $table->integer('parent_id')->default(0); $table->string('icon', 50)->nullable(); $table->string('uri')->nullable(); $table->tinyInteger('is_link')->nullable()->comment('0-no;1-yes'); $table->string('permission_name', 50)->nullable(); $table->string('name'); $table->string('guard_name', 30); $table->smallInteger('sequence')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('menus'); } } ================================================ FILE: tests/TestCase.php ================================================ artisan('migrate', ['--database' => 'mojito']); $this->loadMigrationsFrom(__DIR__ . '/Fixtures/database/migrations'); $this->withFactories(__DIR__ . '/Fixtures/database/factories'); } protected function getEnvironmentSetUp($app) { $app['config']->set('database.default', 'mojito'); $app['config']->set('database.connections.mojito', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); $this->setMojitoConfigs(); $this->setPermissionConfigs(); } protected function getPackageProviders($app) { return [ PermissionServiceProvider::class, MojitoServiceProvider::class, SanctumServiceProvider::class ]; } protected function resolveApplicationHttpKernel($app) { $app->singleton('Illuminate\Contracts\Http\Kernel', Kernel::class); } protected function setMojitoConfigs() { config(['mojito' => include __DIR__ . '/../config/mojito.php']); } protected function setPermissionConfigs() { config(['permission' => [ 'models' => [ 'permission' => Permission::class, 'role' => Role::class, ], 'table_names' => [ 'roles' => 'roles', 'permissions' => 'permissions', 'model_has_permissions' => 'model_has_permissions', 'model_has_roles' => 'model_has_roles', 'role_has_permissions' => 'role_has_permissions', ], 'cache_expiration_time' => 60 * 24, 'display_permission_in_exception' => false, ]]); } } ================================================ FILE: tests/Unit/AdminUserFactoryTest.php ================================================ setUpTheTestEnvironment(); } public function test_if_it_is_admin_user() { $model = AdminUserFactory::adminUser(); $this->assertInstanceOf(AdminUser::class, $model); } } ================================================ FILE: tests/Unit/Requests/AdminUserCreateOrUpdateRequestTest.php ================================================ setMethod('POST'); $attributes = [ 'name' => 'test', 'username' => 'test111', 'password' => '12345544' ]; $validator = Validator::make($attributes, $request->rules()); $this->assertEquals(false, $validator->fails()); } public function test_update_form_request() { $request = new CreateOrUpdateRequest(); $request->setMethod('PATCH'); $attributes = [ 'name' => 'test', 'password' => '123455' ]; $validator = Validator::make($attributes, $request->rules()); $this->assertEquals(true, $validator->fails()); $this->assertArrayHasKey('password', $validator->errors()->toArray()); } } ================================================ FILE: tests/Unit/Requests/ChangePasswordRequestTest.php ================================================ setMethod('PATCH'); $attributes = [ 'old_password' => 'testtest', 'password' => 'test1esss', 'password_confirmation' => 'test1esss' ]; $validator = Validator::make($attributes, $request->rules()); $this->assertEquals(false, $validator->fails()); } } ================================================ FILE: tests/Unit/Requests/MenuCreateOrUpdateRequestTest.php ================================================ 0, 'name' => 'home', 'icon' => 'fa fa-home', 'uri' => '/', 'is_link' => 1, 'guard_name' => 'admin' ]; $validator = Validator::make($attributes, $request->rules()); $this->assertEquals(false, $validator->fails()); $validator = Validator::make([], $request->rules()); $errors = $validator->errors()->toArray(); $keys = ['parent_id', 'name', 'guard_name', 'uri']; foreach ($keys as $key) { $this->assertArrayHasKey($key, $errors); } } } ================================================ FILE: tests/Unit/Requests/PermissionCreateOrUpdateRequestTest.php ================================================ 1, 'name' => 'permission.test', 'guard_name' => 'admin', 'display_name' => 'test', 'icon' => 'fa fa-edit', 'sequence' => '1', 'description' => 'description' ]; $validator = Validator::make($attributes, $request->rules()); $this->assertEquals(false, $validator->fails()); $validator = Validator::make([], $request->rules()); $this->assertEquals(true, $validator->fails()); $keys = [ 'name', 'guard_name', 'display_name', 'pg_id' ]; foreach ($keys as $key) { $this->assertArrayHasKey($key, $validator->errors()->toArray()); } } } ================================================ FILE: tests/Unit/Requests/PermissionGroupCreateOrUpdateRequestTest.php ================================================ 'name' ]; $validator = Validator::make($attributes, $request->rules()); $this->assertEquals(false, $validator->fails()); $validator = Validator::make([], $request->rules()); $this->assertEquals(true, $validator->fails()); } } ================================================ FILE: tests/Unit/Requests/RoleCreateOrUpdateRequestTest.php ================================================ 'name' ]; $validator = Validator::make($attributes, $request->rules()); $this->assertEquals(true, $validator->fails()); $failAttributes = [ 'name' => 'name', 'guard_name' => 'guard_name' ]; $validator = Validator::make($failAttributes, $request->rules()); $this->assertEquals(false, $validator->fails()); } } ================================================ FILE: tests/Unit/ResponseTest.php ================================================ setUpTheTestEnvironment(); } public function test_http_ok() { $data = ['name' => 'moell']; $response = $this->success($data); $this->assertEquals($response->getStatusCode(), 200); $this->assertJsonStringEqualsJsonString(json_encode($data), $response->getContent()); } public function test_http_created() { $response = $this->created(); $this->assertEquals($response->getStatusCode(), 201); } public function test_http_accepted() { $response = $this->accepted(); $this->assertEquals($response->getStatusCode(), 202); } public function test_http_not_content() { $response = $this->noContent(); $this->assertEquals($response->getStatusCode(), 204); } public function test_http_bad_request() { $response = $this->badRequest('error'); $this->assertEquals($response->getStatusCode(), 400); $this->assertJsonStringEqualsJsonString(json_encode(['message' => 'error']), $response->getContent()); } public function test_http_unauthorized() { $response = $this->unauthorized('unauthorized'); $this->assertEquals($response->getStatusCode(), 401); $this->assertJsonStringEqualsJsonString(json_encode(['message' => 'unauthorized']), $response->getContent()); } public function test_http_forbidden() { $response = $this->forbidden('forbidden'); $this->assertEquals($response->getStatusCode(), 403); $this->assertJsonStringEqualsJsonString(json_encode(['message' => 'forbidden']), $response->getContent()); } public function test_http_unprocesable_etity() { $response = $this->unprocesableEtity(); $this->assertEquals($response->getStatusCode(), 422); } } ================================================ FILE: tests/Unit/ServiceProviderTest.php ================================================ setUpTheTestEnvironment(); } public function test_if_the_service_provider_was_loaded() { $providers = $this->app->getLoadedProviders(); $this->assertArrayHasKey(PermissionServiceProvider::class, $providers); $this->assertArrayHasKey(MojitoServiceProvider::class, $providers); $this->assertArrayHasKey(SanctumServiceProvider::class, $providers); } }