I have a login form and it works, but I have to add condition if user is active or not. If he's not active, then redirect to some page show_error. I'm using CodeIgniter. here's my model: I tried with this function "is_active_user" but it's not working.
public function login()
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $this->input->post('username'));
$this->db->where('password',sha1($this->input->post('password')));
$result=$this->db->get();
return $result->row_array();
}
public function is_active_user() {
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $this->input->post('username'));
$this->db->where('deactivated_at = "0000-00-00 00:00:00" || deactivated_at IS NULL ');
$result=$this->db->get();
if($result->num_rows() > 0)
{
return $result->row_array();
}
return false;
}
My controller is:
public function login ()
{
$this->load->model('user_model');
$user=$this->user_model->login();
$is_active=$this->user_model->is_active_user();
$this->form_validation->set_rules('username', 'Потребителско име', 'trim|required|callback_login_check');
$this->form_validation->set_rules('password', 'Парола', 'trim|required');
if ($this->form_validation->run()==FALSE)
{
$this->index();
}
else
{
if(count($user) > 0 && count($is_active) > 0)
{
$this->load->library('session');
$data = array(
'username' => $user['username'],
'user_id' => $user['user_id'],
'is_logged_in' => TRUE,
'role_id' => $user['role_id']
);
$this->session->set_userdata($data);
}
}
}
How to check if user is active or not?
But no result.
Now I tried with:
public function login()
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $this->input->post('username'));
$this->db->where('password',sha1($this->input->post('password')));
$this->db->where('deactivated_at = "0000-00-00 00:00:00" OR deactivated_at IS NULL');
$result=$this->db->get();
return $result->row_array();
}
But it logs me with another profile, not this profile with username and password that I have filled.
public function login()
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $this->input->post('username'));
$this->db->where('password',sha1($this->input->post('password')));
$this->db->where('deactivated_at <> "0000-00-00 00:00:00"');
$this->db->where('deactivated_at IS NOT NULL');
$result=$this->db->get();
return $result->row_array();
}
Related
I created a multistep form but I didn't use Ajax in it because I have no idea about Ajax. I have had to code a lot in my controller and routes for the way I created it which is probably not optimized. I'm new to Laravel so I can't find any solution.
How can I do this with ajax?
Controller
public function InitialCreateReport(Request $request){
$request->session()->forget('report');
$data['fiscalyear'] = FiscalYear::all();
$data['month'] = Months::all();
$data['report_type'] = ReportType::all();
$data['report'] = $request->session()->get('report');
return view('adc.reports.create-report', $data);
}
public function PostInitialCreateReport(Request $request){
$validatedData = $request->validate([
'fiscalyear' => 'required',
'month' => 'required',
'report_type' => 'required',
]);
if (empty($request->session()->get('report'))) {
$report = new Report();
$report->fill($validatedData);
$request->session()->put('report', $report);
} else {
$report = $request->session()->get('report');
$report->fill($validatedData);
$report->session()->put('report', $report);
}
return redirect()->route('adc.create.rent.certificate');
}
public function CreateRentCertificateReport(Request $request)
{
$data['report'] = $request->session()->get('report');
$data['reports'] = Report::distric()->status(1)->get();
return view('adc.reports.start-create-report', $data);
}
public function PostCreateRentCertificateReport(Request $request)
{
$report = $request->session()->get('report');
$request->session()->put('report', $report);
return redirect()->route('adc.preview.rent.certificate.report');
}
public function PreviewRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return view('adc.reports.preview-rent-certificate-report', compact('report', $report));
}
public function PostPreviewRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return redirect()->route('adc.save.rent.certificate.report');
}
public function SaveRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return view('adc.reports.save-rent-certificate-report', compact('report', $report));
}
public function PostSaveRentCertificateReport(Request $request)
{
$report = $request->session()->get('report');
$reports = new Report;
$reports->column_one = $report->sum('column_one');
$reports->column_two = $report->sum('column_two');
$reports->fiscal_year = $report->fiscalyear;
$reports->month = $report->month;
$reports->report_type = $report->report_type;
$reports->save();
$notification = array(
'message' => 'Report Created Successfully',
'alert-type' => 'success'
);
return redirect()->route('adc.pending.report')->with($notification);
}
Route
Route::get('/initial/create/report', [AdcController::class,'InitialCreateReport'])->name('inital.create.report');
Route::post('/initial/create/report', [AdcController::class,'PostInitialCreateReport'])->name('inital.create.report.post');
Route::get('/create/rent/certificate/report', [AdcController::class, 'CreateRentCertificateReport'])->name('create.rent.certificate');
Route::post('/create/rent/certificate/report', [AdcController::class, 'PostCreateRentCertificateReport'])->name('create.rent.certificate.report.post');
Route::get('/preview/rent/certificate/report', [AdcController::class, 'PreviewRentCertificateReport'])->name('preview.rent.certificate.report');
Route::post('/preview/rent/certificate/report', [AdcController::class, 'PostPreviewRentCertificateReport'])->name('preview.rent.certificate.report.post');
Route::get('/save/rent/certificate/report', [AdcController::class, 'SaveRentCertificateReport'])->name('save.rent.certificate.report');
Route::post('/save/rent/certificate/report', [AdcController::class, 'PostSaveRentCertificateReport'])->name('save.rent.certificate.report.post');
I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
protected function guard()
{
return Auth::guard();
}
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function login() {
$authenticated = false;
$remember = request('remember') ? true : false;
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')], $remember)) {
$authenticated = true;
}
if ($authenticated == true) {
$user = Auth::guard('web')->user();
$date = date('Y-m-d');
$success['userId'] = $user->id;
$success['avatar'] = url('/storage/user') . '/' . $user->avatar;
// $success['points'] = $user->userPoints->sum('points');
$success['email'] = $user->email;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->returnResponse(true, $success);
} else {
$success = array();
return $this->returnResponse(false, $success, 1, 'Invalid User Credential');
}
}
api.php
Route::group([
], function () {
Route::post('login', 'ApiController#login');
Route::post('register', 'ApiController#register');
Route::post('forgetPassword', 'ApiController#forgetPassword');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
When I test the login Post Request on the POSTMAN, I got the error shown below:
What could have caused the error?
i think you have declare index() multiple times in your controller so please check and if there is multiple times declaration of index() then just remove anyone.
I'm trying to send an email to a user by entering his name and I look for the user's email with this name, but it does not work, the success message appears but in my email I receive nothing. what am I doing wrong?
if(User::where('name', '=', $destinatario)->exists()){
$exists = DB::table('users')
->select('email')
->where('name', $destinatario)
->get();
Mail::to($exists)->send(new TestEmail($remetente, $nome, $assunto, $exists, $mensagem));
return back()->with('sucess', 'Message sent!');
}else{
return back()->with('error', 'User does not exist!');
}
Mailable:
public function __construct($remetente, $nome, $assunto, $destinatario, $data)
{
$this->remetente = $remetente;
$this->nome = $nome;
$this->assunto = $assunto;
$this->destinatario = $destinatario;
$this->data = $data;
}
public function build()
{
//$address = 'gabriel.jg04#gmail.com';
$subject = 'E-mail de Usuário';
$name = 'Juelito';
return $this->view('emails.test',['texto'=>$this->data])
->from($this->remetente, $this->nome)
->replyTo($this->destinatario, $name)
->subject($this->assunto);
}
Problem is with get(). get() returns collection of users.
But your mailable expect single user.
If you want to send mail to one person you could do like that:
$user = User::where('name', '=', $destinatario)->first();
if($user){
Mail::to($user)->send(new TestEmail($remetente, $nome, $assunto, $user, $mensagem));
return back()->with('sucess', 'Message sent!');
} else {
return back()->with('error', 'User does not exist!');
}
If you want to send mail to multiple persons you could do like that:
$users = User::where('name', '=', $destinatario)->get();
if($users->count()){
foreach($users as $user){
Mail::to($user)->send(new TestEmail($remetente, $nome, $assunto, $user, $mensagem));
}
return back()->with('sucess', 'Message sent!');
} else {
return back()->with('error', 'User does not exist!');
}
Mailable:
public function __construct($remetente, $nome, $assunto, $destinatario, $data)
{
$this->remetente = $remetente;
$this->nome = $nome;
$this->assunto = $assunto;
$this->destinatario = $destinatario;
$this->data = $data;
}
public function build()
{
return $this->view('emails.test', ['texto' => $this->data])
->from($this->remetente, $this->nome)
->replyTo($this->destinatario->email, $this->desctinario->name)
->subject($this->assunto);
}
Please help guys, I have encrypted successfully my password with password_hash but is there any solution how to check login and password using PHP password_verify for multiuser login?
here's my controller:
public function index()
{
$this->form_validation->set_rules('email','Email address','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('view_login');
} else {
$this->load->model('Model_members');
$valid_user = $this->Model_members->check_credential();
if($valid_user == FALSE)
{
$this->session->set_flashdata('error','');
redirect("login");
} else {
$this->session->set_userdata('email', $valid_user->email);
if($this->session->userdata('groups') == '1')
{
redirect('home');
}
elseif($this->session->userdata('groups') == '2')
{
redirect('homepage');
}
elseif($this->session->userdata('groups') == '0')
{
redirect('test1');
}
}
}
}
This is my model:
public function check_credential()
{
$email = set_value('email');
$password = set_value('password');
$hasil3 = $this->db->where('email', $email)
->where('password', $password)
->limit(1)
->get('users');
if($hasil3->num_rows() > 0)
{
return $hasil3->row();
} else {
return array();
}
}
Very appreciate for the help !!
Please find below mentioned solution, It will help you.
In Controller
$userData['email'] = $this->input->post('email');
$userData['password'] = $this->input->post('password');
$valid_user = $this->Model_members->check_credential($userData);
In Model your function will look like below.
public function check_credential($param) {
$hasil3 = $this->db->where('email', $param['email'])
->where('password', password_hash($param['password'], PASSWORD_DEFAULT, ['cost' => 10]))
->limit(1)
->get('users');
if ($hasil3->num_rows() > 0) {
return $hasil3->row();
} else {
return array();
}
}
Let me know if it not work.
Controller
//create array to pass data to model
$data = [
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
];
//check model to see if user exists and if correct password
$user = $this->name_of_model->check_credential($data);
if(isset($user['error])){
//return error message in some form
}
Model:
You want to break you process in two, in order to make error reporting better. First check if user exists, then check if password is correct
public function check_credential($data) {
//see if user exists first
$user = $this->db->where('email', $data['email'])
->get('users')->row_array();
if($user){
$success = (password_verify($data['password'],$user['password']));
return ($success) ? $user : ['error'=>'Incorrect Password']
}
else{
return ['error'=>'User doesn't exist'];
}
}
I have been toiling around to no avail of Solutions Please help. It seems my View cannot read the $code and $user variable respectively from my Controller
Here is the part of my controller that the $code and $user Variables are been instantiated respectively:
UserController.php
public function varifyMail($code){
if(User::where('varification_code','=',$code)->update(['varification_status'=>1])){
return Redirect::route('login')
->with('success', 'Account varified.');
}else{
return Redirect::route('login')
->with('error', 'Varification Failed.Try again');
}
);
$validation = Validator::make(Input::all(),$rules);
if($validation->fails()){
return Redirect::route('login')
->with('error', 'Invalid Email Address. Try again.');
}else{
$code = str_random(25);
$userUpdate = ['recovery_code' => $code];
User::where('email','=',Input::get('email'))->update($userUpdate);
$data = ['code'=>$code];
//send mail
Mail::send('emails.recover',$data,function($message){
$message->to(Input::get('email'))->subject('Recover Your Account.');
});
return Redirect::route('login')
->with('success', 'Request Send successfully.Please Recover Your Account.');
//return User::where('email','=',Input::get('email'))->get();
}
Auth::login($user);
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',$user->id)->first());
}else{
return Redirect::route('login')
->with('error', 'Recovery Failed.Try again');
}
And this is my view:
Adminverify.blade.php
<div class="header-content"><webversion>Web Version</webversion><span class="hide"> | <preferences lang="en">Update preferences</preferences> | </span>
But whenever I try using it it get this error:
ErrorException
Undefined variable: code (View: C:\wamp\www\secureserver\app\views\emails\adminverify.blade.php)
Any Help will be highly Appreciated Thanks!
Thanks for your prompt response but it happens to be that it did not work but here is my entire Controller with the Varify changed to Verify as cadmium suggested so we can be sure what exactly could be the challenge.
class UserController extends BaseController {
private function verify($email){
$verify = User::where('email','=',$email)->first();
if(! is_null($verify)){
if($verify->role_id==2){
return $verify->distributor_approve & $verify->varification_status;
}else{
return $verify->varification_status;
}
}else{
return 0;
}
}
/**
* login page
* #return void
*/
public function login()
{
return View::make('users.login')
->with('title', 'Log in');
}
/**
* process to login a user
* #return void
*/
public function doLogin()
{
$rules = array
(
'email' => 'required|email',
'password' => 'required'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::route('login')
->withInput()
->withErrors($validation);
else
{
$credentials = array
(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if($this->verify(Input::get('email')) && Auth::attempt($credentials))
{
Session::put('role', Auth::user()->role_id);
//return User::where('id','=',Auth::user()->id)->first();
if(User::where('id','=',Auth::user()->id)->first()->first_login == 0){
return Redirect::route('info.create',[Auth::user()->id]);
}
return Redirect::intended('/');
}
else
return Redirect::route('login')
->withInput()
->with('error', 'Error in Email Address or Password.');
}
}
/**
* logout a user
* #return void
*/
function logout()
{
Auth::logout();
Session::forget('role');
return Redirect::route('login')
->with('success', 'You have been logged out.');
}
public function show(){
$pages= Page::orderby('title')->get();
if(Auth::check()){
if(Auth::user()->role_id==1){
return View::make('public.pages.admin')
->with('title', "Home");
}
}
return View::make('public.pages.show')
->with('title', "Home")
->with('pages',$pages);
}
public function register()
{
return View::make('users.register')
->with('title', 'Register');
}
public function doRegister()
{
//return Input::all();
$rules = array
(
'username' => 'required|min:3|max:15',
'email' => 'required|email|unique:users',
'password' =>'Required|Confirmed',
'password_confirmation' =>'Required',
'role' => 'Required',
'agree' => 'Required',
'recaptcha_response_field' => 'required|recaptcha'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::route('register')
->withInput()
->withErrors($validation);
else
{
if(Input::get('role')==3){
$user = new User;
$user->user_name = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->role_id = Input::get('role');
$code = str_random(25);
$user->varification_code = $code;
$data = ['username'=>Input::get('username'),'code'=>$code];
Mail::send('emails.validate',$data,function($message){
$message->to(Input::get('email'))->subject('Please Verify Your Email.');
});
if($user->save())
return Redirect::route('home')
->with('success', "Verify Your Account.");
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}else{
$user = new User;
$user->user_name = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->role_id = Input::get('role');
$user->distributor_status = 1;
$code = str_random(25);
$user->varification_code = $code;
$data = ['username'=>Input::get('username'),'code'=>$code];
Mail::send('emails.validate',$data,function($message){
$message->to(Input::get('email'))->subject('Please Verify Your Email.');
});
if($user->save())
return Redirect::route('home')
->with('success', "Request Send successfully.Please Verify Your Email.");
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}
}
}
public function edit(){
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',Auth::user()->id)->first());
}
public function update(){
$rules = array
(
'username' => 'required|min:3|max:15',
'password' =>'Required|Confirmed',
'password_confirmation' =>'Required'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::back()
->withInput()
->withErrors($validation);
else
{
$userUpdate = ['user_name' => Input::get('username'),
'password'=>Hash::make(Input::get('password'))
];
if(User::find(Auth::user()->id)->update($userUpdate)){
Auth::logout();
Session::forget('role');
return Redirect::route('login')
->with('success', 'Your Cridentials Have Been Changed.');
}
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}
}
public function verifyMail($code){
if(User::where('varification_code','=',$code)->update(['varification_status'=>1])){
return Redirect::route('login')
->with('success', 'Account varified.');
}else{
return Redirect::route('login')
->with('error', 'Varification Failed.Try again');
}
}
public function passwordRecover(){
$rules = array
(
'email' => 'required|email'
);
$validation = Validator::make(Input::all(),$rules);
if($validation->fails()){
return Redirect::route('login')
->with('error', 'Invalid Email Address. Try again.');
}else{
$code = str_random(25);
$userUpdate = ['recovery_code' => $code];
User::where('email','=',Input::get('email'))->update($userUpdate);
$data = ['code'=>$code];
//send mail
Mail::send('emails.recover',$data,function($message){
$message->to(Input::get('email'))->subject('Recover Your Account.');
});
return Redirect::route('login')
->with('success', 'Request Send successfully.Please Recover Your Account.');
//return User::where('email','=',Input::get('email'))->get();
}
}
public function mailRecover($code){
$user = User::where('recovery_code','=',$code)->first();
if(! is_null($user)){
Auth::login($user);
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',$user->id)->first());
}else{
return Redirect::route('login')
->with('error', 'Recovery Failed.Try again');
}
}
/**
* Show a page
* #param string $pageUrl
* #return void
*/
public function pages($pageUrl = 'home')
{
try
{
$page = Page::where('url', '=', $pageUrl)->firstOrFail();
/*
if($page->id == 1) $layout = 'layouts.home';
else $layout = 'layouts.default';
*/
$layout = 'layouts.default';
return View::make('public.pages.publicShow')
->with('title', "$page->title")
->with('page', $page)
->with('layout', $layout);
}
catch(ModelNotFoundException $e)
{
return "Page not found.";
}
}
Somewhere in your code you need to have View::make("adminverify"). I don't see it in the code you've posted, but it's there somewhere. You need to pass the $code value to this view, like so:
View::make("adminverify")->with("code", "some code value");
Once you do that, the $code variable will be available in the template.