I seem to remember in a former version of laravel you could set some logic which fired before the roots were hit. What I am looking to do is:
if(Auth::check())
{
if(!Auth::user()->email || is_null(Auth::user()->email))
{
return redirect('/dashboard')->with('error', 'You have not provided an email address');
}
}
Reason being that I have a social login and Twitter logins do not provide an email address nor do some Facebook logins.
If you can think of a better option than redirecting the user to the dashboard and am add email form please share it, as on registration I send out a welcome email via an event handler and listener and it would save me putting the same logic in the controller before firing the event.
You can add another middleware that does this check, or you could just add it as another condition in the application's existing Authenticate middleware.
Here is the default Authenticate middleware in Laravel 5.2, with your code added to it. (you should be able to find this file in app/Http/Middleware/Authenticate.php.)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
}
return redirect()->guest('login');
}
/* YOUR ADDED CODE STARTS HERE */
// Note that you don't need to call `Auth::check` because
// `Auth::guest` has already been called above and has returned
// `false` in order to get here.
if(!Auth::user()->email || is_null(Auth::user()->email))
{
return redirect('/dashboard')->with('error', 'You have not provided an email address');
}
/* YOUR ADDED CODE ENDS HERE */
return $next($request);
}
}
Related
So I'm trying to make a laravel API for a escorts-like site, anyway, i use Passport for authentification and the register part works but the login one doesnt, and i dont know why, i'll let the passportAuthController down as code and a ss of the database
class passportAuthController extends Controller
{
/**
* handle user registration request
*/
public function registerUserExample(RegisterUserRequest $request){
///TODO: TEST THE CRUD FEATURES IMPLEMENTED IN THE USER CONTROLLER AFTER U CHECK LOGIN FEATURE
$attributes = $request -> validated();
$user = User::create($attributes);
$access_token_example = $user->createToken('RegisterToken')->accessToken;
//return the access token we generated in the above step
return response()->json(['token'=>$access_token_example],200);
}
/**
* login user to our application
*/
public function loginUserExample(Request $request){
$login_credentials=[
'email'=>$request->email,
'password'=>$request->password,
];
if(auth()->attempt($login_credentials)){
//generate the token for the user
$user_login_token= auth()->user()->createToken('LoginToken')->accessToken;
//now return this token on success login attempt
return response()->json(['token' => $user_login_token], 200);
}
else{
//wrong login credentials, return, user not authorised to our system, return error code 401
return response()->json(['error' => 'UnAuthorised Access'], 401);
}
}
/**
* This method returns authenticated user details
*/
// index function
public function authenticatedUserDetails(){
//returns details
return response()->json(['authenticated-user' => auth()->user()], 200);
}
}
The request as well:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterUserRequest 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 [
'name'=>'required|max:255|min:3',
'email'=>'required|email',
'password'=>'required|min:7|max:255',
'gender'=>'required|min:4|max:6',
'interest'=>'required|min:4|max:6',
'Country'=>'required|max:255',
'County'=>'required|max:255',
'City'=>'required|max:255',
'birthday'=>'required|date'
];
}
}
and the ss of the database:
and the routes (api.php):
<?php
use App\Http\Controllers\passportAuthController;
use App\Http\Controllers\UserController;
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:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
//routes/api.php
//login & register routes
Route::post('register',[passportAuthController::class,'registerUserExample']);
Route::post('login',[passportAuthController::class,'loginUserExample']);
//CRUD and search routes
Route::post('storeUser',[UserController::class,'store']);
Route::get('showAll',[UserController::class, 'index']);
Route::put('updateUser/{id}',[UserController::class,'update']);
Route::delete('delete/{id}', [UserController::class,'deleteUser']);
Route::get('search/{name}',[UserController::class,'search']);
//add this middleware to ensure that every request is authenticated
Route::middleware('auth:api')->group(function(){
Route::get('user', [passportAuthController::class,'authenticatedUserDetails']);
});
Your password in users table is not encrypted.
The reason is this line
$attributes = $request->validated();
$user = User::create($attributes);
You have not encrypted your password and the method auth()->attempt($login_credentials) uses compares the encrypted password request with stored encrypted password in your db.
You can use bcrpyt() to encrypt your password, laravel comes with bcrypt() as a helper function.
Change to this in your registerUserExample(RegisterUserRequest $request)
$attributes = $request->validated();
foreach($attributes as $key => $attribute){
if($key == 'password') {
$attributes[$key] = bcrypt($attribute);
}
}
$user = User::create($attributes);
so if you see the response is mean that wrong login credentials, return, user not authorised to our system, return error code 401 ,
So with a little observation you will know that your code work fine but your logic is not good ,
So the answer simply is because the password insert in your database is note crypted and laravel passport when they are trying to make login they use a function of check ,
so if you want your code work your password must be crypted in the register exemple
$user->password = hash::make($request->password);
Or
$user->password = Crypt::encrypt($request->password);
Conclusion you can't make authentification with laravel passport if your password not crypted
The attempt method accepts an array of key / value pairs as its first argument. The password value will be hashed. The other values in the array will be used to find the user in your database table. So,
You try this
public function loginUserExample(Request $request){
$user = User::where('account', $request->account)
->where('password', $request->password)
->first();
if($user) {
Auth::loginUsingId($user->id);
// -- OR -- //
Auth::login($user);
return redirect()->route('home');
} else {
return redirect()->back()->withInput();
}
}
So I have an Laravel app, but I have overridden the default sendEmailVerificationNotification function in my App\User.php. Because I didn't want the default email thing.
Now, when I register, I get an email and activation etc... That all works perfectly. However, when I click the link, I get a 500 error... So I go and look into the logs and see the follwoing error:
Class 'App\Http\Controllers\Auth\Verified' not found
Now, indeed, that class doesn't exist, because I have no idea what I should do in that class...
In my User.php, the verify method is the following;
public function verify(Request $request): Response
{
if ($request->route('id') != $request->user()->getKey()) {
throw new AuthorizationException;
}
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
toastr()->success('Uw email is geverifiëerd', 'Gelukt!', ['timeOut' => 5000]);
}
return redirect($this->redirectPath())->with('verified', true);
}
The full error is this:
[2019-04-14 11:57:29] staging.ERROR: Class
'App\Http\Controllers\Auth\Verified' not found
{"userId":3,"exception":"[object]
(Symfony\Component\Debug\Exception\FatalThrowableError(code: 0):
Class 'App\Http\Controllers\Auth\Verified' not found at
/var/www/rpr/releases/20190414113903/app/Http/Controllers/Auth/VerificationController.php:60)
Line 60 in VerficationController.php is the } of the if-statement with hasVerifiedEmail.
Can someone please explain how I can just verify the user and give a notification that the account has been verified?
You must use the Auth facade. Add this line to your controller:
use Illuminate\Support\Facades\Auth;
You forgot to add Verified class to your use, then add:
use Illuminate\Auth\Events\Verified;
I have created a login page but I cant get past it because it says Sorry, your session has expired. Please refresh and try again.
This is my controller...
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class loginController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$request = Request::all();
$registers = registers::where('employeeID', $request['employeeID'])
->first();
$validCredentials = Hash::check($request['password'], $request-
>get('password'));
if ($validCredentials) {
Session::flash('login','login Successful!');
return view('dashboard');
}
}
this is my route...
Route::get('/', function () {
return view('register');
});
Route::resource('register', 'registerController');
Route::get('login',function(){
return view('login');
});
Route::resource('login', 'loginController');
Route::resource('login', 'loginController#index');
Route::get('dashboard',function(){
return view('dashboard');
});
I dont have a model because I dont think it is necessary
Though your input will be highly appreciated as I am new to laravel
When trying to authenticate user in laravel use the following syntax (you can modify it to what field do you want it to check). What this code does is it will check with your database then if it's a successful attempt, then it will create User session.
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// redirect or do anything else
}
for more detail you can check here : https://laravel.com/docs/5.7/authentication#authenticating-users
=================================
I will try to exmplain your current syntax (part of it)
$validCredentials = Hash::check($request['password'], $request->get('password'));
if ($validCredentials) {
Session::flash('login','login Successful!');
}
here's my short explaination about your code :
$validCredentials.............
only checks if the password is correct with the hash, doesn't make any sessions or cookies. which doesn't truly authenticate the user. it only checks if the password is true
if ($validCredentials) {
Session::flash('login','login Successful!');
}
it only flash session. what you must understand is that flash session is only short term (only available on the next page and will went away if the user change page / refresh the page).
And flash session ONLY WORKS if you create long-term Session (user is trully logged in) using the code like what I wrote above
how to overwrite laravel's login method, I want to add a universal key, to be able to enter the accounts of system users.
After making the login attempt and if it does not match the credentials of the database, make another attempt with a universal password that is in the code.
I think it is here (EloquentUserProvider) where the validation of credentials is done, but I do not know how to customize it so that it works as I wish.
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
I´m usising laravel 5.6
Laravel Fired sendFailedLoginResponse method after failed login. You can overwrite it.
Check AuthenticatesUsers trait in LoginController
protected function sendFailedLoginResponse(Request $request)
{
if($this->limiter()->attempts($this->throttleKey($request)) == 1){ //if first login attempt failed
//implement your own login logic here with universal password
}else{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
}
I use the manual authentication in Larave, here is my function of code
public function doLogin(){
// create our user data for the authentication
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userdata,true)) {
return (Auth::check() ? 'true' : 'false');
}
else {
// validation not successful, send back to form
return (Auth::check() ? 'true' : 'false');
}
}
After logging in, the Auth::check returned true. But after browsing to protected routes, which have this construct function
public function __construct()
{
$this->middleware('auth');
}
the middleware redirects me to the login page again, even after login.
Auth middleware has never been modified. Are there any modifications I needed to do?
I also tried my custom middleware:
class LoginCheck
{
public function handle($request, Closure $next)
{
if (!Auth::check()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect('login');
}
}
return $next($request);
}
}
Still not working, means Auth::check() is returning false.
Cookies are configured to store session, and still not working, too.
This is weird, but...
I created a new Laravel project. Copied all the MVC and routes (only that) but excluding everything about auth. Then I did php artisan make:auth, and it worked, and I have literally no idea why.
Seems like I must have messed with something really, bad.
By the way, thanks for all the help!