Laravel 8: after successful log in Auth session destroying on its own whenever I'm trying to redirect it to another route - laravel-8

web.php
Route::get('/', [AdminLoginController::class, 'index'])->name('admin.login');
Route::post('/login', [AdminLoginController::class, 'login'])->name('admin.login.submit');
Route::group(['middleware' => 'admin.middle' ] , function() {
Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('admin.dashboard');
});
AdminLoginController.php
public function login(Request $request)
{
$validator = Validator::make($request->all(),[
'email' => 'required|email:rfc,dns|exists:admins,email',
'password' => 'required',
],[
'email.required' => "Email is required",
'email.email' => "Email is invlaid",
'email.exists' => "Email does not exist",
'password.required' => "Password is required"
]);
if($validator->fails())
{
$this->sendResponse(400,$validator->errors()->first(),[]);
}
else
{
if (Auth::guard('admin')->attempt(["email" => $request->email , "password" => $request->password])) {
$this->sendResponse(
200,
"Successfully Logged In",
[
'location' => route('admin.dashboard')
]);
}
else {
$this->sendResponse(
500,
"Email or Password is incorrect",
[]);
}
}
}
AdminAuthenticate.php
class AdminAuthentication
{
public function handle(Request $request, Closure $next)
{
if (Auth::guard('admin')->check())
{
if (Auth::guard('admin')->user()){
return $next($request);
}
}
return redirect('/admin');
}
}

Maybe your sendResponse is not set corresponding headers (Set-cookie)? It looks like you mixing api responses with responses for browser.

Related

Registration user with uploading image

i tried to create API using Laravel 8 and here are my code for register new user
public function register(Request $request)
{
$validasi = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'user_id' => 'unique:users',
'password' => 'required|string|min:8',
'foto_ktp' => 'file|mimes:png,jpg',
]);
try {
$fileName = time() . $request->file('foto_ktp')->getClientOriginalName();
$path = $request->file('foto_ktp')->storeAs('uploads/foto_ktp', $fileName);
$validasi['foto_ktp'] = $path;
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'user_id' => $request->id,
'foto_ktp' => $request->foto_ktp,
'password' => Hash::make($request->password),
]);
$user->save();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'data' => $user,
'message' => 'Account Has Successfully Created',
'token' => $token,
'token_type' => 'Bearer',
'code' => 200
]);
} catch (\Exception $e) {
return response()->json([
'message' => 'Something wrong, user was not resgistered successfully',
'errors' => $e->getMessage(),
]);
}
}
when i tried the routes of API in Postman, the data will return like this
{
"data": {
"name": "test",
"email": "test#gmail.com",
"updated_at": "2023-01-02T06:54:01.000000Z",
"created_at": "2023-01-02T06:54:01.000000Z",
"id": 22,
"foto_ktp": {}
},
"message": "Account Has Successfully Created",
"token": "19|RXUZB40Oc35XCY4OMU6TPpqLJsmTRdFVpqsdNaS5",
"token_type": "Bearer",
"code": 200
}
foto_ktp will return {} and i checked it in database, foto_ktp field will store this data C:\xampp\tmp\php53D.tmp
I'm quite new in Laravel and i have tried to search any references but i haven't gotten it. Is there any suggestion what should i do? I used Laravel 8 for developing the API

cakephp $this->Auth->identify() always return false

