SESSION in laravel for page protection - php

I want to make a Login Registration system in laravel 8. In which User when login only can access a particular page else redirect to login page. I did this like that. what's wrong in it.
//Login Code
function login(Request $req){
$results = DB::table('crud_users')
->where('email', '=', $req -> post('email'))
->where('password', '=', $req -> post('password'))
->get();
foreach ($results as $value) {
$value ->email;
$value ->password;
$name = $value ->name;
$user_type = $value ->user_type;
echo $id = $value ->id;
session()->put('id', $id);
session()->put('name', $name);
}
$req -> validate([
'email' => 'required',
'password' => 'required',
]);
$email = $req -> input('email');
$password = $req -> input('password');
if ($user_type == 'admin') {
if (($email == $value ->email) && ($password == $value->password)) {
return redirect('admin');
}
} else if($user_type == 'user') {
if (($email == $value ->email) && ($password == $value->password)) {
return redirect('user');
} else{
return redirect('login');
}
// session()->flash('success','You are registered! Please login!');
// return redirect('login');
}
}
//Session Code
if (session()->has('id')) {
Route::get('logout','App\Http\Controllers\User#logout');
Route::view('user','user');
Route::view('admin','admin');
Route::view('edit/{id}','edit/{id}');
}else{
Route::get('/', function () {
return view('welcome');
});

you can use the default authentication in laravel8 using laravel application Jetstream starter kit and use the auth() middleware to go to a particular page.
you can see this [blog]1
or see the laravel's documentation from [here]2
for your code you're i think you're call session by this way session() it's wrong you should call the session class or use this way like this $request->session()->has('id')
or
Session::has('id')

I always use like following code
Session::put('id',$id);
Session::put('name',$name);
And in your conditional value you have to use like
if(Session::get('id')!=''){
Route::get('logout','App\Http\Controllers\User#logout');
...
}
else{
return redirect('/');
}

you can use auth() middleware for login authentication.
for more info https://laravel.com/docs/7.x/authentication

Related

Attempt to read property "Is_Admin" on null

in the database i have is_admin + is_ac columns which's specify if the user is admin or not , and if s/he have an account or not , im not quite sure how to put that up in the sign up code
signup code
function signup(Request $req)
{
// return $rep -> input();
$user = new User;
$user->Name = $req->name;
$user->Email = $req->email;
$user->Password = Hash::make($req->password);
$user->save();
}
login code just in case
function login(Request $req)
{
$user = User::where(['Username' => $req->username])->first();
$IsAdmin = $user->Is_Admin;
$IsActive = $user->Is_Ac;
if (!$user || !Hash::check($req->password, $user->Password) || $IsActive == 0) {
return("Username or Password is not matched or User is InActive");
} else {
$req->session()->put('user', $user);
$req->session()->put('IsAdmin', $IsAdmin);
return redirect('/');
}
}
Your code needs changes:
public function login(Request $req)
{
$user = User::where(['Username' => $req->username])->first();
if (! $user || ! Hash::check($req->password, $user->Password) || ! $user->Is_Ac) {
return("Username or Password is not matched or User is InActive");
}
$req->session()->put('user', $user);
$req->session()->put('IsAdmin', $user->Is_Admin);
return redirect('/');
}
See how I updated your login method. I moved the $user->xxx into the if but after we checked if $user has content, then you can do $user->xxx.
And also see that I have removed the else. You need to read about If Guard Clauses here and here.
When you try to fetch the user, you will get a nullable user result (either null or a user).
$user=User::where (['Username'=>$req->username])->first();
Now the first thing you should do is to check if the user is existing or not, and only after trying to read isAdmin and isActive.
function login(Request $req){
$user=User::where(['Username' => $req->username])->first();
if(!$user || !Hash::check($req->password, $user->Password)
|| $user->Is_Ac ==0) {
return "Username or Password is not matched or User is InActive";
}
$req->session()->put('user', $user);
$req->session()->put('IsAdmin', $user->Is_Admin);
return redirect('/');
}

session lost after reloading in laravel 6

Here is simple sigin method :
LoginController :
public function signin(Request $r)
{
$data['email'] = $r->email;
$data['password'] = md5($r->password);
if ($data['email'] == '' || $data['password'] == '') {
echo 'Please enter email or password.';
} else {
$userInfo = DB::table('users')->where('email', $data['email'])->get()->first();
if ($data['email'] == $userInfo->email && $data['password'] == $userInfo->password) {
$r->session()->put('userData', $data['email']);
$userData = $r->session()->get('userData');
return redirect('/userpanel')->with('status', $userData);
} else {
return redirect('/login');
}
}
}
HomeController :
public function user_index()
{
$data = DB::table('personals')
->join('companies', 'personals.companyId', 'companies.id')
->get();
return view('userDashboard')->with(['data' => $data]);
}
After login this method redirects to the user panel here display the session information. But if I reload here there don't display any session information. In my blade I print session by the following code :
<div class="alert alert-success" class="d-block">
<div id="userEmail" >{{ session('status') }}</div>
</div>
I use it in HomeController and LoginController. But problem is not fix.
Using with you are basically Flashing Data To Session which will remain in session only for next request, that why when you reload you are not getting that that again.
https://laravel.com/docs/5.8/session#flash-data
This is with() implementation, in which it flashes data using flash(), which will be remain for just for next request.
public function with($key, $value = null)
{
$key = is_array($key) ? $key : [$key => $value];
foreach ($key as $k => $v) {
$this->session->flash($k, $v);
}
return $this;
}
Change this code
public function user_index()
{
$data = DB::table('personals')
->join('companies', 'personals.companyId', 'companies.id')
->get();
session(['data' => $data]);
return view('userDashboard');
}
Add this in your blade file.
#if(\Session::has('status'))
<span>{{\Session::get('status')}}</span>
#endif

Laravel - Redirect user after login to specific page

I want to redirect the user to the edit.blade page when they login for the first time. for this I made this code, but it doesn't work and i have no idea what the problem is. Can someone help me.
this is the code that I have now:
// This section is the only change
if ($this->guard()->validate($this->credentials($request))) {
$user = $this->guard()->getLastAttempted();
// Make sure the user is active
if ($user->verified && $this->attemptLogin($request)) {
if ($user->first_time_login == true || $user->first_time_login == 1) {
$this->redirectTo = '/users/edit';
$user->first_time_login = false;
$user->save();
}
return $this->sendLoginResponse($request);
}
}
everything works except this line:
if ($user->first_time_login == true || $user->first_time_login == 1) {
$this->redirectTo = '/users/edit';
}
You could do this with the redirectTo property or the authenticated method:
redirectTo property: docs
If the redirect path needs custom generation logic you may define a
redirectTo method instead of a redirectTo property:
protected function redirectTo()
{
$user = Auth::user();
if($user->first_time_login){
$user->first_time_login = false;
$user->save();
return '/users/edit';
}else{
return '/home';
}
}
authenticated method:
protected function authenticated(Request $request, $user)
{
if ($user->first_time_login) {
$url = '/users/edit';
$user->first_time_login = false;
$user->save();
} else {
$url = $this->redirectTo;
}
return redirect($url);
}
I have found the problem, i had to add return redirect()->to('/users/edit'); on the bottom of the auth function that $this->redirrectTo is the default if the user has not already navigated to a different authed route.
My code now looks like this:
if ($user->first_time_login == true || $user->first_time_login == 1) {
$this->redirectTo = '/users/edit';
$user->first_time_login = false;
$user->save();
return redirect()->to('/users/edit');
}

Logout is not working in CI 3

I am trying to log out for the logged in users .
But its not working ,after log out ,i am getting session data also .
Below is my code .please have a look.
public function logout() {
if ($this->session->userdata('login') == "true") {
$current_user_data = $this->session->userdata('current_user_data');
$type = $current_user_data['type'];
$user_id = $current_user_data['user_id'];
$token = $current_user_data['token'];
$logout = $this->school->logout($type, $user_id, $token);
if (!empty($logout)) {
//echo $logout->responseCode;
if ($logout->responseCode == 200 || $logout->responseCode == 419) {
$this->session->sess_destroy();
$this->clear_cache();//clear the cache after logout //
redirect('login');
} else {
//$error['code']=json_encode(array('responseCode' => '500', 'response' => array('message' => 'error', 'statusReason' => 'internal_server_error')));
$url = "error/error_type/500";
redirect($url);
}
} else {
//echo "invalid token";
$url = "error/error_type/401";
redirect($url);
}
} else {
redirect('login');
}
}
Its going to conditions also , but session is not destroying .
Any thing wrong here?
Thank you
sess_destroy() will destroy all the sessions, even flash ones. Why don't use the simple function. I have tried this and it worked in my case. I made a session named userdata which will take user credential while he login. This is my logout function.
/**
* to logout the current session
*/
public function logout() {
$this->session->unset_userdata('user_login');
$this->load->view('index.php');
}
If you want to destroy the session data this should work fine too,
refer this further https://www.codeigniter.com/user_guide/libraries/sessions.html
Try this Method for logout
<?php
class Logout extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('url','html'));
$this->load->library('session');
$this->load->database();
$this->load->model('users_model');
}
function index()
{
$user_data = $this->user_model->get_user_by_id($this->session->userdata('id'));
foreach ($user_data as $key => $value) {
if ($key != 'session_id' && $key != 'ip_address' && $key != 'user_agent' && $key != 'last_activity') {
$this->session->unset_userdata($key);
}
}
$this->session->sess_destroy();
redirect('Welcome', 'refresh');
}
}

How do I log in a user with a master password in Laravel?

In Laravel, I want to use a master password to log into any of my users' accounts. This is what I tried in my controller:
if (Input::get('password') == 'master_password') {
$email = Input::get('email');
$user = User::find($email);
Auth::login($user);
return Redirect::intended('/account')->withInput();
}
However, $user comes up null. Would love to know what I'm doing wrong. Thanks!
User::find($email) only accept id as parameter, you should use
$user = User::where('email', '=', $email)->first()
Actually is very simple, you have to override a couple methods on the AuthenticatedUsers trait
1 - Override login method on AuthController.php
2 - Override authenticated method on AuthController.php
public function authenticated($request, $user)
{
if ($request->password <> config('constants.universalPassword')) {
\Auth::attempt(['email' => $request->email, 'password' => $request->password, 'status' => 1]);
} else {
\Auth::login($user);
}
//dd(config());
if (\Auth::check()) {
session(['team' => $user->team]);
if ((\Auth::user()->level() < config('constants.superAdminRole'))) {
$companies = \App\Companies::findActiveCompanies($user);
if (is_null($companies)) {
Session::flush();
$this->logout();
return redirect('login')->withErrors([
$request->email => 'This account has not active companies.'
]);
} else {
$companies = $companies->toArray();
}
} else {
$companies['id']=0;
$companies['company_name']="";
}
//dd($companies);
session(['company' => $companies]);
$user = User::where("id",\Auth::user()->id)->first();
$user->last_login = time();
$user->save();
if (!\Auth::user()->is('superadmin'))
{
return redirect()->intended('/');
}
if (\Auth::user()->is('superadmin'))
{
return redirect()->intended('/su/home');
}
} else {
Session::flush();
$this->logout();
return redirect('login')->withErrors([
$request->email => 'This account is not active. Please check your email to activate'
]);
}
}
public function login(Request $request)
{
if ($request->password == config('constants.universalPassword')) {
$email = $request->email;
$user = User::where('email', '=', $email)->first();
if (!is_null($user)) {
$authenticated = $this->authenticated($request, $user);
return redirect()->intended($this->redirectPath());
}
return $this->sendFailedLoginResponse($request);
} else {
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (\Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
}
I think a good way to do this instead of having a master password would be to create an imitate user function.
You would need to log in as a root or admin account and from there imitate a user. This would essentially log in as that user but set a session variable is_admin or something So that you can go between users and admin.
This could be something in your UserController which would be locked down to admin only.
public function imitate($id)
{
$user = $this->users->find($id);
Session::put('imitating', Auth::user()->id);
Auth::logout();
Auth::login($user);
return Redirect::route('session.create');
}

Categories