I created a Laravel login passport API but when email is provided "null" or password is null, it's not showing validation required error. It's returning html of something?
Here is my code of controller:
<?php
namespace App\Http\Controllers\Api;
use\App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
public function login(Request $request)
{
$loginData= $request->validate([
'email'=>'required',
'password'=>'required',
]);
if(!auth()->attempt($loginData))
{
return response()->json(['message'=>'Invalid credientails']);
}
$accessToken =auth()->user()->createToken('authToken')->accessToken;
return response()->json(['user'=>auth()->user(),'access_Token'=>$accessToken]);
}
}
Try this
Also please make sure you include the class validator in controller-> use Validator;
$validator = Validator::make($request->all(), [
'email'=>'required',
'password'=>'required',
]);
if ($validator->fails())
{
$message = $validator->errors()->first();
return response()->json(['statusCode'=>200,'success'=>false,'message'=>$message], 200);
}
Related
i got some issue on laravel with this code > for logincontroller
in database i was using char for level as called for admin and user. and the code i build like this
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
class LoginController extends Controller
{
public function index(){
return view('auth.login');
}
public function store(Request $request){
if(Auth::user()->level==admin){
return view('admin.admin-home',[
]);
}else{
(Auth::user()->level==user);
return view('user.user-home'
);
}
return back()->with('alert',[
'type' => 'danger',
'msg' => 'There is wrong in your credentials!'
]);
}
}
when to run this got error > ErrorException Attempt to read property "level" on null
hope can help for this thanks.
I am creating user authentication using a custom table. In my login controller authentication is working fine and redirected to dashboard. But when I am going to create another url using a new controller, user auth data not showing for that controller.
I want to get user data through auth facade in constructor. How will that possible?
Here is my code:
web.php:
<!---Routes for login and dashboard-->
Route::get('/login','CustomLogin#index');
Route::post('/login','CustomLogin#checklogin');
Route::get('/','CustomLogin#SuccessLogin');
Route::get('/logout','CustomLogin#logout');
<!---Routes for other controller where user auth not working-->
Route::get('/add-creditor', 'AddCreditor#index');
CustomLogin.php (controller):
<?php
namespace App\Http\Controllers;
use App\library\My_functions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\User;
use Illuminate\Support\Facades\Auth;
use Redirect;
use View;
use Session;
use Cookie;
class CustomLogin extends Controller
{
public function __construct()
{
$this->_myFun = new My_functions;
}
public function index()
{
if(!Auth::check()) {
return view('CustomLogin.CustomLogin');
}
else{
Redirect::to(SITE_URL)->send();
}
}
public function username()
{
return 'user_name';
}
function checklogin(Request $request)
{
$this->validate($request, [
'input-username' => 'required',
'input-password' => 'required'
]);
$user_data = array(
'user_name' => $request->get('input-username'),
'password' => $request->get('input-password')
);
if(Auth::attempt($user_data)){
return redirect('/');
}
else
{
return back()->with('error','Wrong Login Details');
}
}
function SuccessLogin(){
if (!$this->_myFun->DoLogIn()) {
Redirect::to(SITE_URL.'login')->send();
}
else {
$data=array();
return View::make('include.dashboard',$data);
}
}
function logout(Request $request){
Auth::logout();
return redirect('/login');
}
}
Function DoLogIn() (app/library)
<?php namespace App\library {
use Illuminate\Routing\Controller as BaseController;
use App\library\CreateCrmGuid; // Get custom function
use App\library\FunctionForContact; // Get custom function
use Illuminate\Http\Request;
use Session;
use DB;
use Hash;
use Auth;
use App\User;
class My_functions{
public function DoLogIn()
{
//dd(Auth::user()); /*returns data if run from Login controller but null from Add Creditor controller*/
if(Auth::check())
{
$user_id = Auth::user()->id;
define('authenticated_user_id' ,$user_id);
return true;
}
else
{
return false;
}
}
}
AddCreditor Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Cookie;
use Config;
use App\library\my_functions; // Get custom function
use Redirect;
use DB;
use Session;
class AddCreditor extends Controller
{
protected $_myFun;
function __construct(){
dd(Auth::user()); // this returns null
$this->_myFun = new My_functions;
if (!$this->_myFun->DoLogIn()) {
Redirect::to(SITE_URL.'login')->send();
}
}
}
Add auth Middleware in your routes
Route::middleware(['auth'])->get('/add-creditor', 'AddCreditor#index');
Still, after this, you might not get user data through Auth facade in the controller constructor, But in your Route method i.e. AddCreditor#index you will get the user data either through the following methods
Auth::user();
or
request()->user();
I need to use my custom validation rule for validating API requests.
Request Class:
This is my request validation rule.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class LoginRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'username' => 'required',
'password' => 'required'
];
}
public function messages()
{
return [
'username.required' => 'The Username field is required',
'password.required' => 'The Password field is required'
];
}
}
API Controller:
This is my API controller and method.
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\LoginRequest;
class LoginController extends BaseController
{
public function login(LoginRequest $request)
{
print_r($validatorMsg);
die();
}
}
Unable to get error message.
guys, I resolved the problem this is the solution:
public function login(Request $request)
{
$LoginRequest = New LoginRequest;
$validator = Validator::make($request->all(), $LoginRequest->rules(),$LoginRequest->messages());
if($validator->fails()){
return response()->json($validator->errors(), 422);
}
}
In order to display error messages in your API's, use response() method in your LoginRequest class, so you always return JSON. Something like this:
public function response(array $errors)
{
// Always return JSON.
return response()->json($errors, 422);
}
Now try to submit empty form, and you should be able to view the error message.
I'm building an api to authenticate my users through my mobile application
The login controller return me the correct token.
<?php
namespace App\Api\V1\Controllers;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tymon\JWTAuth\JWTAuth;
use App\Http\Controllers\Controller;
use App\Api\V1\Requests\LoginRequest;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class LoginController extends Controller
{
public function login(LoginRequest $request, JWTAuth $JWTAuth)
{
$credentials = $request->only(['username', 'password']);
try {
$token = $JWTAuth->attempt($credentials);
if(!$token) {
throw new AccessDeniedHttpException();
}
} catch (JWTException $e) {
throw new HttpException(500);
}
return response()
->json([
'status' => 'ok',
'token' => $token
]);
}
}
Postman result
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHBzOlwvXC9iZXRhZmlsZS5vcmdcL2dpcHNcL3B1YmxpY1wvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTQ5Mjc4MDI2NiwiZXhwIjoxNDkyNzgzODY2LCJuYmYiOjE0OTI3ODAyNjYsImp0aSI6InZHWkxaNHNqRUlqYW05WTMifQ.g8_-qHsVVvCEj9_BoqDCKJ9QHvm-yqWALsXmxeMK_3c"
}
Now when I tried to get the current user by token I get the signature error
User controller
<?php
namespace App\Api\V1\Controllers;
use JWTAuth;
use App\Record;
use App\Http\Requests;
use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;
use App\Http\Controllers\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class RecordController extends Controller
{
use Helpers;
public function store(Request $request) {
//$record = new Record;
//return $this->currentUser();
$currentUser = JWTAuth::parseToken()->authenticate();
return $currentUser;
}
private function currentUser() {
return JWTAuth::parseToken()->authenticate();
}
}
Postman result
{
"error": {
"message": "Token Signature could not be verified.",
"status_code": 500
}
}
I already try by pass the token by url domain.com/api/auth?token=token_key and by header Authorization Bearer token_key
Also I have the jwt secret inside config/jwt.php 'secret' => env('jwt_secret') and inside .env JWT_SECRET=jwt_secret
Any tip to help to solve this issue?
Thanks
Try generate a key:
php artisan jwt:secret
This will update your .env file with something like JWT_SECRET=foobar
try to create validator manually in Lumen. The official documentation is written:
<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
/**
* Store a new blog post.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
I wrote
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController,
Validator;
class Welcome extends BaseController
{
public function index()
{
$validator = Validator::make(
['test' =>'TestValidation'],
['test' => 'required|unique:posts|max:255']
);
}
}
but Lumen returns fatal error:
Fatal error: Class 'Validator' not found in ...
I have tried to do like in Laravel 5:
use Illuminate\Support\Facades\Validator;
but then Lumen returns
Fatal error: Call to a member function make() on a non-object in
Somebody knows how to use the Validator class in Lumen? Thank you.
Validator is a facade. Facades aren't enabled by default in lumen.
If you would like to use the a facade, you should uncomment the
$app->withFacades();
call in your bootstrap/app.php file.
This is for Lumen version 5.3 (as shown in the docs):
use Illuminate\Http\Request;
$app->post('/user', function (Request $request) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users'
]);
// Store User...
});
https://lumen.laravel.com/docs/5.3/validation