Laravel: Alternate to Session, to show logged in user data - php

I want to show logged in user data with the user of Laravel in-built class. I have used 'Session' to show the data which makes the code bulky and is not a good practice because we have to always put and flush data.
Here are my codes:
public function login(Request $req) {
$this->validate($req, [
'email' => 'required',
'password' => 'required',
]);
$email = $req->input('email');
$password = $req->input('password');
$checkLogin = DB::table('admin')->where(['email'=>$email,'password'=>$password])->first();
if(count($checkLogin) > 0){
Session::put('admin-name', $checkLogin->name);
Session::put('admin-email', $checkLogin->email);
Session::put('admin-address', $checkLogin->address);
Session::put('admin-mobile',$checkLogin->mobile);
Session::put('admin-dob',$checkLogin->dob);
Session::put('admin-pic',$checkLogin->photo);
Session::put('admin-password',$checkLogin->password);
return view('admin');
}
else {
return Redirect::route('admin-login')->with(['error'=> "Invalid email or Password!!"]);
}
}
View:
<div class="col-md-7 col-sm-7 col-xs-7 round-img-neighbour">
<p>{{Session::get('admin-name')}}</p>
<small><cite title="">{{Session::get('admin-address')}} <i class="glyphicon glyphicon-map-marker"></i></cite></small>
</div>

So you are not logging in the admin:
First log him in then access his datas:
public function login(Request $req) {
$this->validate($req, [
'email' => 'required',
'password' => 'required',
]);
$email = $req->input('email');
$password = $req->input('password');
$checkLogin = DB::table('admin')->where(['email'=>$email,'password'=>$password])->first();
if(count($checkLogin) > 0){
$adminData = Auth::loginUsingId($checkLogin->id);
return view('admin', compact('adminData'));
}
else {
return Redirect::route('admin-login')->with(['error'=> "Invalid email or Password!!"]);
}
}
In view u may access like this:
<div class="col-md-7 col-sm-7 col-xs-7 round-img-neighbour">
<p>{{$adminData->admin-name}}</p>
<small><cite title="">{{$adminData->admin-address}} <i class="glyphicon glyphicon-map-marker"></i></cite></small>
</div>

You can simply use
Auth::user();
for get the logged in user information
for ex.
if(Auth::check())
{
$loggedin_user = Auth::user();
}

Related

How can I decrypt password to login in laravel?

While changing the password I am using this function
public function passwordChange(Request $request, $userId)
{
$user = User::find($userId);
$user->password = Crypt::encrypt(Input::get('password'));
$user->save();
return redirect('my-profile');
}
So in my mongoDb database password insert in encrypted form, So whenever I have to login in system at that time how can I compare my password with password of database
public function authenticate(Request $request)
{
$rules = array(
'company_email' => 'required|email|exists:users,company_email',
'password' => 'required|string|max:20|min:4',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return view('pages.login')->with('v_errors', $validator->errors()->messages());
}
else
{
//get email and query
$authenticateMe = $request->only('company_email', 'password');
$user = User::where($authenticateMe)->first();
if (empty($user))
{
return view('pages.login')->with('not_exists', 'true');
}
//session set
// Session::put('key', $user->username, $user->file);
Session::put('key', ['username' => $user->username, 'email' => $user->company_email, 'userId' => $user->id, 'profilePicture' => $user->file]);
return redirect('my-profile');
}
}
I am not using php artisan make:auth
will anyone please help??
Instead of encrypting the password, use hashing. Laravel has its own documentation about how to use that: https://laravel.com/docs/5.8/hashing
Simply you can not decrypt an encrypted password but you can check user credentials by adding an array of user email & password to Auth::attempt() function Here is a link to the description: https://laravel.com/docs/5.8/authentication#authenticating-users?
Here is your function using Auth::attempt():
public function authenticate(Request $request)
{
$rules = array(
'company_email' => 'required|email|exists:users,company_email',
'password' => 'required|string|max:20|min:4',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return view('pages.login')->with('v_errors', $validator->errors()->messages());
}
else
{
//get email and query
$authenticateMe = $request->only('company_email', 'password');
if (Auth::attempt($authenticateMe)) {
$user = User::find(Auth::user()->id);
//session set
// Session::put('key', $user->username, $user->file);
Session::put('key', ['username' => $user->username, 'email' => $user->company_email, 'userId' => $user->id, 'profilePicture' => $user->file]);
return redirect('my-profile');
}else{
return view('pages.login')->with('not_exists', 'true');
}
}
}
And do not forget to add use Auth; to the function controller

Logout user from all browser when password is reset in laravel 5.6

When the user changes their password, they get Logged Out from the browser. However, if they are logged into another browser at the same time they stay logged in on the other browser.
I want to log out the user from all browsers they are logged into when they reset their password.
Here login controller.
function checklogin(Request $request)
{
$this->validate($request, ['email' => 'required|email', 'password' => 'required|string|min:3']);
$user_data = array(
'email' => $request->get('email') ,
'password' => $request->get('password')
);
$remember_me = $request->has('remember') ? true : false;
if (Auth::attempt($user_data, $remember_me))
{
return redirect()->intended('dashboard');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
send mail function as below
function sendEmail(Request $request)
{
$this->validate($request, ['email' => 'required|exists:users']);
$email = $request->email;
$name = User::where('email', $email)->first();
$name = $name->name;
$token = Password::getRepository()->createNewToken();
$link = url("password/reset?email=$email&token=$token");
$value = Password_resets::where('email', $email)->first();
if (isset($value))
{
Password_resets::where('email', $email)->update(['email' => $email, 'token' => $token]);
}
else
{
Password_resets::insert(['email' => $email, 'token' => $token]);
}
Mail::to($email)->send(new \App\Mail\ResetPassword($link, $name));
return redirect()->back()->with('success', 'Please check your Email for Password Reset');
}
password reset function as below
function resetpasswordchange(Request $request)
{
$passwordtoken = $request->input('passwordtoken');
$email = $request->input('email');
$user_password = $request->input('user_password');
$users['user'] = Password_resets::where('token', $passwordtoken)->where('email', $email)->get();
if (empty($users['user'][0]))
{
$settoken = '0';
}
else
{
$settoken = $users['user'][0]->token;
}
if (($settoken) == $passwordtoken)
{
$update = array(
'password' => bcrypt($user_password) ,
);
User::where('email', $email)->update($update);
/* Auth::logout();
auth()->logoutOtherDevices(bcrypt($user_password),'password');*/
return redirect()->route('login')->with('success', 'Password has been Updated.');
}
else
{
return redirect()->back()->with('error', 'Token & Email Not Match!.');
}
}
How I can logout the user from all browsers who they are logged already ?
Open App\Http\Kernel and inside the protected $middlewareGroups property uncomment the \Illuminate\Session\Middleware\AuthenticateSession::class middleware. This compares the password hash of the user to see if the session is valid or not.

how to make custom login in laravel 5.6?

I have used my own custom login without using auth. Here is my code
public function userLogin(Request $request){
if($request->isMethod('post')){
$data = $request->input();
$this->validate($request, [
'uemail'=> 'required|email',
'user_type'=> 'required',
'user_id' => 'required',
'upassword' => 'required|min:6',
],
[
'uemail.email' => 'Email must be valid',
'uemail.required' => 'Email is required',
'user_type.required' => 'Type is required',
'user_id.required' => 'Name is required',
'upassword.required' => 'Password is required',
'upassword.min' => 'Password must be at least 6 characters',
]);
$user_type = $data['user_type'];
$user_id = $data['user_id'];
$uemail = $data['uemail'];
$upassword = $data['upassword'];
$hashPass = bcrypt($upassword);
DB::enableQueryLog();
$user1 = User::where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->firstOrFail();
$user = DB::table('users')->where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null);
// $query = DB::getQueryLog();
// $query = end($query);
$isPasswordCorrect = Hash::check($upassword, $user1->password);
if($user == null){
echo "Failed"; die;
}
if($user->exists() && $isPasswordCorrect){
echo "Success"; die;
Session::put('userSession',$user1->email);
Session::put('loginSession',$user_type);
Session::put('idSession',$user1->user_id);
return redirect('/user/dashboard');
} else {
return redirect('/user')->>with('flash_message_error','Invalid Login Credentials..');
}
}
return view('death_notice.user_login');
}
This is my login function. But its not working. When the credentials is right it redirects to dashboard i.e that's correct, but when the email or password or other credentials is wrong it showing error message. But when if the user enter such data which is not in the database then it must show message that user doesn't exists. but its going to page not found error...
I want to have the solution of this problem.
Okay, first confirm that, you have a route like '/user' defined in your web.php
You haven't used get() in $user eloquent
$user = DB::table('users')->where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->get();
And it shows 404 not found error because you have used firstorFail() it will fail on no record matching and will show 404 not found error so
$user1 = User::where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->first();
if(empty($user1))
{
echo "user doesn't exists";exit;
}
As per my understanding the query $user and $user1 is same so my suggestion would be to use only one
I made the following corrections:
$data = $request; is sufficient, you don't need to do $data = $request->input();
Check the count on the Eloquent query like this count($users->get()), to check if user was found.
public function userLogin(Request $request){
if($request->isMethod('post')){
$data = $request->input();
$this->validate($request, [
'uemail'=> 'required|email',
'user_type'=> 'required',
'user_id' => 'required',
'upassword' => 'required|min:6',
],
[
'uemail.email' => 'Email must be valid',
'uemail.required' => 'Email is required',
'user_type.required' => 'Type is required',
'user_id.required' => 'Name is required',
'upassword.required' => 'Password is required',
'upassword.min' => 'Password must be at least 6 characters',
]);
$user_type = $data['user_type'];
$user_id = $data['user_id'];
$uemail = $data['uemail'];
$upassword = $data['upassword'];
$hashPass = bcrypt($upassword);
DB::enableQueryLog();
$user1 = User::where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->firstOrFail();
$users = DB::table('users')->where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null);
// $query = DB::getQueryLog();
// $query = end($query);
$isPasswordCorrect = Hash::check($upassword, $user1->password);
if(count($users->get()) == 1){
$user1 = $users->first();
$isPasswordCorrect = Hash::check($upassword, $user1->password);
echo "Success"; die;
Session::put('userSession',$user1->email);
Session::put('loginSession',$user_type);
Session::put('idSession',$user1->user_id);
return redirect('/user/dashboard');
} else {
return redirect('/user')->>with('flash_message_error','Invalid Login Credentials..');
}
}
return view('death_notice.user_login');
}
I have not tested the code, but the idea should be clear.
Use following code to custom login. it's for, Ajax login, you can modify according to your requirements.
function userLogin(Request $request)
{
$auth = false;
$credentials = $request->only('email', 'password');
// if user login credentials are correct then users logged in
if (Auth::attempt($credentials, $request->has('remember')))
{
$auth = true; // Success
}
// returns json response if login credentials are correct.
if ($auth == true)
{
return response()->json([
'auth' => $auth,
'intended' => URL::previous(),
'msg'=>1,
'name' => Auth::user()->name
]);
} else { // returns json response if login credentials are incorrect
return response()->json(['msg' => 2]);
}
}

email duplicate login with api google in laravel because I have email in database same with google email akun

this is my controller, so i wanna to make this function to handle if email in database null so i can to insert but if email in database already available i can to update so not duplicate
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->stateless()->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect($this->redirectTo);
}
maybe in where the main must to be change please if you know help me, thanks
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('email', $user->email)->exists();
if ($authUser) {
return $authUser;
}
else {
return User::create([
'name' => $user->name,
'email' => $user->email,
'provider' => strtoupper($provider),
'provider_id' => $user->id
]);
}
}

Issues with validation of signup form

I'm adding a validation to my sign up form , the validate code is working but the errors don't shows up in the page
PHP code
public function postSignUp(Request $request)
{
$this->validate($request, [
'email'=> 'required|email|unique:users',
'first_name'=> 'required|max:120',
'password' => 'required|min:4'
]);
$email = $request['email'];
$first_name = $request['first_name'];
$password = bcrypt($request['password']);
$user = new User();
$user->email = $email;
$user->first_name = $first_name;
$user->password = $password;
$user->save();
Auth::Login($user);
return redirect()->route('dashboard');
}
Welcome.blade.php code
#section('content')
#if(count($errors) > 0)
<div class="row">
<div class="col-md-6">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
</div>
#endif
the php code is working because if i tried to register with an email that already taken it wont register but the error is that errors are not showing up in the welcome page
You are not passing the error messages back to the view.
As stated at documentation
if ($validator->fails())
{
return redirect('dashboard')->withErrors($validator);
}
You are checking with the function count($errors) but that is an object and it will always enter the condition since you are counting the object not the list itself.
Replace #if(count($errors) > 0) with #if(!empty($errors->all()))

Categories