Using the Remember me feature with Sentry in Laravel 4 - laravel

I'm trying to get a login form to 'remember' the user logging in and I just can't work out how to do it.
Here's my controller
public function getLogin()
{
// Return the view with the data
return View::make('users.login');
}
public function postLogin()
{
// Gather Sanitized Input
$input = array(
'email' => Binput::get('email'),
'password' => Binput::get('password'),
'rememberMe' => Binput::get('rememberMe')
);
// Set Validation Rules
$rules = array (
'email' => 'required|min:4|max:64|email',
'password' => 'required|min:6'
);
//Run input validation
$v = Validator::make($input, $rules);
if ($v->fails())
{
// Validation has failed
return Redirect::to('users/login')->withErrors($v)->withInput();
}
else
{
try
{
//Check for suspension or banned status
$user = Sentry::getUserProvider()->findByLogin($input['email']);
$throttle = Sentry::getThrottleProvider()->findByUserId($user->id);
$throttle->check();
// Set login credentials
$credentials = array(
'email' => $input['email'],
'password' => $input['password']
);
// Try to authenticate the user
$user = Sentry::authenticate($credentials, $input['rememberMe']);
Sentry::loginAndRemember($user);
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
// Sometimes a user is found, however hashed credentials do
// not match. Therefore a user technically doesn't exist
// by those credentials. Check the error message returned
// for more information.
Session::flash('error', 'Invalid username or password.' );
return Redirect::to('users/login')->withErrors($v)->withInput();
}
catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
{
echo 'User not activated.';
Session::flash('error', 'You have not yet activated this account.');
return Redirect::to('users/login')->withErrors($v)->withInput();
}
// The following is only required if throttle is enabled
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
$time = $throttle->getSuspensionTime();
Session::flash('error', "Your account has been suspended for $time minutes.");
return Redirect::to('users/login')->withErrors($v)->withInput();
}
catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
{
Session::flash('error', 'You have been banned.');
return Redirect::to('users/login')->withErrors($v)->withInput();
}
return Redirect::to('/');
}
}
/**
* Logout
*/
public function getLogout()
{
Session::flush();
Sentry::logout();
return Redirect::to('/');
}
And here's my View
#extends('layouts/master')
{{-- Web site Title --}}
#section('title')
#stop
{{-- Content --}}
#section('content')
<div class="tck-well span6 offset3">
<h1>Login</h1>
<form class="" action="{{ URL::to('users/login') }}" method="post">
{{ Form::token(); }}
<div class="control-group {{ ($errors->has('email')) ? 'error' : '' }}" for="email">
<label class="control-label" for="email">E-mail</label>
<div class="controls">
<input name="email" id="email" value="{{ Request::old('email') }}" type="text" class="input-xlarge" placeholder="E-mail">
{{ ($errors->has('email') ? $errors->first('email') : '') }}
</div>
</div>
<div class="control-group {{ $errors->has('password') ? 'error' : '' }}" for="password">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input name="password" value="" type="password" class="input-xlarge" placeholder="New Password">
{{ ($errors->has('password') ? $errors->first('password') : '') }}
</div>
</div>
<div class="control-group" for"rememberme">
<div class="controls">
<label class="checkbox inline">
<input type="checkbox" name="rememberMe" value="1"> Remember Me
</label>
</div>
</div>
<div class="form-actions">
<input class="button button-large button-secondary" type="submit" value="Log In">
Forgot Password?
</div>
</form>
</div>
#stop
Can someone help point me in the right direction please?

You could also use the helper method:
if( Input::get('rememberMe') ) {
$user = Sentry::authenticateAndRemember($credentials)
} else {
$user = Sentry::authenticate($credentials, false);
}

Similar to Devo's
// Try to log the user in
Sentry::authenticate(Input::only('email', 'password'), Input::get('remember-me', 0));
// For the view page
<input type="checkbox" name="remember-me" id="remember-me" value="1" /> Remember me;

Instead of,
$user = Sentry::authenticate($credentials, $input['rememberMe']);
Use,
if(!empty($input['rememberMe'])) {
$user = Sentry::authenticate($credentials, true);
} else {
$user = Sentry::authenticate($credentials, false);
}
And make sure you are getting some value in $input['rememberMe'].

From GitHub it seems setting gc_maxlifetime in php.ini (or .htaccess) is sometimes necessary as well..
session.gc_maxlifetime = 2592000

In app/config/session.php add this lines:
'lifetime' => 999999,
'expire_on_close' => false,

Related

delete if password is correct

i need to create a condition that clears the record but with a password.
if the password is correct execute the delete();
controller:
public function eliminar($id){
$registros = \App\Models\Registro::findOrFail($id);
$registros->delete();
return redirect('sistema')->with('mensaje', 'Registro Borrado con exito');
}
public function borrar($id){
// return $request->all();
$data = [
'category_name' => 'datatable',
'page_name' => 'multiple_tables',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
'fechax' => Carbon::now(),
'borrar' => \App\Models\Registro::findOrFail($id),
'password' => 'PASSCODE',
];
return view('borrar')->with($data);
}
blade.php:
<h1>Do you want to delete the record?</h1>
<form action="{{ route('eliminar', $borrar) }}" class="d-inline" method="POST">
#method('DELETE')
#csrf
<button type="submit" class="btn btn-danger btn-sm">DELETE</button>
<div class="form-group col-md-6">
<label for="telefono">Password</label>
<input name="password" type="password" class="form-control" id="telefono" required>
</div>
</form>
the password is obtained statically
How can I make it delete without the password is identical?
help please
If the password is saved statically, inside in a variable, the following should do the job for you.
routes/web.php
Route::delete('/path/here', 'SomeController#destroy');
SomeController.php
public function destroy($id)
{
$model = YourModel::find($id);
if (! $model) {
session()->flash('error_message', 'Model not found with the given id: ', . $id);
return back();
}
// $password is the password that you have saved somewhere
if (request()->password_field_value == $password) {
$model->delete();
session()->flash('success_message', 'Model deleted successfully.');
return back();
}
session()->flash('error_message', 'Invalid password. Try again');
return back();
}

Undefined Index:email Error In Laravel 5.6

I want to make login functionality for my website. But unfortunately it is giving undefined Index:email in my AdminController:
public function login(Request $request)
{
if($request->isMethod('post'))
{
$data = $request->input();
if (Auth::attempt(['email' => $data['email'], 'password' => $data['password'],'admin' => '1'])) {
echo "Success";
//console.log("Successfull");
die;
}
else
{
echo "Failed";
//console.log("Failed");
die;
}
}
return view('admin.admin_login');
}
In Blade:
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text bg-success text-white" id="basic-addon1"><i class="ti-user"></i></span>
</div>
<input type="email" name="email" class="form-control form-control-lg" placeholder="Email" aria-label="Email" aria-describedby="basic-addon1" required="">
</div>
change $data['email'] to $request->email.Because $request contain object not an array
You can do the following
public function login(Request $request)
{
if($request->isMethod('post'))
{
if (Auth::attempt(['email' =>$request->email, 'password' => $request->password,'admin' => '1'])) {
echo "Success";
//console.log("Successfull");
die;
}
else
{
echo "Failed";
//console.log("Failed");
die;
}
}
return view('admin.admin_login');
}
even i dont see password field in your blade template

DOMPDF - Laravel - Email PDF with Attachment

