i'm new in laravel. I'm stuck when creating manual authentication with laravel 9.
when the user is successfully logged in, but cannot access the view page with middleware Auth.
I tried dd(Auth::user()) and the result is null.
where is my mistake?
Controller
`
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
class OtorisasiController extends Controller
{
public function create()
{
return view('otorisasi.login');
}
public function login(Request $request)
{
$validasi = $request->validate([
'username' => 'required',
'password' => 'required'
]);
if (Auth::attempt($validasi)) {
$request->session()->regenerate();
return redirect()->intended('/');
}
return back()->with('infologin', 'Data yang anda masukan salah');
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
`
route
// Deafult Page After Login Route::get('/', [TransfersController::class, 'index'])->name('home')->middleware('auth');
how to do so, when login is successful, I can access all middleware auth pages
Related
i am working on API. I want to create login api. i have created UsersController in API folder it in controllers. when i run in postman i shows an error
Illuminate\Contracts\Container\BindingResolutionException: Target class [App\Http\Controllers\App\Http\Controllers\API\UsersController] does not exist. in file F:\University_Data\xamp\htdocs\stylooworld\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 835`
I don't now why its duplicated the routing path Target class [App\Http\Controllers\App\Http\Controllers\API\UsersController]
api.php
<?php
use Illuminate\Http\Request;
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::namespace('App\Http\Controllers\API')->group(function () {
Route::post('login', 'UsersController#loginUser');
});
UsersController.php
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\UserController;
class UsersController extends Controller
{
//
public function loginUser(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
echo "<pre>";
print_r($data);
die;
if (Auth::attempt(['email' => $data['email'], 'password' => $data['password']])) {
// check email is activated or not (Only Work Online Server)
/* $userStatus = User::where('email', $data['email'])->first();
if ($userStatus->status == 0) {
Auth::logout();
$message = "Your account is not activated yet! Please confirm your email to activate!";
Session::flash('error_message', $message);
return redirect()->back();
}*/
//update user cart with user id
if (!empty(Session::get('session_id'))) {
$user_id = Auth::user()->id;
$session_id = Session::get('session_id');
Cart::where('session_id', $session_id)->update(['user_id' => $user_id]);
}
return redirect('/');
} else {
$message = "Invalid Username or Password";
Session::flash('error_message', $message);
return redirect()->back();
}
}
}
}
I don't know why this happen?
Update the routes.
For details please check (ref link) https://laravel.com/docs/8.x/upgrade and https://laravel.com/docs/8.x/releases#routing-namespace-updates
Use like this
api.php
If not working
Route::namespace('App\Http\Controllers\API')->group(function () {
Route::post('login', 'UsersController#loginUser');
});
Then Use like this
use App\Http\Controllers\API\UsersController;
Route::post('login', [UsersController::class, 'loginUser']);
import method Request
class Request extends SymfonyRequest implements Arrayable, ArrayAccess
on click (import method) always ready.
are you ok.
We are trying to setup the Facebook social connect on our Laravel application, but it seems like we have an issue on session creation.
Here is the code for the Controller :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;
use App\Services\SocialAuthService;
class SocialAuthController extends Controller
{
public function redirect()
{
return Socialite::driver('facebook')->redirect();
}
public function callback(SocialAuthService $service)
{
$user = $service->createOrGetUser(Socialite::driver('facebook')->stateless()->user());
auth()->login($user);
return redirect()->intended('/');
}
}
And the code for the service :
<?php
namespace App\Services;
use Laravel\Socialite\Contracts\User as ProviderUser;
use Myproject\Users\User;
use Myproject\Users\SocialLogin;
class SocialAuthService
{
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialLogin::where('provider', '=', 'facebook')
->where('provider_user_id', '=', $providerUser->getId())
->first();
if ($account) {
return $account->user;
}
$user = User::where('email', '=', $providerUser->email)->first();
if (!$user) {
$fullname = explode(' ', $providerUser->getName());
$user = User::create([
'email' => $providerUser->getEmail(),
'firstname' => $fullname[0],
'lastname' => $fullname[1],
'password' => md5(rand(1, 9999)),
]);
}
$account = new SocialLogin([
'provider_user_id' => $providerUser->getId(),
'provider' => 'facebook'
]);
$account->user()->associate($user);
$account->save();
return $user;
}
}
And finally the Model :
<?php
namespace Myproject\Users;
use Illuminate\Database\Eloquent\Model;
use Myproject\Users\User;
class SocialLogin extends Model
{
protected $table = 'social_logins';
protected $fillable = ['user_id', 'provider_user_id', 'provider'];
public function user()
{
return $this->belongsTo(User::class);
}
}
When we're trying to connect via Facebook, the information is correctly insert in Database, and the callback URL set on Facebook Developers correspond to what we have in our .env, so the redirection is correctly done but at the end we don't have any session created for the user.
I think the issue comes from cross-domain, here are the interesting parts of our .env file :
APP_URL=https://www.website.com
APP_DOMAIN=website.com
SESSION_DOMAIN=.website.com
CACHE_DRIVER=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120
FACEBOOK_REDIRECT=https://www.website.com/callback/facebook
GOOGLE_REDIRECT=https://www.website.com/auth/google/callback
And our routing on web.php :
Route::domain('{subdomain}.{domain}')->middleware('locale')->group(function () {
Route::get('/callback/facebook', 'Auth\SocialAuthController#callback');
Route::get('/redirect/facebook', 'Auth\SocialAuthController#redirect');
});
I really think the issue is located on routing or SESSION_DOMAIN, but we tried to :
delete the session domain
routing outside the middleware locale, in a middleware auth
It still doesn't affect the login.
I am working on a Laravel site and I have been the LoginController. Although I obtain the auth_token at login - it doesn't allow me to call the user method - it claims the user is "unauthetnicated"
https://laravel.com/docs/7.x/passport
https://laravel.com/docs/5.8/api-authentication
I followed some documentation claiming that its unauthenticated because I need to group commands in the route?
"This is because we are not authenticated to access that route"
https://www.toptal.com/laravel/passport-tutorial-auth-user-access
but then it throws an error with ['cors', 'json.response']?
my route/api.php looks like this
<?php
use Illuminate\Http\Request;
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::group(['middleware' => [/*'cors', 'json.response'*/]], function () {
// public routes
// get auth token, POST, /login
Route::post('login', 'LoginController#login');
Route::post('logout', 'LoginController#logout')->middleware('auth:api');
});
Route::middleware('auth:api')->group(function () {
// our routes to be protected will go in here
});
and my logincontroller is like this
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
//
function login(Request $request)
{
$request->validate([
'email' => ['required', 'email'],
'password' => ['required']
]);
$user = User::where('email', $request->email)->first();
//if user not found or the request password and user password does not match
if(!$user || !Hash::check($request->password, $user->password)){
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect']
]);
}
return $user->createToken('Auth Token')->accessToken;
}
function logout(Request $request)
{
$request->user()->tokens()->delete();
}
}
I'm trying to implement my own login/logout with passport in a new Controller.
class AuthController extends AccessTokenController
{
use AuthenticatesUsers;
.
.
My login methods works fine:
public function login(ServerRequestInterface $request)
{
if (!auth()->attempt([
'email' => $request->getParsedBody()['email'],
'password' => $request->getParsedBody()['password']
])) {
return response()->json('failed attempt...');
}
auth()->login(User::where('id', Auth::user()->id)->first());
.
.
// I can access auth()->user() here just fine ..
}
But I can't access the authenticated user in the logout method so I can get his tokens and delete them.
public function logout()
{
//I can't access the authenticated user here
return auth()->user();
//return response()->json('Logged out successfully', 200);
}
What am I doing wrong?
Note: I left out anything in the login method that is related to issuing a token because it's not related to the question ..
Update: my routes/api.php
Route::post('register', 'Auth\RegisterController#register');
Route::post('login', 'Auth\AuthController#login');
Route::post('logout', 'Auth\AuthController#logout');
if you are using api then you should send authorization header else it should work for session based authentication
Then you can access the authenticated user using the request
public function logout(Request $request)
{
return $request->user(); //the user that made the request (the authenticated user)
}
Or:
public function logout(Request $request)
{
return Auth::user(); //the user that made the request (the authenticated user)
}
I added registration, and I don't want to using laravels hash but mysql Hash (because I want existing users to still be able to connect).
So i do it step by step and for now I just try to register and then login without any hashing. The credentials are correct in my table but I get
"message":"The given data was invalid.","errors":{"email":["These credentials do not match our records."]}
I tried setting it in LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
public function username()
{
return 'email';
}
public function password()
{
return 'email';
}
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
public function Login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'pwd' => $request->password, 'password' => $request->password])){
$user = Auth::user();
$username = $user->nom;
return response()->json([
'status' => 'success',
'user' => $username,
]);
} else {
return response()->json([
'status' => 'error',
'user' => 'Unauthorized Access'
]);
}
}
}
I guess I should overwrite another function, but can't find out which one.
Could you please give me some help?
Altough what you're trying to achieve is considered unsecure, to remove Laravel's hashing for password, you need to add this to your User model :
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
and not in your controller, and be sure to remove the brcypt() methods in your RegisterController
To add your MySQL own hashing methods, update your controller to insert a RAW query while creating a user upon registration