I have two environments in cakephp 3.9 , both same code and same SO etc... Both in AWS hosted. I have created an API that works fine in staging but not in production, I always get FALSE when the user login with the email and pwd to get the JWT token. The weird thing it is that it works perfectly in the same environment in staging.
In the endpoint, I have this
/**
* Get JWT token
*/
public function token()
{
$user = $this->Auth->identify();
$roleQuery = TableRegistry::getTableLocator()->get('UsersRoles');
// Get user role
$role = $roleQuery
->find()
->select(['role_id'])
->where(['user_id' => $user['id']])
->first();
if (!$user) {
// throw new UnauthorizedException('Invalid login details');
$this->set([
'success' => false,
'data' => [
"code" => 401,
'message' => 'Invalid login details',
],
'_serialize' => ['success', 'data']
]);
} else{
$tokenId = base64_encode(32);
$issuedAt = time();
$key = Security::salt();
// $email = $user['email'];
$this->set([
'msg' => 'Login successfully',
'success' => true,
// 'user' => $user,
'data' => [
'token' => JWT::encode([
'alg' => 'HS256',
'id' => $user['id'],
'sub' => $user['id'],
'iat' => time(),
'exp' => time() + 86400,
],
$key)
],
'_serialize' => ['success', 'data', 'key']
]);
}
}
}
And the configuration for this environment
'Api' => [
'auth' => [
'storage' => 'Memory',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email'
],
],
'ADmad/JwtAuth.Jwt' => [
'parameter' => 'token',
'userModel' => 'Users',
// 'scope' => ['Users.status' => 1],
'fields' => [
'id' => 'id'
],
'queryDatasource' => true
]
],
'unauthorizedRedirect' => false,
'checkAuthIn' => 'Controller.initialize'
],
],
In the ApiController I have these two methods to load the components etc...
public function initialize(): void
{
parent::initialize();
$this->loadComponent('Security');
$this->loadComponent('RequestHandler');
$this->loadComponent('Auth', Configure::read('Api.auth'));
$this->Auth->allow([
'token'
]);
}
public function beforeFilter(Event $event): void
{
$this->Security->setConfig('unlockedActions', [
'token'
]);
}
I always get the same response in production
{
"success": false,
"data": {
"code": 401,
"message": "Invalid login details"
}
}
Well, after a few hours I fixed the problem. It was a very very stupid thing, I just forgot to add the https protocol to the URL in Rester (plugin similar to Postman) before call the endpoint, that's it!!!.

Auth::check() false even if logged in

if the email and username is incorrect it redirects to /login. And if i am successfully logged in, it donot redirect to /crud.
public function authenticate(Request $request)
{
$password=$request->get('password');
$email=$request->get('email');
if (Auth::attempt(['email' => $email, 'password' => $password]) )
{
return redirect()->intended('/crud');
}
else
{
return redirect('/crud/login');
}
}
but then again if i am logged in this function below shows me logged in.
public function check()
{
if (Auth::check())
{
print_r('logged in');
}
else
{
print_r('not logged in');
}
}
this is how i protected /crud
Route::group(['middleware' => ['auth','web']], function () {
Route::get('/crud','CrudController#index');
});

CakePHP Error: Class App\Controller\AuthComponent not found

I'm working in CakePHP 3.2 and writing an admin panel where only admin can login.
There is a separate table admins to store admin credentials. There is users table also which is used for users to register/login from main application.
I have to use admins table to login in admin panel.
What I have done is.
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class AppController extends Controller
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Admins',
'action' => 'login',
'plugin' => 'Admins'
],
'loginRedirect' => [
'controller' => 'ServiceRequests',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Admins',
'action' => 'login'
],
'authenticate' => [
'Form' => [
'userModel' => 'Admin',
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
]
]);
}
public function beforeRender(Event $event)
{
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
}
}
}
AdminsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
use App\Controller\AuthComponent;
/**
* Admins Controller
*
* #property \App\Model\Table\AdminsTable $Admins
*/
class AdminsController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow('add');
// Pass settings in using 'all'
$this->Auth->config('authenticate', [
AuthComponent::ALL => ['userModel' => 'Members'],
'Basic',
'Form'
]);
}
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
}
But this is not working. and gives Error: Class App\Controller\AuthComponent' not found
Also I want to restrict access to all controllers and actions without login. Thats why there is no $this->Auth->allow() in AppsController.php
use Cake\Controller\Component\AuthComponent;

basic login using auth component in cakephp2.2

could you tell how to use auth component in cake2.2 to login by authenticating from the database table.
As my AppController.php is:
`
class AppController extends Controller {
var $components = array('Auth', 'Session');
var $helpers = array('Form');
}`
my UsersController.php is:
class UsersController extends AppController {
var $name = 'Users';
var $components = array('Auth');
function login()
{
}
function logout()
{
$this->redirect($this->Auth->logout());
}
}
my view as:view\user\login.ctp
<?php
echo $this->Session->flash('auth');
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
public function login() {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}
}
You can set up the Auth configurations component and should look something like
public $components = array(
'Auth' => array(
'loginAction' => array(
'controller' => 'users',
'action' => 'login',
'plugin' => 'users'
),
'authError' => 'Did you really think you are allowed to see that?',
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
);
The function for the login, which is kinda the same as Ceeram posted it
<?php
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
Everything that i am saying it's on the oficial documentation and this tutorial about Auth is really well explained http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html