I am getting this error what would be the reason for this
"Undefined variable: quotation"
QuotationController.php
public function update(Request $request, Quotation $quotation)
{
{
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->save();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
}
public function edit(Quotation $quotation)
{
return view('employees.quotations.edit', compact('quotation'));
//return view('employees.quotations.edit')->with('quotation');
}
......................................................................
routes look like this
Route::post('/quotation', 'Employee\QuotationController#store')->name('employee.quotation.store');
Route::get('/quotation', 'Employee\QuotationController#index')->name('employee.quotation.index');
Route::get('/quotation/create', 'Employee\QuotationController#create')->name('employee.quotation.create');
Route::put('/quotation/{quotation}', 'Employee\QuotationController#update')->name('employee.quotation.update');
Route::get('/quotation/{quotation}', 'Employee\QuotationController#show')->name('employee.quotation.show');
Route::delete('/quotation/{quotation}', 'Employee\QuotationController#destroy')->name('employee.quotation.destroy');
Route::get('/quotation/{quotation}/edit', 'Employee\QuotationController#edit')->name('employee.quotation.edit');
employees.quotations.edit.blade.php looks like this
#section('left-menu')
#endsection
#section('right-menu')
#endsection
#section('content')
<h1>Update a Quotation</h1>
<br><br>
<form action="{{ route('employee.quotation.update',$quotation->id) }}" method="post">
#method('PUT')
#csrf
<div class="form-group">
<label for="inputJobDescription">Description</label>
<textarea class="form-control" rows="2" id="inputQuoteDescription" name="description" placeholder="Description">{{$quotation->description}}
</textarea>
</div>
<div class="form-group row">
<label for="inputQty" class="col-2 col-form-label">Qty</label>
<div class="col-10">
<input type="text" class="form-control" id="inputQty" name="qty" value="{{$quotation->qty}}" oninput="quotation_calculate()" onchange="quotation_calculate()">
</div>
</div>
<div class="form-group row">
<label for="inputEachPrice" class="col-2 col-form-label">Each Price</label>
<div class="col-10">
<input type="text" class="form-control" id="inputEachPrice" name="each_price" value="{{$quotation->each_price}}" oninput="quotation_calculate()" onchange="quotation_calculate()">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
#endsection
#section('pagescript')
#stop
What am i missing here ? I am already passing $quotation to the edit view
You are obviously not passing the $quotation variable through your route. You are also using the $quotation as an object; that tells me you don't intend passing it through the route. Try the following code:
public function update(Request $request, $quotation_id)
{
$quotation = Quotation::findOrFail($quotation_id);
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->update();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message) use ($quotation){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
This should work.
Why are you using double brackets to declare a function ? Why not:
public function update(Request $request, Quotation $quotation)
{
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->save();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
I think you need to pass $quotation into the closure:
Mail::send(['text' => 'mail'], $info, function ($message) use ($quotation) {
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com', 'John Doe')->subject('Quotation');
$message->from('from#gmail.com', 'The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});

Can't log in to admin dashboard

My password and username are correct, but I can't login to admin. Is there anything wrong with my controller?
This is my model:
class login_model extends CI_Model{
function cek($username, $password){
$this->db->where("username", $username);
$this->db->where("password", $password);
return $this->db->get("user_admin");
}
function getLoginData($usr, $psw){
$u = $usr;
$p = md5($psw);
$q_cek_login = $this->db->get_where('user_admin', array('username' => $u, 'password' => $p));
if(count($q_cek_login->result()) > 0){
foreach($q_cek_login->result() as $qck){
foreach($q_cek_login->result() as $qad){
$sess_data['logged_in'] = TRUE;
$sess_data['id'] = $qad->id;
$sess_data['username'] = $qad->username;
$sess_data['password'] = $qad->password;
$sess_data['email'] = $qad->email;
$sess_data['level'] = $qad->level;
$this->session->set_userdata($sess_data);
}
redirect('welcome_message');
}
}else{
$this->session->set_flashdata('result_login'. 'username dan password salah');
header('location: '. base_url(). 'login');
}
}
}
This is my controller:
class login extends CI_Controller {
function _construct(){
parent::_construct();
if($this->session->userdata('username')){
redirect(base_url('welcome_message'));
}
$this->load->model(array('login_model'));
}
function index(){
$this->load->view('login');
}
function proses(){
$this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
if($this->form_validation->run() == FALSE){
$this->load->view('login');
}else{
$usr = $this->input->post('username');
$psw = $this->input->post('password');
$u = $usr;
$p = md5($psw);
$cek = $this->login_model->cek($u, $p);
if($cek->num_rows() > 0 ){
foreach($cek->result() as $qad){
$sess_data['id'] = $qad->id;
$sess_data['email'] = $qad->email;
$sess_data['username'] = $qad->username;
$sess_data['level']=$qad->level;
$this->session->set_userdata($sess_data);
}
$this->session->set_flashdata('success', 'login berhasil');
redirect(base_url('/'));
}else{
$this->session->set_flashdata('result_login', 'username dan password yang anda masukkan salah');
redirect(base_url('login'));
}
}
}
My view:
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<form action="<?php echo base_url('login/proses'); ?>" method="post">
<?php if (validation_errors() || $this->session->flashdata('result_login')) { ?>
<div class="alert alert-danger animated fadeInDown" role="alert">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Peringatan!</strong>
<?php echo validation_errors(); ?>
<?php echo $this->session->flashdata('result_login'); ?>
</div>
<?php } ?>
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Username" id="username" name="username">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" id="password" name="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
Register a new admin
</div>
When I try to log in, I always get this error:
I don't see anything strikingly wrong with your code.
Well you are obviously hitting your last nested else which means for some reason this statement $cek->num_rows() > 0 is evaluating to false.
I assume that you are entering a proper and existing username + password combination. But to troubleshoot you can after $p = md5($psw); do:
echo 'hashed password: ' . $p . '<br>username: ' . $u; exit;
and see if the username and hashed password match something in the database, if not, you have your answer. My best guess is that you perhaps didn't store a hashed password and only plain-text one.
As a side note you should move all of your redirects and flashdata out of your model. Models should only return or throw Exceptions.

I Cannot able to pass the id in route file in laravel

I am declaring the above thing in the route for edit of my data.
Route::get('editproduct/{id}', 'HomeController#Edit_Product');
Above is my editproduct.blade.php page
<?php
$id = $_GET['eid'];
$product_info = DB::select("SELECT * FROM `product` WHERE `pid` = '".$id."'");
foreach($product_info as $detail)
{
$actual_image = 'theme/uploads/'.$detail->pimage;
$product_image = $detail->pimage;
$product_name = $detail->pname;
$product_price = $detail->pprice;
}
?>
#include('include/header')
<div class="tab-pane add-product-view" id="profile">
<form name="add_product" method="post" enctype="multipart/form-data" role="form" action="{{ url('edit-product-process') }}">
{{ csrf_field() }}
<div class="form-label">Add Image: </div>
<div class="form-field"><input type="file" name="add_image" id="add_image" value="{{asset($actual_image)}}" /></div>
<img src="{{asset($actual_image)}}" width="50" height="50" />
<div class="form-label">Product Name:</div>
<div class="form-field"><input type="text" name="product_name" id="product_name" value="{{ $product_name }}" /></div>
<div class="form-label">Product Price:</div>
<div class="form-field"><input type="text" name="product_price" id="product_price" value="{{ $product_price }}" /></div>
<div class="btn btn-primary"><input type="submit" name="submit" value="Add Product"</div>
</form>
</div>
#include('include/footer')
This is My HomeController.blade.php
public function Edit_Product($id){
return View::make('editproduct')->with('id', $id);
}
public function edit_product_process(Request $request){
$prd_id = $request->pid;
$imageTempName = $request->file('add_image')->getPathname();
$imageName = $request->file('add_image')->getClientOriginalName();
$path = base_path() . '/theme/uploads/';
$request->file('add_image')->move($path , $imageName);
$remember_token = $request->_token;
$date = date('Y-m-d H:i:s');
$pname = $request->product_name;
$pprice = $request->product_price;
DB::table('product')->where('pid',$prd_id)->update(
array(
'pimage' => $imageName,
'pname' => $pname,
'pprice' => $pprice,
'remember_token' => $remember_token,
'created_at' => $date,
'updated_at' => $date,
)
);
return redirect('dashboard');
}
I am getting the below error, Please anyone can be able to help me, I am new at laravel.
page is not found
NotFoundHttpException in RouteCollection.php line 161:
If you're getting this error when you're trying to submit the form, you should check you route. It should look like this:
Route::post('edit-product-process', 'HomeController#edit_product_process');
Also, to pass an ID into edit_product_process you need to add field with ID into the form:
<input type="hidden" name="id" value="{{ $id }}">
And then you can get it in edit_product_process with $request->id
Your route should be as:
Route::get('editproduct/{id}', 'HomeController#Edit_Product')->name('product.edit');
Then you can use it as:
{{ route('product.edit', ['id' => $id]) }}
But it's a terrible practice to use DB queries in views.
Please do read more about queries and controllers in the docs.
Check Your Controller Name Why r using blade in that.This is bad practice.HomeController.blade.php

Resources