Skip to content

Instantly share code, notes, and snippets.

@arif98741
Last active November 7, 2022 10:36
Show Gist options
  • Save arif98741/4d0970779bc3e469785b8041b0eb31ec to your computer and use it in GitHub Desktop.
Save arif98741/4d0970779bc3e469785b8041b0eb31ec to your computer and use it in GitHub Desktop.
Api\AuthController
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
public function login(Request $request){
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->createNewToken($token);
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return JsonResponse
*/
protected function createNewToken($token){
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()
]);
}
}
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* Create a new notification instance.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* Get the mail representation of the notification.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native type.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getJWTIdentifier(){
return $this->getKey();
}
public function getJWTCustomClaims(){
return [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment