Problems getting Auth:: user() - php

I'm new to Laravel. I want to get an authorized user using the Auth::user () facade, in order to extract its ID, in the logout() method this is obtained and the authorized user is returned as an array with its data, but in the store() method Auth:: user () returns null. Tell me, please, what is the problem?
AuthController (here is logout()):
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserLoginRequest;
use Egulias\EmailValidator\Exception\AtextAfterCFWS;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;
class AuthController extends Controller
{
public function store(UserCreateRequest $request){
$user = new User();
$user->login = $request->get('login');
$user->password = Hash::make($request->get('password'));
$user->email = $request->get('email');
$user->number_phone = $request->get('number_phone');
$user->assignRole('user');
if (!$user->save()) {
return response()->json(['message'=>'Регистрация не удалась']);
}
return response()->json(['message'=>$user->jsonSerialize()]);
}
public function login(UserLoginRequest $request){
$user = User::query()->where('login', $request->get('login'))->first();
if (!$user || !Hash::check($request->get('password'), $user->password)) {
return response()->json(['message'=>'Попытка входа не удалась'], 400);
}
$token = $user->createToken('api_token')->plainTextToken;
$user->api_token = $token;
$user->save();
$user = Auth::login($user);
return response()->json(['message'=>Auth::user()->api_token], 200);
}
public function logout(Request $request) {
dd(Auth::user());
$request->user()->currentAccessToken()->delete();
return response()->json(['message' => 'Вы вышли из системы'], 200);
}
AuthController (here is store()):
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ApplicationCreateRequest;
use Illuminate\Http\Request;
use App\Models\Application;
use App\Models\Status;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class ApplicationController extends Controller
{
public function showById($id) {
return response()->json(Application::find($id), 200);
}
public function show() {
return response()->json(Application::all(), 200);
}
public function store(ApplicationCreateRequest $request){
dd(Auth::user());
//$application = new Application();
//dd(Auth::user()->api_token);
//$application->user_id = Auth::id();
//$application->status_id = 1;
//$application->description = $request->get('description');
//
//if (!$application->save()) {
// return response()->json(['message'=>'Заявка не отправлена'], 500);
//}
//
//return response()->json(['message'=>$application->jsonSerialize()]);
}
public function delete(Application $application) {
if ($application->delete()) {
return response()->json('Заявка удалёна', 200);
}
return response()->json(['message' => 'Заявка не удалёна'], 500);
}
// public function updateStatus(Application $application)
// {
// if ($application->status_id)
// }
}
api.php:
<?php
use App\Http\Controllers\ApplicationController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\ReviewController;
use App\Http\Controllers\AdminController;
use App\Http\Requests\UserLoginRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['middleware' => ['role:admin']], function () {
});
Route::post('login', [AuthController::class, 'login']);
Route::post('authStore', [AuthController::class, 'store']);
Route::get('authLogout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
Route::get('application/{id}', [ApplicationController::class, 'showById']);
Route::get('application', [ApplicationController::class, 'show']);
Route::post('applicationStore', [ApplicationController::class, 'store'])->middleware('auth:sanctum');
Route::post('applicationDelete/{application}', [ApplicationController::class, 'delete'])->middleware('auth:sanctum');
//Route::post('userDelete/{user}', [AdminController::class, 'delete']);
Route::post('userStore', [AdminController::class, 'store']);
Route::get('user', [AdminController::class, 'show']);
Route::get('user/{id}', [AdminController::class, 'showById']);
Route::post('userDelete/{user}', [AdminController::class, 'delete'])->middleware('auth:sanctum');
Route::get('review', [ReviewController::class, 'showReview']);
Route::get('review/{id}', [ReviewController::class, 'showReviewById']);
Route::post('reviewStore', [ReviewController::class, 'store'])->middleware('auth:sanctum');
Route::post('reviewUpdate/{id}', [ReviewController::class, 'updateReview'])->middleware('auth:sanctum');
Route::post('reviewRatingUpdate/{id}', [ReviewController::class, 'updateReviewRating'])->middleware('auth:sanctum');
Route::get('reviewRating', [ReviewController::class, 'showReviewRating'])->middleware('auth:sanctum');
Route::get('reviewRating/{id}', [ReviewController::class, 'showReviewRatingById']);
Route::get('authUser', [AuthController::class, 'user']);

Define middleware in the constructer of your controller and it will do the trick here
public function __construct()
{
$this->middleware('auth:api');
}
Or moved the route into Route::middleware it will work
Route::middleware('auth:api')->group( function () {
Route::post('authStore', [AuthController::class, 'store']);
});

Use
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
at the start
register method
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
'mobile' => 'required|min:10',
]);
if ($validator->fails()) {
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
[
'password' => bcrypt($request->password),
]
));
return response()->json([
'message' => 'User successfully registered',
'user' => $user
], 201);
}

