added role based user management

added send reset link method
updated jwt expire to one week
added seeder
This commit is contained in:
jack
2018-04-26 17:18:53 +08:00
parent a16a9350cd
commit b4c257b2d0
17 changed files with 794 additions and 34 deletions
+27 -27
View File
@@ -4,9 +4,11 @@ use Illuminate\Http\Request;
use App\User;
use App\UserVerification;
use JWTAuth;
use Auth;
use Aloha\Twilio\Twilio;
use Tymon\JWTAuth\Exceptions\JWTException;
use Validator, DB, Hash, Mail, Illuminate\Support\Facades\Password;
use Illuminate\Auth\Passwords\TokenRepositoryInterface;
class AuthController extends Controller
{
@@ -95,33 +97,28 @@ class AuthController extends Controller
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function register(Request $request)
public function updateUser(Request $request)
{
$credentials = $request->only('role', 'name', 'password', 'confirm_password');
$credentials = $request->only('role', 'name', 'password', 'password_confirmation');
$rules = [
'name' => 'required|max:255',
'phone' => 'required|digits:10|unique:users',
'role' => 'required',
'password' => 'required|confirmed|min:6'
];
$validator = Validator::make($credentials, $rules);
if($validator->fails()) {
return response()->json(['success'=> false, 'error'=> $validator->messages()]);
}
$name = $request->name;
$phone = "+6" . $request->phone;
$password = $request->password;
$user = User::create(['name' => $name, 'phone' => $phone, 'password' => Hash::make($password)]);
$verification_code = rand (0000,9999); //Generate verification code
DB::table('user_verifications')->insert(['user_id'=>$user->id,'token'=>$verification_code]);
// send SMS
$message = "IZYIM verification code : 12332";
$twilio = new Twilio(env('TWILIO_ACC'), env('TWILIO_TOKEN'), env('TWILIO_NUMBER'));
$twilio->message($phone, $message);
$user = Auth::user();
$user->update(['name' => $name, 'password' => Hash::make($password)]);
return response()->json(['success'=> true, 'message'=> 'A verification code has been send to your mobile number.']);
return response()->json(['success'=> true, 'message'=> 'Profile updated.']);
}
@@ -186,22 +183,25 @@ class AuthController extends Controller
*/
public function recover(Request $request)
{
$user = User::where('email', $request->email)->first();
if (!$user) {
$error_message = "Your email address was not found.";
return response()->json(['success' => false, 'error' => ['email'=> $error_message]], 401);
}
try {
Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject('Your Password Reset Link');
});
} catch (\Exception $e) {
//Return with error
$error_message = $e->getMessage();
return response()->json(['success' => false, 'error' => $error_message], 401);
$user = User::where('phone', $request->phone)->first();
if ($user){
$token = str_random(64);
DB::table(config('auth.passwords.users.table'))->insert([
'phone' => $user->phone,
'token' => $token
]);
}
/*
todo
send SMS
*/
return response()->json([
'success' => true, 'data'=> ['message'=> 'A reset email has been sent! Please check your email.']
'success' => true, 'data'=> ['message'=> 'A reset link has been send to your mobile phone.']
]);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace App;
use Laratrust\Models\LaratrustPermission;
class Permission extends LaratrustPermission
{
//
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace App;
use Laratrust\Models\LaratrustRole;
class Role extends LaratrustRole
{
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace App;
use Laratrust\Models\LaratrustTeam;
class Team extends LaratrustTeam
{
}
+2
View File
@@ -5,9 +5,11 @@ namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laratrust\Traits\LaratrustUserTrait;
class User extends Authenticatable implements JWTSubject
{
use LaratrustUserTrait;
use Notifiable;
/**
+1
View File
@@ -11,6 +11,7 @@
"fideloper/proxy": "^4.0",
"laravel/framework": "5.6.*",
"laravel/tinker": "^1.0",
"santigarcor/laratrust": "5.0.*",
"tymon/jwt-auth": "1.0.*",
"zizaco/entrust": "5.2.x-dev"
},
Generated
+186 -2
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"content-hash": "79f35763f56d5e27e88c843097cba288",
"content-hash": "cede893a42c764bea70b46adc91247ad",
"packages": [
{
"name": "aloha/twilio",
@@ -874,6 +874,51 @@
],
"time": "2015-04-20T18:58:01+00:00"
},
{
"name": "kkszymanowski/traitor",
"version": "0.2.5",
"source": {
"type": "git",
"url": "https://github.com/KKSzymanowski/Traitor.git",
"reference": "9770fc7de72ff585601dc9c42b31715d9fc40a24"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/KKSzymanowski/Traitor/zipball/9770fc7de72ff585601dc9c42b31715d9fc40a24",
"reference": "9770fc7de72ff585601dc9c42b31715d9fc40a24",
"shasum": ""
},
"require": {
"nikic/php-parser": "^1.0|^2.0|^3.0|^4.0",
"php": ">=5.4"
},
"require-dev": {
"phpunit/phpunit": "~4.1"
},
"type": "library",
"autoload": {
"psr-4": {
"Traitor\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Kuba Szymanowski",
"email": "kuba.szymanowski@inf24.pl"
}
],
"description": "Add a trait use statement to existing PHP class",
"keywords": [
"add",
"php",
"trait"
],
"time": "2018-04-19T12:24:36+00:00"
},
{
"name": "laravel/framework",
"version": "v5.6.17",
@@ -1807,6 +1852,75 @@
],
"time": "2018-01-20T00:28:24+00:00"
},
{
"name": "santigarcor/laratrust",
"version": "5.0.9",
"source": {
"type": "git",
"url": "https://github.com/santigarcor/laratrust.git",
"reference": "526cc3e8970c35b97c71a7a6d8b63c2073568bb1"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/santigarcor/laratrust/zipball/526cc3e8970c35b97c71a7a6d8b63c2073568bb1",
"reference": "526cc3e8970c35b97c71a7a6d8b63c2073568bb1",
"shasum": ""
},
"require": {
"illuminate/auth": "~5.2",
"illuminate/cache": "~5.2",
"illuminate/console": "~5.2",
"illuminate/database": "^5.2.32",
"illuminate/support": "~5.2",
"kkszymanowski/traitor": "^0.2.0",
"php": ">=5.5.9"
},
"require-dev": {
"mockery/mockery": ">=0.9.9",
"orchestra/testbench": "~3.2",
"phpunit/phpunit": ">=4.1"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Laratrust\\LaratrustServiceProvider"
],
"aliases": {
"Laratrust": "Laratrust\\LaratrustFacade"
}
}
},
"autoload": {
"psr-4": {
"Laratrust\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Santiago Garcia",
"homepage": "http://santigarcor.me"
}
],
"description": "This package provides a flexible way to add Role-based Permissions to Laravel",
"keywords": [
"Teams",
"acl",
"authorization",
"laratrust",
"laravel",
"multiusers",
"permissions",
"php",
"rbac",
"roles"
],
"time": "2018-03-05T13:21:52+00:00"
},
{
"name": "swiftmailer/swiftmailer",
"version": "v6.0.2",
@@ -2993,6 +3107,74 @@
"environment"
],
"time": "2016-09-01T10:05:43+00:00"
},
{
"name": "zizaco/entrust",
"version": "5.2.x-dev",
"source": {
"type": "git",
"url": "https://github.com/Zizaco/entrust.git",
"reference": "3623cc052937d9e62543402b50f24065720d44b9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Zizaco/entrust/zipball/3623cc052937d9e62543402b50f24065720d44b9",
"reference": "3623cc052937d9e62543402b50f24065720d44b9",
"shasum": ""
},
"require": {
"illuminate/cache": "~5.0",
"illuminate/console": "~5.0",
"illuminate/support": "~5.0",
"php": ">=5.5.0"
},
"require-dev": {
"illuminate/database": "~5.0",
"mockery/mockery": "dev-master",
"phpunit/phpunit": "~4.1",
"sami/sami": "dev-master"
},
"type": "library",
"autoload": {
"classmap": [
"src/commands"
],
"psr-4": {
"Zizaco\\Entrust\\": "src/Entrust/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Andrew Elkins",
"homepage": "http://andrewelkins.com"
},
{
"name": "Zizaco Zizuini",
"email": "zizaco@gmail.com"
},
{
"name": "Ben Batschelet",
"homepage": "http://github.com/bbatsche"
},
{
"name": "Michele Angioni",
"email": "michele.angioni@gmail.com"
}
],
"description": "This package provides a flexible way to add Role-based Permissions to Laravel",
"keywords": [
"acl",
"auth",
"illuminate",
"laravel",
"permission",
"roles"
],
"time": "2016-12-29T06:25:06+00:00"
}
],
"packages-dev": [
@@ -4739,7 +4921,9 @@
],
"aliases": [],
"minimum-stability": "dev",
"stability-flags": [],
"stability-flags": {
"zizaco/entrust": 20
},
"prefer-stable": true,
"prefer-lowest": false,
"platform": {
+3 -3
View File
@@ -151,7 +151,7 @@ return [
*/
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
Aloha\Twilio\Support\Laravel\ServiceProvider::class,
Zizaco\Entrust\EntrustServiceProvider::class,
Laratrust\LaratrustServiceProvider::class,
/*
* Application Service Providers...
@@ -213,8 +213,8 @@ return [
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
'Twilio' => Aloha\Twilio\Support\Laravel\Facade::class,
'Entrust' => Zizaco\Entrust\EntrustFacade::class,
'Laratrust' => Laratrust\LaratrustFacade::class,
'auth.password.broker' => Illuminate\Auth\Passwords\TokenRepositoryInterface::class
],
];
+1 -1
View File
@@ -100,7 +100,7 @@ return [
|
*/
'ttl' => env('JWT_TTL', 60),
'ttl' => env('JWT_TTL', 20160), // one week
/*
|--------------------------------------------------------------------------
+210
View File
@@ -0,0 +1,210 @@
<?php
/**
* This file is part of Laratrust,
* a role & permission management solution for Laravel.
*
* @license MIT
* @package Laratrust
*/
return [
/*
|--------------------------------------------------------------------------
| Use MorphMap in relationships between models
|--------------------------------------------------------------------------
|
| If true, the morphMap feature is going to be used. The array values that
| are going to be used are the ones inside the 'user_models' array.
|
*/
'use_morph_map' => false,
/*
|--------------------------------------------------------------------------
| Use cache in the package
|--------------------------------------------------------------------------
|
| Defines if Laratrust will use Laravel's Cache to cache the roles and permissions.
|
*/
'use_cache' => true,
/*
|--------------------------------------------------------------------------
| Use teams feature in the package
|--------------------------------------------------------------------------
|
| Defines if Laratrust will use the teams feature.
| Please check the docs to see what you need to do in case you have the package already configured.
|
*/
'use_teams' => true,
/*
|--------------------------------------------------------------------------
| Strict check for roles/permissions inside teams
|--------------------------------------------------------------------------
|
| Determines if a strict check should be done when checking if a role or permission
| is attached inside a team.
| If it's false, when checking a role/permission without specifying the team,
| it will check only if the user has attached that role/permission ignoring the team.
|
*/
'teams_strict_check' => false,
/*
|--------------------------------------------------------------------------
| Laratrust User Models
|--------------------------------------------------------------------------
|
| This is the array that contains the information of the user models.
| This information is used in the add-trait command, and for the roles and
| permissions relationships with the possible user models.
|
| The key in the array is the name of the relationship inside the roles and permissions.
|
*/
'user_models' => [
'users' => 'App\User',
],
/*
|--------------------------------------------------------------------------
| Laratrust Models
|--------------------------------------------------------------------------
|
| These are the models used by Laratrust to define the roles, permissions and teams.
| If you want the Laratrust models to be in a different namespace or
| to have a different name, you can do it here.
|
*/
'models' => [
/**
* Role model
*/
'role' => 'App\Role',
/**
* Permission model
*/
'permission' => 'App\Permission',
/**
* Team model
*/
'team' => 'App\Team',
],
/*
|--------------------------------------------------------------------------
| Laratrust Tables
|--------------------------------------------------------------------------
|
| These are the tables used by Laratrust to store all the authorization data.
|
*/
'tables' => [
/**
* Roles table.
*/
'roles' => 'roles',
/**
* Permissions table.
*/
'permissions' => 'permissions',
/**
* Teams table.
*/
'teams' => 'teams',
/**
* Role - User intermediate table.
*/
'role_user' => 'role_user',
/**
* Permission - User intermediate table.
*/
'permission_user' => 'permission_user',
/**
* Permission - Role intermediate table.
*/
'permission_role' => 'permission_role',
],
/*
|--------------------------------------------------------------------------
| Laratrust Foreign Keys
|--------------------------------------------------------------------------
|
| These are the foreign keys used by laratrust in the intermediate tables.
|
*/
'foreign_keys' => [
/**
* User foreign key on Laratrust's role_user and permission_user tables.
*/
'user' => 'user_id',
/**
* Role foreign key on Laratrust's role_user and permission_role tables.
*/
'role' => 'role_id',
/**
* Role foreign key on Laratrust's permission_user and permission_role tables.
*/
'permission' => 'permission_id',
/**
* Role foreign key on Laratrust's role_user and permission_user tables.
*/
'team' => 'team_id',
],
/*
|--------------------------------------------------------------------------
| Laratrust Middleware
|--------------------------------------------------------------------------
|
| This configuration helps to customize the Laratrust middleware behavior.
|
*/
'middleware' => [
/**
* Define if the laratrust middleware are registered automatically in the service provider
*/
'register' => true,
/**
* Method to be called in the middleware return case.
* Available: abort|redirect
*/
'handling' => 'abort',
/**
* Parameter passed to the middleware_handling method
*/
'params' => '403',
],
/*
|--------------------------------------------------------------------------
| Laratrust Magic 'can' Method
|--------------------------------------------------------------------------
|
| Supported cases for the magic can method (Refer to the docs).
| Available: camel_case|snake_case|kebab_case
|
*/
'magic_can_method_case' => 'kebab_case',
];
+29
View File
@@ -0,0 +1,29 @@
<?php
return [
'role_structure' => [
'administrator' => [
'users' => 'c,r,u,d',
'acl' => 'c,r,u,d',
'profile' => 'r,u'
],
'freightforwarder' => [
'users' => 'c,r,u,d',
'profile' => 'r,u'
],
'importer' => [
'profile' => 'r,u'
],
],
'permission_structure' => [
'cru_user' => [
'profile' => 'c,r,u'
],
],
'permissions_map' => [
'c' => 'create',
'r' => 'read',
'u' => 'update',
'd' => 'delete'
]
];
@@ -0,0 +1,83 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class LaratrustSetupTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Create table for storing roles
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('display_name')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
// Create table for storing permissions
Schema::create('permissions', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('display_name')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
// Create table for associating roles to users and teams (Many To Many Polymorphic)
Schema::create('role_user', function (Blueprint $table) {
$table->unsignedInteger('role_id');
$table->unsignedInteger('user_id');
$table->string('user_type');
$table->foreign('role_id')->references('id')->on('roles')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['user_id', 'role_id', 'user_type']);
});
// Create table for associating permissions to users (Many To Many Polymorphic)
Schema::create('permission_user', function (Blueprint $table) {
$table->unsignedInteger('permission_id');
$table->unsignedInteger('user_id');
$table->string('user_type');
$table->foreign('permission_id')->references('id')->on('permissions')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['user_id', 'permission_id', 'user_type']);
});
// Create table for associating permissions to roles (Many-to-Many)
Schema::create('permission_role', function (Blueprint $table) {
$table->unsignedInteger('permission_id');
$table->unsignedInteger('role_id');
$table->foreign('permission_id')->references('id')->on('permissions')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['permission_id', 'role_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('permission_user');
Schema::dropIfExists('permission_role');
Schema::dropIfExists('permissions');
Schema::dropIfExists('role_user');
Schema::dropIfExists('roles');
}
}
@@ -0,0 +1,67 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class LaratrustSetupTeams extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Create table for storing teams
Schema::create('teams', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('display_name')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
Schema::table('role_user', function (Blueprint $table) {
// Drop role foreign key and primary key
$table->dropForeign(['role_id']);
$table->dropPrimary(['user_id', 'role_id', 'user_type']);
// Add team_id column
$table->unsignedInteger('team_id')->nullable();
// Create foreign keys
$table->foreign('role_id')->references('id')->on('roles')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('team_id')->references('id')->on('teams')
->onUpdate('cascade')->onDelete('cascade');
// Create a unique key
$table->unique(['user_id', 'role_id', 'user_type', 'team_id']);
});
Schema::table('permission_user', function (Blueprint $table) {
// Drop permission foreign key and primary key
$table->dropForeign(['permission_id']);
$table->dropPrimary(['permission_id', 'user_id', 'user_type']);
$table->foreign('permission_id')->references('id')->on('permissions')
->onUpdate('cascade')->onDelete('cascade');
// Add team_id column
$table->unsignedInteger('team_id')->nullable();
$table->foreign('team_id')->references('id')->on('teams')
->onUpdate('cascade')->onDelete('cascade');
$table->unique(['user_id', 'permission_id', 'user_type', 'team_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
}
@@ -0,0 +1,32 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ChangeEmailToPhoneFromPasswordresetTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('password_resets', function (Blueprint $table) {
$table->renameColumn('email', 'phone');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('password_resets', function (Blueprint $table) {
$table->renameColumn('phone', 'email');
});
}
}
+1
View File
@@ -12,5 +12,6 @@ class DatabaseSeeder extends Seeder
public function run()
{
// $this->call(UsersTableSeeder::class);
$this->call(LaratrustSeeder::class);
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class LaratrustSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->command->info('Truncating User, Role and Permission tables');
$this->truncateLaratrustTables();
$config = config('laratrust_seeder.role_structure');
$userPermission = config('laratrust_seeder.permission_structure');
$mapPermission = collect(config('laratrust_seeder.permissions_map'));
foreach ($config as $key => $modules) {
// Create a new role
$role = \App\Role::create([
'name' => $key,
'display_name' => ucwords(str_replace('_', ' ', $key)),
'description' => ucwords(str_replace('_', ' ', $key))
]);
$permissions = [];
$this->command->info('Creating Role '. strtoupper($key));
// Reading role permission modules
foreach ($modules as $module => $value) {
foreach (explode(',', $value) as $p => $perm) {
$permissionValue = $mapPermission->get($perm);
$permissions[] = \App\Permission::firstOrCreate([
'name' => $permissionValue . '-' . $module,
'display_name' => ucfirst($permissionValue) . ' ' . ucfirst($module),
'description' => ucfirst($permissionValue) . ' ' . ucfirst($module),
])->id;
$this->command->info('Creating Permission to '.$permissionValue.' for '. $module);
}
}
// Attach all permissions to the role
$role->permissions()->sync($permissions);
$this->command->info("Creating '{$key}' user");
// Create default user for each role
$user = \App\User::create([
'name' => ucwords(str_replace('_', ' ', $key)),
'phone' => $key,
'password' => bcrypt('password')
]);
$user->attachRole($role);
}
// Creating user with permissions
if (!empty($userPermission)) {
foreach ($userPermission as $key => $modules) {
foreach ($modules as $module => $value) {
// Create default user for each permission set
$user = \App\User::create([
'name' => ucwords(str_replace('_', ' ', $key)),
'phone' => $key,
'password' => bcrypt('password'),
'remember_token' => str_random(10),
]);
$permissions = [];
foreach (explode(',', $value) as $p => $perm) {
$permissionValue = $mapPermission->get($perm);
$permissions[] = \App\Permission::firstOrCreate([
'name' => $permissionValue . '-' . $module,
'display_name' => ucfirst($permissionValue) . ' ' . ucfirst($module),
'description' => ucfirst($permissionValue) . ' ' . ucfirst($module),
])->id;
$this->command->info('Creating Permission to '.$permissionValue.' for '. $module);
}
}
// Attach all permissions to the user
$user->permissions()->sync($permissions);
}
}
}
/**
* Truncates all the laratrust tables and the users table
*
* @return void
*/
public function truncateLaratrustTables()
{
Schema::disableForeignKeyConstraints();
DB::table('permission_role')->truncate();
DB::table('permission_user')->truncate();
DB::table('role_user')->truncate();
\App\User::truncate();
\App\Role::truncate();
\App\Permission::truncate();
Schema::enableForeignKeyConstraints();
}
}
+5 -1
View File
@@ -19,13 +19,17 @@ use Illuminate\Http\Request;
Route::post('register', 'AuthController@register');
Route::post('login', 'AuthController@login');
Route::post('recover', 'AuthController@recover');
Route::post('password/recover', 'AuthController@recover');
Route::post('send-verification', 'AuthController@sendVerification');
Route::post('verify', 'AuthController@verifyUser');
Route::group(['middleware' => ['jwt.auth']], function() {
Route::get('logout', 'AuthController@logout');
Route::put('user', 'AuthController@updateUser');
Route::get('test', function(){
return response()->json(['foo'=>'bar']);
});