how to change the value of a column in laravel on logout - php

i have a column called active_user to show when a user is online(1). When i log a user in i set the active_user column to 1 but when i log the user out and check active_user it still shows online(1). what i want is that when i click the logout button the aactive_user column will change to offline(0) and also update it to the database. my login is below.
public function postSignIn(Request $request) {
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
$user=User::whereRaw('email=?',[Input::get('email')])->first();
//this is where i set the active_user to 1
$user->active_user=1;
$user->save();
if($user!=null){
switch($user->role_id){
case 1:
if($user->status==0){
session()->flash('flash_message_error', ' Your Account has been deactivated. Contact the administrator');
return Redirect::to('admin/login');
}
return redirect()->route("index");
break;
then below is my logout function
public function LogOut($id) {
$user = User::find($id);
$user->active_user=1;
$user->save();
Auth::logout();
return redirect('admin/login');
}
in the logout function i want to change the active_user back to offline(0) but i keep getting an error "Missing argument 1 for App\Http\Controllers\AdminController::LogOut()"

Your route logout is now expecting an id attribute passed to it. This seems wrong to me as it is the authenticated user that you want to apply this logic to, having to pass their id to logout is unnecessary. For example if your logged in user has an id of 1, to logout with your code they would need to go to a url such as:
http://myapp.app/logout/1
Instead, use the Auth implementation to modify the user.
// Remove requirement for ID as a parameter
public function LogOut() {
$user = Auth::user();
$user->active_user=1;
$user->save();
Auth::logout();
return redirect('admin/login');
}

Related

Comment with Auth in laravel

I want the user to only post a comment when logged in. Otherwise a massege appears 'You must be logged in to post a comment'. If I logged in it works if not it doesnt just redirect back!
I solved it. The problem was that the PostCommentsController was in the admin middleware where you have to logged in to see If you are an admin. And if you not logged in redirect to index.
the Controller:
public function store(Request $request)
{
if (Auth::check()) {
$user = Auth::user();
$data = [
'post_id' => $request->post_id,
'author' => $user->name,
'email' => $user->email,
'body' => $request->body
];
Comment::create($data);
$request->session()->flash('comment_success','Your comment have been submited and is waiting moderation');
return redirect()->back();
} else {
$request->session()->flash('login','You must be logged in to post a comment');
return redirect('/login')->back();
}
}
public function store(Request $request)
{
if (!Auth::check()) {
$request->session()->flash('login', 'You must be logged in to post a comment');
return redirect()->back();
}
$user = Auth::user();
$data = [
'post_id' => $request->post_id,
'author' => $user->name,
'email' => $user->email,
'body' => $request->body
];
if (Comment::create($data)) {
$request->session()->flash('comment_success', 'Your comment have been submitted and is waiting moderation');
return redirect()->back();
}
$request->session()->flash('comment_error', 'Your comment does not submited. Try again!!');
return redirect()->back();
}
In your else statement, just use this code return redirect('/login'); using back() function will redirect user back.
Laravel has the built in Auth system, if you use that you can use constructors like the example from my project.
public function __construct()
{
$this->middleware('auth');
}
This just says that the user cannot access any of the methods in this class without being logged in. If they are not logged in it will redirect them back to the login page. You can also have, in your views, #auth and #guest. I use this to show info on private information e.g. private servers can only be seen by the logged in user.
If you have any other questions I may be able to answer, let me know, I would love to help!
https://laravel.com/docs/5.6/authentication

What is the best way to check active status for user whille loging in native multi-auth Laravel?

I am using laravel multi-auth. I have a table column called status. At the time of login in, I want compare user whether it is active or in active. If active only login and if not give a message 'inactive account, please contacct to administrator'.
Here is my login controller.
<?php
namespace Modules\University\Http\Controllers;
class LoginController extends Controller
{
protected $redirectTo = '/university';
public function __construct()
{
$this->middleware('guest:university', ['except' => ['universityLogout']]);
}
public function showLoginForm()
{
return view('university::login');
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
//attempt to log the user in
if(Auth::guard('university')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
/****Here I want check whether university status is active or not and give message if not else login*****/
return redirect()->intended(route('university.dashboard'));
}
Session::flash('failed', 'Login credential incorrect!');
return redirect()
->back()
->withInput($request->only('email', 'remember'));
}
public function universityLogout(Request $request)
{
Auth::guard('university')->logout();
return redirect(route('university.login'));
}
}
Thanks in advance.
if(Auth::guard('university')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
if( Auth::guard('university')->user()->status == 'inactive')
{
return redirect()->route('university.dashboard-inactive');
}
return redirect()->intended(route('university.dashboard'));
}
If you want to check before login is attempted you may just query the DB by the email address to check its status and then procceed with login attempt if the status is active. If you want to login anyhow regardless of the status and redirect only if inactive, something like above would work.

Set the active status of a user in the credentials and still return an activation message in Laravel 5.1

I wanted to find out how I would do as requested in the subject line, as the code below works fine but the user is logged in before checking the $user->Activated status. Here is some code to illustrate:
AuthController
public function authenticated(Request $request, User $user)
{
if ($user->Activated) {
return redirect()->intended($this->redirectPath());
} else {
Auth::logout();
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'activated' => 'You need to activate your account to login'
]);
}
}
Preferably I would like to do the following:
AuthController
public function getCredentials(Request $request)
{
$credentials = $request->only($this->loginUsername(), 'password');
return array_add($credentials, 'Activated', '1');
}
But then the only message that gets returned is "These credentials do not match our records.", instead of "You need to activate your account to login". Also how would I update a LoginStatusId once the user is logged in, currently I do it like this:
AuthController
public function authenticated(Request $request, User $user)
{
if ($user->Activated) {
$user->LoginStatusId = 1;
$user->save();
return redirect()->intended($this->redirectPath());
} else {
Auth::logout();
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'activated' => 'You need to activate your account to login'
]);
}
}
Is there a better place to set the $user->LoginStatusId once they login, or is this the best place to put it?
Open this file vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
Add this block of code inside postLogin
// If activated is equal to 1, user allowed to login or throw an credential mismatch error
$userData = User::select('activated')->where('email', $request['email'])->first();
if ($userData->activated == 1) {
$request['activated'] = $activated;
}
$credentials = $this->getCredentials($request); //add these code before this line
And add 'activated' to getCredentials method. It will look like this:
protected function getCredentials(Request $request)
{
return $request->only($this->loginUsername(), 'password', 'activated');
}
You can check user login status anywhere just using this Auth::user(). No need to store login status by yourself. As example in any controller you can write this:
if(Auth::user()){
// do this;
}else{
// do that;
}

Laravel 5.1: Auth::attemp() success but Auth::check() return false

I already looking for related issue with this but didn't solved yet.
link 1, link 2, link 3
Auth::attempt() is success
try to register session after Auth::attempt() is success
remember_token field on users table is always null
This is my code:
AuthController:
protected function login(Request $request){
$result = [];
$rules = ['email' => 'required|email', 'password' => 'required|alphaNum|min:3'];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()) {
$result['message'] = 'Login Failed';
}else{
$userdata = ['email' => $request->email, 'password' => $request->password];
if (Auth::attempt($userdata, $request->has('auth_remember'))) {
// dd(Auth::user()); << THIS DATA IS EXIST
// $request->session()->push('user.id', Auth::user()->id);
// $request->session()->push('user.name', Auth::user()->name);
// $request->session()->push('user.email', Auth::user()->email);
// dd($request->session()->all()); << THIS DATA IS EXIST
$result['message'] = 'Login successfull. Redirecting ...';
}else{
$result['message'] = 'User not found';
}
}
echo json_encode($result);
}
I have a middleware Auth when I go to http://.../dashboard, but...
Auth::check() return false
$request->session()->has('user') return false
Auth Middleware:
public function handle($request, Closure $next){
if($this->auth->viaRemember()) return $next($request);
if($this->auth->guest()){
if($request->ajax()){
return response('Unauthorized.', 401);
}else{
return redirect()->guest('login');
}
}
return $next($request);
}
storage/framework/session already set to 777
file session are generated
app timezone already match with server settings and database settings
Any help would be appreciated.
Why are you adding logged user data manually to the session, You can user use Auth::user() to get user data anytime after attempt
Delete this lines:
$request->session()->push('user.id', Auth::user()->id);
$request->session()->push('user.name', Auth::user()->name);
$request->session()->push('user.email', Auth::user()->email);
and verify with dd($request) the auth_remember
I think I resolve this issue.
Laravel authentication are not working when using Ajax. Just follow the documentation from http://laravel.com/docs/5.1/authentication and all should be worked!
But it's strange! Authentication with ajax are worked well in my localhost but no when I upload it to server.

Passing a user ID from a button to disable that user in the database

I want to disable a users account by changing their activation field from 1 to 0 if a button is clicked.
This is my Route:
Route::post('admin/useradmin/{id}', array('as' => 'user-admin-disable-post', 'uses' => 'AdminController#postDisable'))->before('auth');
My Controller:
public function postDisable($id)
{
$user = User::find($id);
$user = $user->first();
$user->activate = 0;
if($user->save())
{
return Redirect::route('user-admin')
->with('global', 'The users account has been disabled');
}
return Redirect::route('user-admin')
->with('global', 'Error disabling user account');
}
The View, this button that will be clicked, and then pass the users id to the controller to perform the action:
Disable
It's giving me a not found error when I click the button, and I see that the function is not being executed, how can I fix this?
The method User::find($id) will already return the user object, no need to call $user->first(); afterwards. – #martinstoeckli
I also changed the post to get in my routes.
This solved the issues I was having

Categories