Related

Bad routes for admin in Laravel

I am a newbie in Laravel and wanna create Admin Login and Registration. I have user registration and it works properly.
My web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::view('/', 'index');
Route::name('user.')->group(function () {
Route::view('/private', 'private')->middleware('auth')->name('private');
Route::get('/login', function() {
if (Auth::check()) {
return redirect(route('user.private'));
}
return view('login');
})->name('login');
Route::post('/login', [\App\Http\Controllers\LoginController::class, 'login']);
Route::get('/logout', function () {
Auth::logout();
return redirect('/');
})->name('logout');
Route::get('/registration', function() {
if (Auth::check()) {
return redirect(route('user.private'));
}
return view('registration');
})->name('registration');
Route::post('/registration', [\App\Http\Controllers\RegisterController::class, 'save']);
});
Route::name('admin.')->group(function () {
Route::view('/adminPrivate', 'adminPrivate')->middleware('auth')->name('adminPrivate');
// dd(Route::view('/adminPrivate', 'adminPrivate')->middleware('auth')->name('private'));
Route::get('/adminLogin', function() {
if (Auth::guard('admin')->check()) {
return redirect(route('admin.adminPrivate'));
}
return view('adminLogin');
})->name('login');
Route::post('/adminLogin', [\App\Http\Controllers\LoginAdminController::class, 'login']);
Route::get('/adminLogout', function () {
Auth::guard('admin')->logout();
return redirect('/');
})->name('logout');
Route::get('/adminRegistration', function() {
if (Auth::guard('admin')->check()) {
return redirect(route('admin.adminPrivate'));
}
return view('adminRegistration');
})->name('registration');
Route::post('/adminRegistration', [\App\Http\Controllers\RegisterAdminController::class, 'save']);
});
My RegisterAdminController.php
<?php
namespace App\Http\Controllers;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RegisterAdminController extends Controller
{
public function save(Request $request) {
if (Auth::guard('admin')->check()) {
return redirect(route('admin.adminPrivate'));
}
$validateFields = $request->validate([
'username' => 'required',
'password' => 'required'
]);
if (Admin::where('username', $validateFields['username'])->exists()) {
return redirect(route('admin.registration'))->withErrors([
'username' => 'Username already registered!'
]);
}
$admin = Admin::create($validateFields);
if ($admin) {
Auth::guard('admin')->login($admin);
return redirect(route('admin.adminPrivate'));
}
return redirect(route('admin.login'))->withErrors([
'formError' => 'Cannot save admin!'
]);
}
}
My LoginAdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
class LoginAdminController extends Controller
{
public function login(Request $request) {
if (Auth::guard('admin')->check()) {
return Redirect::to(route('admin.adminPrivate'));
}
$formFields = $request->only(['username', 'password']);
if (Auth::guard('admin')->attempt($formFields)) {
return Redirect::to(route('admin.adminPrivate'));
}
return redirect(route('admin.login'))->withErrors([
'username' => 'Can not authorize'
]);
}
}
I don't understand how I can solve this problem. Need a help. I tried modify all names of my Routes, but this didn't help.

Authorization in laravel

I'm new to laravel, I'm building an API and using laravel sanctum to implement authorization. After authorization, I get the user token, but I can't get any other user data so that I can, for example, extract the ID of the authorized user or substitute it in another table from the database, or use the data of the authorized user in any way. I don't know what exactly I did wrong. Please help me solve this problem. Here is my code:
AuthController:
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserLoginRequest;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;
class AuthController extends Controller
{
public function store(UserCreateRequest $request){
$user = new User();
$user->login = $request->get('login');
$user->password = Hash::make($request->get('password'));
$user->email = $request->get('email');
$user->number_phone = $request->get('number_phone');
// $user->role_id = 1;
$user->assignRole('user');
if (!$user->save()) {
return response()->json(['message'=>'Регистрация не удалась']);
}
return response()->json(['message'=>$user->jsonSerialize()]);
}
public function auth(UserLoginRequest $request){
$user = User::query()->where('login', $request->get('login'))->first();
if (!$user || !Hash::check($request->get('password'), $user->password)) {
return response()->json(['message'=>'Попытка входа не удалась'], 400);
}
$token = $user->createToken('api_token')->plainTextToken;
$user->api_token = $token;
$user->save();
return response()->json(['message'=>$user->api_token = $token], 200);
}
public function logout(Request $request) {
$request->user()->currentAccessToken()->delete();
return response()->json(['message' => 'Вы вышли из системы'], 200);
}
}
Api.php:
<?php
use App\Http\Controllers\ApplicationController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\ReviewController;
use App\Http\Controllers\UserController;
use App\Http\Requests\UserLoginRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['middleware' => ['role:admin']], function () {
Route::get('test', function () {
return view('test');
});
});
Route::post('auth', [AuthController::class, 'auth']);
Route::post('authStore', [AuthController::class, 'store']);
Route::get('authLogout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
Route::get('application/{id}', [ApplicationController::class, 'showById']);
Route::get('application', [ApplicationController::class, 'show']);
Route::post('applicationStore', [ApplicationController::class, 'store']);
Route::post('applicationDelete', [ApplicationController::class, 'delete']);
Route::post('userDelete/{user}', [UserController::class, 'delete']);
Route::post('userStore', [UserController::class, 'store']);
Route::get('review', [ReviewController::class, 'show']);
Route::post('reviewStore', [ReviewController::class, 'store']);
Route::post('review/{id}', [ReviewController::class, 'update']);
UserLoginRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserLoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'login' => 'required|string',
'password' => 'required|string',
];
}
}
Kernel.php:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
use Illuminate\Support\Facades\Auth;
// Get the currently authenticated user...
$user = Auth::user();
// Get the currently authenticated user name...
$username = Auth::user()->name;
// Get the currently authenticated user's ID...
$id = Auth::id();
in blade.php you can get it like this
{{{ isset(Auth::user()->name) ? Auth::user()->name : Auth::user()->id }}}

Call to a member function token() on null

I'm doing authorization using laravel:sanctum for the API. But, when calling the logout() method, I get the following error: Call to a member function tokens() on null. Please help me get rid of this error
AuthController
public function auth(UserLoginRequest $request){
$user = User::query()->where('login', $request->get('login'))->first();
if (!$user || !Hash::check($request->get('password'), $user->password)) {
return response()->json(['message'=>'Попытка входа не удалась'], 400);
}
$token = $user->createToken('api_token')->plainTextToken;
$user->api_token = $token;
$user->save();
return response()->json(['message'=>$user->api_token], 200);
}
public function logout(Request $request) {
$request->user()->tokens()->delete();
return response()->json(['message' => 'Вы вышли из системы'], 200);
}
api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::middleware('auth:sanctum')->get('user', function (UserLoginRequest $request) {
return response()->json(['login' => $request->user()->login]);
});
Route::post('auth', [AuthController::class, 'auth']);
Route::post('authStore', [AuthController::class, 'store']);
Route::get('authLogout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
Route::get('application/{id}', [ApplicationController::class, 'showById']);
Route::get('application', [ApplicationController::class, 'show']);
Route::post('applicationStore', [ApplicationController::class, 'store']);
Route::post('applicationDelete', [ApplicationController::class, 'delete']);
Route::post('userDelete/{user}', [UserController::class, 'delete']);
Route::post('userStore', [UserController::class, 'store']);
Route::post('review', [ReviewController::class, 'show']);
Route::post('reviewCreate', [ReviewController::class, 'create']);
solved this by adding my logout Route inside :-
Route::group(['middleware' => ['auth:sanctum']], function () {
// logout route api code here
}
Use auth('sanctum') instead auth() because of you used to sanctum auth
It should be:
auth('sanctum')->user()->tokens()->delete();
The code should be like following
public function logout(Request $request) {
if ($request->user()) {
$request->user()->tokens()->delete();
}
return response()->json(['message' => 'Вы вышли из системы'], 200);
}
use currentAccessToken() instead of tokens().

In a Laravel 5.4 app, when I try to login, it redirects to same login page

Web.php
Route::get('/' , ['as' => '/' , 'uses'=> 'loginController#getlogin']);
Route::post('/login', ['as' => 'login', 'uses'=> 'loginController#postlogin']);
Route::group(['middleware' =>['authen']],function (){
Route::get('/logout' ,['as'=>'logout', 'uses'=> 'loginController#getLogout']);
Route::get('/dashboard',['as'=>'dashboard', 'uses'=> 'dashboardController#dashboard']);
});
dashboardController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class dashboardController extends Controller
{
public function __construct()
{
$this->middleware('web');
}
public function dashboard()
{
return view('layouts.master');
}
}
Authen.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authen
{
public function handle($request, Closure $next ,$guard ='web')
{
if (!Auth::guard($guard)->check())
{
return redirect()->route('/');
}
return $next($request);
}
}
loginController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
class loginController extends Controller
{
use AuthenticatesUsers;
protected $username = 'username';
protected $redirectTo = '/dashboard';
protected $guard = 'web';
public function getLogin()
{
if (Auth::guard('web')->check())
{
return redirect()->route('dashboard');
}
return view('login');
}
public function postlogin(Request $request)
{
$auth = Auth::guard('web')->attempt(['username'=>$request->username,'password'=>$request->password,'active'=>1]);
if ($auth)
{
return redirect()->route('dashboard');
}
return redirect()->route('/');
}
public function getLogout()
{
Auth::guard('web')->logout();
return redirect()->route('/');
}
}
When I try to login it redirects to the same page i.e login page, I tried to solve this problem but I can't. I want to redirect dashboard through login page, but it is not happen. There is no error shown and I can't go on dashboard page too.
Try this way in postlogin function to check user authentication.
$auth = Auth::attempt(['username'=>$request->username,'password'=>$request->password,'active'=>1]);
if($auth){
//do something...
}

Laravel POST method going to GET

I have a problem that I can not resolve in Laravel 5.4.
I'm using the Postman extension to make requests for my API, so far it works normally with GET, but when I try to do a POST, the method that's actually called is GET again. (The API can not have authentication or token for the user).
api.php:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['api' => ['auth:api']], function(){
Route::group(['prefix' => 'user'], function(){
Route::get('{id}', ['uses' => 'UserController#getUser']);
Route::post('', ['uses' => 'UserController#saveUser']);
Route::get('', ['uses' => 'UserController#allUsers']);
Route::put('{id}',['uses' => 'UserController#updateUser']);
Route::delete('{id}', ['uses' => 'UserController#deleteUser']);
});
});
UserController.php:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller{
protected $user = null;
public function __construct(User $user){
$this->user = $user;
}
public function allUsers(){
return $this->user->allUsers();
}
public function getUser($id){
}
public function saveUser(){
return $this->user->saveUser();
}
public function updateUser($id){
}
public function deleteUser($id){
}
}
User.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $hidden = ['venda','remember_token', 'created_at','updated_at'];
public $fillable = ['nome','email', 'venda'];
public function allUsers(){
return self::all();
}
public function saveUser(){
$input = Input::all();
echo 'aa';
$user = new User();
$user->fill($input);
$user->save();
return $user;
}
}
First change this:
Route::group(['api' => ['auth:api']], function(){
To:
Route::group(['middleware' => ['auth:api']], function(){

Categories