Undefined variable for hidden input after registration - Laravel - php

I have this method of trying to get their email to resend verification link if they didnt receive the first time. The problem is i dont want to let them login without verification because this database is connected with a game server and i dont want them to log in without verification. I tried to store the email so the resend button resends it to that email the verification link but after i register and when its trying to redirect me to the verify.blade i get.
Undefinded variable: user
And its pointing to the hidden input which i will show below.
This is my registration function which works fine and registers the user in the database:
protected function create(array $data)
{
$user = Account::create([
'login' => $data['login'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'verifyToken'=> Str::random(40),
'active' => (env('CONFIRM_EMAIL', true)) ? 0 : 1
]);
$thisUser = Account::findOrFail($user->id);
if(env('CONFIRM_EMAIL') == true){
$this->sendEmail($thisUser);
}
return $user;
}
This is the function that redirects or logins the user depending if i have set to True the email verification:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
if(env('CONFIRM_EMAIL') == false){
$this->guard()->login($user);
}else{
return redirect(route('verifyEmail'));
}
if ($response = $this->registered($request, $user)) {
return $response;
}
return $request->wantsJson()
? new Response('', 201)
: redirect($this->redirectPath());
}
and this is the resend function and html code with the hidden input that points the error to the value="$user->email":
protected function resend(Request $request)
{
$user = Account::where('email', $request->email)->first();
if($user){
$user->verifyToken = Str::random(40);
$user->save();
$this->sendEmail($user);
return back()->with('user',$user)->with('success', 'A link has been sent to your email');
}
}
<form action=" {!! route('resendEmail') !!}" method="POST">
#csrf
<input type="hidden" name="email" value="{{ $user->email }}">
<button class="btn btn-default db" type="submit" value="Submit">Resend Verification Link</button>
</form>
This is the route for verifyemail which i dont know how to pass the email parameter:
return redirect(route('verifyEmail'));

Related

Undefined variable when registering user - Laravel

I want to store the registered email from user so if he doesnt get verification link on email to use resend function to get another email. Iam not allowing users to login so i cant get their email as Auth::$user->email, i created the hidden input to store the email but i get this error:
Undefined variable: user
This is my register function:
protected function create(array $data)
{
$user = Account::create([
'login' => $data['login'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'verifyToken'=> Str::random(40),
'active' => (env('CONFIRM_EMAIL', true)) ? 0 : 1
]);
$thisUser = Account::findOrFail($user->id);
if(env('CONFIRM_EMAIL') == true){
$this->sendEmail($thisUser);
}
return $user;
}
This is my resend function and html code to store the email:
protected function resend(Request $request)
{
$user = Account::where('email', $request->email)->first();
if($user){
$user->verifyToken = Str::random(40);
$user->save();
$this->sendEmail($user);
return back()->with('user',$user)->with('success', 'A link has been sent to your email');
}
}
<form action=" {!! route('resendEmail') !!}" method="POST">
#csrf
<input type="hidden" name="email" value="{{ $user->email }}">
<button class="btn btn-default db" type="submit" value="Submit">Resend Verification Link</button>
</form>
The error is pointing at the hidden input with value $user->email while the register function works fine and creates user in database.

How to enter session code number in laravel?

After register redirect to this page.
I want enter this code. (Of course mobile number and the code save in database and send a sms to mobile).
How to enter session code number?
Code
web.php
Route::get('/code', 'HomeController#code')->name('code');
Route::post('/send', 'HomeController#send')->name('send');
RegisterController.php
public function register(Request $request, User $user)
{
$code = rand(10000,99999);
$user = \App\User::create([
'first_name' => $request->first_name,
.
.
.
.
return redirect()->route('code',['mobile'=>$request->mobile]);
HomeController.php
public function code()
{
return view('Home.send');
}
public function send(Request $request)
{
$mobile = $request->session()->get('mobile');
$user = User::whereCode($request->code)
->whereMobile($mobile)
->firstOrFail();
if($user){
$user->verification_code = 1;
$user->save();
alert()->success('ok');
return redirect()->back();
} else {
alert()->error('error');
return redirect()->back();
}
}
send.blad,php
<form action="{{ route('send') }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="code">Code</label>
<input type="text" class="form-control" name="code" id="code">
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger" id="btn-ok">OK</button>
</div>
</form>
I get this error
404
I have verification_code in users table. I want In case of enter true code and mobile number, verification_code change to 1
Take a look on Retrieving Single Models - Not Found Exceptions.
The firstOrFail method will retrieve the first result of the query;
however, if no result is found, a
Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.
If the exception is not caught, a 404 HTTP response is automatically sent
back to the user. It is not necessary to write explicit checks to
return 404 responses when using these methods.
So, you can try catch the exeption:
try {
$mobile = $request->session()->get('mobile');
$user = User::whereCode($request->code)
->whereMobile($mobile)
->firstOrFail();
$user->verification_code = 1;
$user->save();
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
return redirect()->back()->with('alert', 'error');
}
return redirect()->back()->with('success', 'ok');
Or otherwise use first instead of firstOrFail, which will return null if there is no record that meets the where conditions:
$mobile = $request->session()->get('mobile');
$user = User::whereCode($request->code)
->whereMobile($mobile)
->first();
if(empty($user)){
return redirect()->back()->with('alert', 'error');
}
$user->verification_code = 1;
$user->save();
return redirect()->back()->with('success', 'ok');

Preventing login with Laravel's Auth

I'm trying to prevent the user from logging in under some conditions.
My idea is to perform some additional checks after using Laravel's Auth system.
As for the login / register and recover password systems, everything works fine. But I can't seem to be able to log out the user and show a custom error in the login page.
All I want to do is to show a custom "your account was suspended" message under the "email address" field, after verifying if the user was suspended or not.
My code (HomeController), as well as some of my solutions:
public function index(Request $request)
{
// After Laravel logs the user through its authentication system
$user = Auth::user();
if (!isset($user)) {
return redirect('/');
} else {
// we perform some checks of our own
if ($user->suspended != 0) { // suspended by an administrator
$error = trans('errors_login.SUSPENDED_BY_ADMIN');
// return redirect()->route('logout', array('error_msg' => $error));
// return redirect()->route('logout')->withErrors('email','There was an error'); // trying to replace the "email" error
Auth::logout();
$error = ['loginError'=> trans('errors_login.SUSPENDED_BY_ADMIN')];
return view('auth.login', $error);
}
}
...
Just to clarify what the "logout" route is:
Route::get('/logout', '\App\Http\Controllers\Auth\LoginController#logout');
I'm using Laravel's generated login view:
...
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
Nothing seems to work.
I'm fairly new to Laravel, so I must be missing something.
Thank you.
Laravel's default login controller (App\Http\Controller\Auth\LoginController) uses a trait called AuthenticatesUsers under the hood.
So, whenever a user is authenticated, it calls an authenticated() method prior to sending the login response back, which means, you could probably do something like this.
In App\Http\Controller\Auth\LoginController add a new authenticated() method which overrides AuthenticatesUsers::authenticated().
protected function authenticated(Request $request, $user)
{
if ($user->suspended) {
Auth::logout();
return back()
->with('loginError', trans('errors_login.SUSPENDED_BY_ADMIN'));
}
return redirect()->intended($this->redirectPath());
}
I did it using this also :
protected function sendFailedLoginResponse(Request $request)//this will get triggered if the method above (attemptLogin(Request $request)) returns false.
{
$credentials = [
'email' => $request['email'],
'password' => $request['password'],
];
$valid = Auth::attempt($credentials);
if ($valid == false) { //if user credentials are incorrect
$errors = [$this->username() => trans('auth.failed')];
Auth::logout();
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
} else { // //if user credentials are correct check additional conditions
$user = User::where('email', $request->input('email'))->first();
if ($user->locked == 1) {
$errors = [$this->username() => trans('auth.locked')];
Auth::logout();
throw ValidationException::withMessages([
$this->username() => [trans('auth.locked')],
]);
} else {
$errors = [$this->username() => trans('auth.notactivated')];
Auth::logout();
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
}
}
Not sure if is good enough, but it also working.

laraevl 5.4 login with username or password (both)

I want to login using username or password in laravel 5.4, I tried some thing but nothing worked for me.
public function login(Request $request) {
$field = filter_var($request->input('login'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('login')]);
if ($this->auth->attempt($request->only($field, 'password')))
{
return redirect('/');
}
return redirect('/login')->withErrors([
'error' => 'These credentials do not match our records.sssss',
]);
}
I added this function in LoginController.php file, but I think it is not hitting this function, So how to do it ?
Try Something like this. You should override this code in LoginController.php
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|string',
]);
if (Auth::guard()->attempt(['email'=>$request->email,'password'=>$request-password], $request->remember)) {
if successfull, then redirect to intended location
return view('level1');
else
return view('manager');
}
//if successfull, then redirect back to login with the form data
return redirect()->back()->withInput($request->only('email','remember'));
}
return $this->sendFailedLoginResponse($request);
}
Laravel already provides authentication by default. In fact everything is configured already by Laravel. You just need to do the following for setting up authentication correctly in Laravel :
php artisan make:auth (this will create all the routes and view you need for authentication)
When a user is successfully authenticated, they will be redirected to the /home URI. You can customize the post-authentication redirect location by defining a redirectTo property on the LoginController, RegisterController, and ResetPasswordController:
protected $redirectTo = '/';
You can get the authenticated user in any controller by including the below code
use Illuminate\Support\Facades\Auth;
// Get the currently authenticated user...
$user = Auth::user();
// Get the currently authenticated user's ID...
$id = Auth::id();
You can check if user is authenticated or not by using the below code
use Illuminate\Support\Facades\Auth;
if (Auth::check()) {
// The user is logged in...
}
Add the below code to your Login Controller
public function username() {
return 'username';
}
if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
//user sent their email
Auth::attempt(['email' => $username, 'password' => $password]);
} else {
//they sent their username instead
Auth::attempt(['username' => $username, 'password' => $password]);
}
You can read more about laravel authentication and its customization's at https://laravel.com/docs/5.4/authentication
As #Gaurav Roy mentioned, you must first create Laravel's authentication routes by typing on console php artisan make:auth. You will notice that in Controllers directory exists a directory named Auth with some Controllers in it. Open LoginController and override username() function and return the column you wish to authenticate with the password. In your case:
private $value = 'username';
public function username()
{
return $this->value;
}
Now override attemptLogin(Request $request) function and try to login with username or email:
protected function attemptLogin(Request $request)
{
// try to login with username
$loginWithUsername = $this->guard()->attempt(
$this->credentials($request), $request->has('remember')
);
// if credentials with username are not valid, try with email
if (!$loginWithUsername) {
// replace username with email
$this->value = 'email';
$this->username();
// add input value to email
$request['email'] = $request['username'];
unset($request['username']);
return $this->guard()->attempt(
$this->credentials($request), $request->has('remember')
);
}
return $loginWithUsername;
}
Now go to resources->views->auth, open login file and replace email's input so it can accept the username. For example:
From:
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
To:
<input id="username" type="text" class="form-control" name="username" value="{{ old('username') }}" required autofocus>
Now you can login with username or email!
If you want both username and email then in your LoginController you can try something like:
return property_exists($this, 'username') ? $this->username : 'email';

custom Authentication on Laravel

I want to write a custom authentication on laravel, I want to know should I use default auth or should I write a new?
my auth workflow is:
Step 1- Show email form (in this step we will get just email address)
Step 1-2- check for email existence and if email exists we will go to Step 2 and if not exists I should redirect user to Step 3
Step 2- get the user password (validate password and if everything was OK user will login)
Step 3- show registration form and fill the email with entered user email address (validate form and register user)
What is your solution ?
//Login rules
public function user_login_rules(array $data)
{
$messages = [
'email.required' => 'Please enter your email'
];
$validator = Validator::make($data, [
'email' => 'required'
], $messages);
return $validator;
}
Your post method
public function postSignIn(Request $request)
{
$request_data = $request->all();
$validator = $this->user_login_rules($request_data);
if($validator->fails())
{
return redirect()->back()->withErrors($validator)->withInput();
}
else
{
$email = $request_data['email'];
$user_details = User::where('email', $email)->first();
if(count($user_details) > 0)
{
$credentials = array('email'=> $email ,'password'=> $request_data['password']);
if ($this->auth->attempt($credentials, $request->has('remember')))
{
//Login successful
return redirect()->to('/home');
}
else
{
$error = array('password' => 'Please enter a correct password');
return redirect()->back()->withErrors($error);
}
}
else
{
//Display register page with email
return view('register')->with('email', $email);
}
}
}

Categories