Skip to content

Instantly share code, notes, and snippets.

@manuelgeek
Last active May 18, 2018 19:49
Show Gist options
  • Save manuelgeek/3b1938fe8ffda569c2489f57aafb5c45 to your computer and use it in GitHub Desktop.
Save manuelgeek/3b1938fe8ffda569c2489f57aafb5c45 to your computer and use it in GitHub Desktop.
GTT API code
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
[20:43, 1/18/2018] +254 704 407117: first create a new project by
[20:44, 1/18/2018] +254 704 407117: i assume that u have install php 5.6> and composer
[20:44, 1/18/2018] +254 704 407117: then after creating the project cd in to its folder cd passport
install laravel
composer create-project --prefer-dist laravel/laravel passport
so, create a db, I named mine gtt_api,
then edit .env in root folder like this, the DB part
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=gtt_api
DB_USERNAME=root
DB_PASSWORD=
use your credentials
I realised kama yangu new project haina .env, incase youre like me, create a .env file and copy the .env.example to it,
incase this affetcs you,
run
php artisan key:generate
run php artisan make:auth
run php artisan serve
the open
http://localhost:8000/
youll see the login and register links, tuko hapo
ok so in the database folder, database/migrations
kuna create users table< thats what will run our users table ,migration, for now, we wont edit it,
we'll just use email, name and passsworsd
so run
php artisan migrate
to create the tables
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t
oo long; max key length is 767 bytes (SQL: alter table `users` add unique `
users_email_unique`(`email`))
incase you get this error, for those using maria DB, its because of the db encoding stuff,
you can correct it by changing your AppServiceProvide.php
check the gist, for now we will
ignore it, it wont affect us
ok, I forgot something,
so run this command, we want to add the api_token column
php artisan make:migration add_api_key_to_users --table=users
then run
php artisan migrate
again
http://localhost:8000/api/login while wmpty
returns
{
"success": false,
"message": {
"remember": [
"The remember field is required."
]
}
}
no inputs
then kwa our LoginController.php
cahnge the reg_no to email, I purposed for that but no time,
the iputs i meand, replace reg_no to email, we;rre loging with emailnot reg no in this case,
edit /app/User.php
to this one below
sorry
send this request
{
"email":"emashmagak@gmail.com",
"password":"manuelgeek",
"remember" : true
}
replace with your credentials
result json
{
"success": true,
"data": {
"id": 1,
"name": "Geek Manu",
"email": "emashmagak@gmail.com",
"created_at": "2018-01-18 18:40:38",
"updated_at": "2018-01-18 19:09:34",
"api_token": "xlWZudhvKeck3HCrpkixTps8xTgr66IPWoIVLXihWINnK1adsjXeBtyMB6x9"
}
}
lets create logout function in LoginController.php
add the function below the login function
logout function
public function logout(Request $request)
{
//pass request in header
$user = Auth::guard('api')->user();
if ($user) {
$user->api_token = null;
$user->save();
return response()->json([
'success' => true,
'message' => 'User logged out.'], 200);
}
return response()->json([
'success' => false,
'message' => 'User Not loged in'], 200);
}
final routes
Route::middleware(['auth:api'])->group(function () {
Route::post('logout', 'API\LoginController@logout');
});
Route::post('login', 'API\LoginController@login');
Route::post('register', 'API\RegisterController@register');
lets do register now
create a controller
php artisan make:controller API/RegisterController
Add too routes these
tuko sawa?, kama huna error, its, ok
if you have the error
now dlete the tables kwa db, the
reu
php artisan migrate
no errors sasa
now, in root folder
check for /routes/api.php
Route::post('login', 'API\LoginController@login');
run
php artisan make:controller API/LoginController
navigate to
App\Http\Controllers\API, you'll find the controller<
then we need to add a function login
run php arisan route:list
you should see this route
| POST | api/login | | App\Http\Controllers\API\LoginController@login | api
now to postman
try send a post request to
http://localhost:8000/api/login
rem to run
php artisan serve
[20:43, 1/18/2018] +254 704 407117: first create a new project by
[20:44, 1/18/2018] +254 704 407117: i assume that u have install php 5.6> and composer
[20:44, 1/18/2018] +254 704 407117: then after creating the project cd in to its folder cd passport
install laravel
composer create-project --prefer-dist laravel/laravel passport
so, create a db, I named mine gtt_api,
then edit .env in root folder like this, the DB part
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=gtt_api
DB_USERNAME=root
DB_PASSWORD=
use your credentials
I realised kama yangu new project haina .env, incase youre like me, create a .env file and copy the .env.example to it,
incase this affetcs you,
run
php artisan key:generate
run php artisan make:auth
run php artisan serve
the open
http://localhost:8000/
youll see the login and register links, tuko hapo
ok so in the database folder, database/migrations
kuna create users table< thats what will run our users table ,migration, for now, we wont edit it,
we'll just use email, name and passsworsd
so run
php artisan migrate
to create the tables
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t
oo long; max key length is 767 bytes (SQL: alter table `users` add unique `
users_email_unique`(`email`))
incase you get this error, for those using maria DB, its because of the db encoding stuff,
you can correct it by changing your AppServiceProvide.php
check the gist, for now we will
ignore it, it wont affect us
ok, I forgot something,
so run this command, we want to add the api_token column
php artisan make:migration add_api_key_to_users --table=users
app/Exceptions/Handler.php
the unauthenticated funtion to this below render() function , top avoid redirecting to login page in api
make sure the logout or any request got
headers Accept : application/json
add these to top of file
use Request;
use Illuminate\Auth\AuthenticationException;
use Response;
protected function unauthenticated($request, AuthenticationException $exception)
{
if( $request->expectsJson())
{
return response()->json([
'success' => false,
'message' => 'User not Unauthenticated.'], 401);
}
return redirect()->guest(route('login'));
}
<?php
namespace App\Http\Controllers\API;
use App\User;
use Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|string',
'password' => 'required|string',
'remember' => 'required',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message'=>$validator->errors()], 422);
}
if (Auth::attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
Auth::user()->generateToken();
return response()->json([
'success' => true,
'data' => Auth::user()->toArray(),
]);
}
return response()->json([
'success' => false,
'message' => 'Wrong Reg No or Password'],200);
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddApiKeyToUsers extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('api_token', 60)->unique()->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
Schema::dropIfExists('api_token');
});
}
}
<?php
namespace App\Http\Controllers\API;
use App\User;
use Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class RegisterController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message'=>$validator->errors()], 422);
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
]);
if ($user) {
Auth::attempt(['email' => $request->email, 'password' => $request->password]);
Auth::user()->generateToken();
return response()->json([
'success' => true,
'data' => Auth::user()->toArray(),
]);
}
return response()->json([
'success' => false,
'message'=> 'Error ocured, try again',500]);
}
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function generateToken()
{
$this->api_token = str_random(60);
$this->save();
return $this->api_token;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment