How can I handle Blocked Users in laravel - laravel

I need a help . Can u guide me How can i Show a message to blocked user that his account has been blocked . i m just rendering him to post page . but i want to show him some message that your account has been blocked or somthing like we do in validation messages . Please guide briefly .
public function login(Request $request)
{
$username= $request->username;
$user = User::where('username',$username)->first();
// return $user;
// return $user->id;
if($user != null){
$active = Activation::whereUserId($user->id)->first();
if($active->completed==0){
return redirect('/posts');
}

You need to use session. One way to do that:
return redirect('posts')->with('error', 'Your account is blocked');
And in a view after redirection:
#if (session('error'))
{{ session('error') }}
#endif
If you don't want to redirect the user, just pass a variable into the view:
return view('login.form', ['notActivated' => $active->completed === 0])
And in the view:
#if ($notActivated)
Your account is blocked
#endif

Related

Redirecting to a laravel's web route from a vue component without using vue-router

I know this question seems to be redundant, but I can't find the solution anywhere.
I'm using laravel-vujs mix and integrated the web routes and the api routes in the same project.
Now, I'm trying to create a register api function called registernative wherein it authenticates user and returns some status code.
for example
public function registernative(Request $request) {
$user = User::where('email', '=', $request->email)->first();
$response = [];
if(!$user) { //If user not exist, create
try {
$slug = strtolower($request->firstname) . '-' . strtolower($request->lastname) . '-' . time();
$user = new User();
$user->name = $request->firstname . ' ' . $request->lastname;
$user->email = $request->email;
$user->slug = $slug;
$user->password = Hash::make($request->password);
$user->save();
Auth::login($user);
$response = ['status'=>1, 'msg'=>'ok', 'data'=>$user->toArray()];
} catch (Exception $e) {
$response = ['status'=> -1, 'msg'=>'bad', 'data'=>[]];
}
} else { //If exist, login
$response = ['status'=> 0, 'msg'=>'user already exist', 'data'=>[]];
}
return response()->json( $response );
}
now in my vue component's register function, I checked the status returned from the api, if its 1, I have to redirect to the default dashboard page.
the default page's inline-template goes like this (I don't know if its necessary providing this, but I'll provide it anyway).
#section('content')
<defaultpage inline-template :user_session_details=" {{ Auth::user() }} ">
<div>
...
...
...
</div>
</defaultpage>
#endsection
I tried using window.location.replace('http://localhost/defaultpage'); but it says 'Unauthenticated'.
Why is it unauthenticated knowing I Auth::login($user) it after saving?
Sorry for bad english, not a native speaker.
Sessions are not available in laravel api. To use sessions you can define your route in web routes or add \Illuminate\Session\Middleware\StartSession::class to api's middlewares in App/Http/Kernel.php

How To Display Laravel Breeze Status Message

I'm using Laravel Breeze for authentication, and I'm facing a problem:
When user request a password reset link, I like to show him/her a success message, if we send email successfully. PasswordResetLinkController returns this:
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
When it goes back, it goes, for example, to home route. HomeController returns home.blade.php. When I try to display $status, which should be passed by PasswordResetLinkController, I got undefiened variable error. How can I get that message?
EDIT
PasswordResetLinkController.php
// This is the original store function came with Breeze.
// I did touch neither code nor the comments.
public function store(Request $request)
{
$request->validate([
'email' => 'required|email',
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
HomeController.php
public function index()
{
$baseData = $this->baseData();
$asset = $this->pickAssetRandom();
$publishings = $this->paginate($this->getPublishings, 12);
return view('pages.home', compact('publishings', 'baseData', 'asset'));
}
The $status is being set in the PasswordResetLinkController.
Specifically:
back()->with('status', __($status))
So, as you can see, it is returning the previous page and passing in status.
However, if $status == Password::RESET_LINK_SENT is false, then $status is not set, but the $errors['email'] is. You can see this on the ternary condition in your code.
Try:
dd($status == Password::REST_LINK_SENT);
before the return statement on the controller, if you get false then there will be no $status, and you will get the undefiened variable error.
You can account for this in your view:
#if ($status)
{{ $status }} // A link was sent
#endif
// no link sent and here are the errors.
#if ($errors->any())
#foreach ($errors->all() as $error)
{{ $error }}
#endforeach
#endif
Laravel docs on this: https://laravel.com/docs/8.x/passwords#resetting-the-password
Treat that status as a session and it will work
#if (session('status'))
<span class="alert alert-success">{{ session('status') ?? ''}} </span>
#endif

Display own post only and all posts for admin with laravel policy

How can I use Laravel Policy for displaying all products for admin and editor but own product for vendor?
I have done the following in view and view-any
public function viewAny(User $user)
{
return true;
}
public function view(User $user, Product $product)
{
return $user->id === $product->vendor_id;
}
And in my blade template, I have done this:
#foreach($allProducts as $productLists)
#can('view', $productLists)
codes....
#endcan
#endforeach
you can't do that in Policy ...
Policy is meant to give you True or False so the current user can access the action in your controller ...
in your case, both admin and regular user can access your controller's action, so policy is not the place for that ...
you can do it in controller, something like:
$currentUser = auth()->user();
if ($currentUser->is_admin) {
$values = DB::table('products')->get();
} else {
$values = DB::table('products')->where('owner_id', $currentUser->id)->get();
}
now you can pass the $values to your view ....
Why don't you use policy filters?
Just keep the code below on the top of your ProductPolicy
public function before($user, $ability){
if($user->role == 'admin' || $user->role == 'employee'){
return true;
}
}
You may want to visit laravel-documentation for more information.

How to get a custom message on fail login credentials in Laravel?

I use this code to check user credentials, but I can't figure how to change the code to get an error message when credentials fail. Used redirect and so on, but show nothing....
public function loginWithCredentials(Request $request) {
$signinEmail = $request->input('email');
$signinPassword = $request->input('password');
$user = new Users();
$errors = new MessageBag;
$user = $user
->where('email', '=', $signinEmail)
->get()->first();
if(empty($user)) {
$errors->add('error', 'Invalid credentials!');
return json_encode([
'error'=>true,
'messages'=>$errors
]);
}
$userdata = $user->toArray();
if(md5($signinPassword) != $userdata['password']) {
$errors->add('error', 'Invalid credentials!');
return redirect()->guest('auth/login');
}
Session::put('user',$userdata);
$errors->add('message0', 'Welcome ' . strtoupper($userdata['username']) . '!');
}
Now it just simple redirects me to a white page with the "invalid credentials" message. I want the message to be on login page.
Your code you has some flaws, consider fixing it.
Why are you mixing json response with html response?
Consider using bcrypt() for hashing your users passwords instead md5().
Add some sort of validation, Laravel has the built in validation.
Laravel ships with easy use login auth, take a look at.
So in your code needs some changes here it is:
public function loginWithCredentials(Request $request) {
$signinEmail = $request->input('email');
$signinPassword = $request->input('password');
$user = new Users();
$user = $user
->where('email', '=', $signinEmail)
->get()->first();
if(empty($user) || md5($signinPassword) != $user->password) {
return redirect()->back()->with('message', 'Invalid credentials!');
}
$userdata = $user->toArray();
Session::put('user', $userdata);
return view('view.name')->with('message', 'Welcome ' . strtoupper($userdata['username']) . '!');
}
Then in your view you write the success message like so:
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
this example is using blade, but should be similar to other views.
You just need to override AuthenticatesUsers Trait method named sendFailedLoginResponse like this:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
class LoginController extends Controller
{
use AuthenticatesUsers;
...
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
'your array key' => ['Place your custom message here'],
]);
}
...
}
That's It!
I hope this will help you. :)

How to change password in laravel-4 with auth

I am using laravel-4 auth component . I want to make a function which will change user password . I have my view as follows :
password - Text-box ;
new_password - Text-box;
confirm_new_password - Text-box
I also have checked manual for password reset , but in that doc(http://laravel.com/docs/security#password-reminders-and-reset) they are sending mail for password reset .
View is as follows :
#extends('layouts.main')
#section('title') Change Password
#stop
#section('content')
{{ Form::open(array('url'=>'users/user-password-change', 'class'=>'block small center login')) }}
<h3 class="">Change Password</h3>
<h6>Please change your password below.</h6>
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
{{ Form::password('password', array('class'=>'input-block-level', 'placeholder'=>'Old Password')) }}
{{ Form::password('new_password', array('class'=>'input-block-level', 'placeholder'=>'New Password')) }}
{{ Form::password('confirm_new_password', array('class'=>'input-block-level', 'placeholder'=>'Confirm New Password')) }}
{{ Form::submit('Register', array('class'=>'k-button'))}}
{{ Form::close() }}
#stop
Controller code is as follows :
public function postUserPasswordChange(){
$validator = Validator::make(Input::all(), User::$change_password_rules);
if($validator->passes()){
$user=new UserEventbot;
$user->password=Hash::make(Input::get('new_password'));
$user->save();
return Redirect::to('users/change-password');
}else {
return Redirect::to('users/change-password')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
}
}
Please help me on this , how to first match this password with database table users , and then the whole process .
Thank you .
To match current user password with password in database you can do something like this,
// retrieve the authenticated user
$user = Auth::user();
Retrieve the current password specified by the user inside the form,
$current_password = Input::get('current_password');
We can see if the current password has bee specified and check against the hashed password as follows,
if (strlen($current_password) > 0 && !Hash::check($current_password, $user->password)) {
return Redirect::to('/user/edit-profile')->withErrors('Please specify the good current password');
}
Important thing to note here is the function
Hash::check(CURRENT_PASSWORD_ENTERED_IN_FORM, HASHED_VERSION_OF_PASSWORD_STORED_IN_AUTH_USER)
Finally, if it's all good you can update the current user password inside Auth and in database as follows,
// authenticated user
$user = Auth::user();
$user->password = Hash::make($new_password);
// finally we save the authenticated user
$user->save();
Try the following:
public function postUserPasswordChange(){
$validator = Validator::make(Input::all(), User::$change_password_rules);
if($validator->passes()){
$user = UserEventbot::findOrFail(Auth::user()->id);
$user->password = Hash::make(Input::get('new_password'));
$user->save();
return Redirect::to('users/change-password');
}else {
return Redirect::to('users/change-password')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
}
}
this is my own solution, I have 3 inputs = old_password, password, password_confirmation, form with action=post.
Validator check requirements, hash checks if Old password matches
public function changePassword()
{
$user = Auth::user();
$rules = array(
'old_password' => 'required|alphaNum|between:6,16',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::action('UserController#show',$user->id)->withErrors($validator);
}
else
{
if (!Hash::check(Input::get('old_password'), $user->password))
{
return Redirect::action('UserController#show',$user->id)->withErrors('Your old password does not match');
}
else
{
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::action('UserController#show',$user->id)->withMessage("Password have been changed");
}
}
}
Please try the following changed
public function postUserPasswordChange(){
$validator = Validator::make(Input::all(), User::$change_password_rules);
if($validator->passes()){
$user = UserEventbot::findOrFail(Auth::user()->id);
if(Hash::check(Input::get('password'), $user->getAuthPassword())) {
$user->password = Hash::make(Input::get('new_password'));
$user->save();
return Redirect::to('users/change-password')->with('message','Your password has been changed');
}
}
return Redirect::to('users/change-password')->with('message', 'The following errors occurred')->withErrors($validator);
}
You should exclude withInput() in term of password.Hope this help

Resources