Check if user is not active, not to log in - codeigniter

I want to add condition for my login form - if a user is not already active, not to log in. I'm using CodeIgniter. That's my controller:
public function login ()
{
$this->load->model('user_model');
$user=$this->user_model->login();
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_login_check');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run()==FALSE)
{
$this->index();
}
else
{
if(count($user) > 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);
redirect('index/home_page');
}
}
}
My model is:
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();
}
I have tried with this: $this->db->where('deactivated_at = "0000-00-00 00:00:00" OR deactivated_at IS NULL'); in my login function, but it does not work. How could I make this authentication, if not active user, not to log in at all?

There's a few things I would say is wrong with your code.
First off, you're trying to login the user before the form validation has completed. This should be done afterwards, or I don't see the need for validation?
This would be my version of your login function, within your controller.
function login()
{
$this->load->model('users_model');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if (!$this->form_validation->run())
{
$this->index(); // Show the login form..
}
else
{
// This is where we try to login the user, now the validation has passed
if ($user = $this->users_model->login())
{
// Start the session...
}
else
{
// The model returned false..
}
}
}
So you don't go to the model, until the form validation has passed. Then, in your model;
function login()
{
$where = array(
'username' => $this->input->post('username'),
'password' => sha1($this->input->post('password'))
);
// $this->db->select('*'); No need for this line
$query = $this->db->get_where('users', $where);
if ($query->num_rows() > 0)
{
// Found a match
// Are they activated?
if (!is_null($query->row('deactivated_at'))
{
// The user isn't deactivated
return $query->row_array();
}
else
{
// The user is deactivated
return false;
}
}
else
{
// The username and/or password is wrong...
return false;
}
}
Hope this helps.

Related

Codeigniter sessions, display user's firstname

I'm trying to display the user's firstname after login but it doesn't appear on the page. I tried to display it like this
<h2> Welcome <?php echo $this->session->userdata('firstname'); ?> </h2>
but it didn't display the user's firstname, even though there are data in DB. But when I tried to change the 'firstname' into 'username', it displayed the email of the user(test#gmail.com). How can I display the user firstname? Here's my controller:
function login(){
$this->form_validation->set_rules('username', 'Username', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) {
redirect('/');
} else {
$user_login = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
);
$login = new UI_model;
$result = $login->login_user($user_login);
if($result){
$auth_details = array(
'firstname' => $result->firstname,
'lastname' => $result->lastname,
'username' => $result->username,
);
$this->session->set_userdata($auth_details);
// $this->session->set_userdata('authenticated', '1');
$this->session->set_flashdata('status', 'User Logged in Successfully!');
redirect(base_url('pages/index'));
} else {
$this->session->set_flashdata('status', 'Invalid Credentials. Please try again');
redirect(base_url('pages/about'));
}
}
}
Here's my Model:
public function login_user($data){
$this->db->select('*');
$this->db->where('username', $data['username']);
$this->db->where('password', $data['password']);
$this->db->from('users');
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows() == 1){
return $query->row();
} else {
return false;
}
}
Can you attach an image of your database you are using for and echo all data session?

Add a third parameter to a login request using JWT

I'm working on an api in Laravel and want to edit the login procedure a bit.
Users log in with a username and a password but as a third parameter I want to add an app_id.
This is because usernames can be double in the database when the app_id is different. This is my current login code. It's using JWT as a driver.
$credentials = request(['username', 'password']);
if(!$token = auth()->attempt($credentials)) {
return response()->json([
'error' => ['code' => 1],
'status' => 'error',
], 401);
}
How can I accomplish this?
Kind regards,
Kevin Walter
Edit: My entire AuthController
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('jwt.verify', ['except' => ['login', 'refresh']]);
}
/**
* Login to get JWT credentials
*/
public function login() {
//TODO: LOCKOUT AFTER X AMOUNT OF TRIES
if(!$token = auth()->attempt($this->credentials())) {
return response()->json([
'error' => ['code' => 1],
'status' => 'error',
], 401);
}
return $this->me(true, $token);
}
public function checkPin() {
$username = request('username');
$pincode = request('pincode');
$user = auth()->user();
if($user && $user->username && $user->pincode && $username == $user->username && $pincode == $user->pincode) {
return $this->outputJson(0, 'auth', 'checkPin',[
"firebase_key" => $this->create_custom_token($user->uid, true),
"pin_ok" => 1,
]);
} else {
return $this->outputJson(0, 'auth', 'checkPin', ["pin_ok" => 0]);
}
}
public function me($withToken = false, $token = "") {
$user = auth()->user();
$output = $user;
$output->groups = $user->groups;
$output->categories = $user->categories;
$output->hasPin = $user->hasPin();
$headers = array();
if($withToken) {
$headers["X-TOKEN-RETURN"] = $token;
}
return $this->outputJson('0', 'auth', 'me', $output, $headers);
}
public function logout() {
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
}
It was just as simple as merging the app_id in the credentials. This is the working example!
//Add app ID into the mix of credentials
protected function credentials()
{
return array_merge(request(['username', 'password']), ['app_id' => \request()->header('X-APP-ID')]);
}
/**
* Login to get JWT credentials
*/
public function login() {
//TODO: LOCKOUT AFTER X AMOUNT OF TRIES
if(!$token = auth()->attempt($this->credentials())) {
return response()->json([
'error' => ['code' => 1],
'status' => 'error',
], 401);
}
return $this->me(true, $token);
}

how to make admin forget password functionality in laravel?

I want to create a forgot password functionality of admin panel but, now I am using the custom admin login functionality in my AdminController. how can I create a forgot password functionality with a token for the admin panel ?
MY AdminController Code Here ...
login Method
public function login(Request $request)
{
if($request->isMethod('post')) {
$data = $request->input();
$adminCount = Admin::where([
'username' => $data['username']
'password'=> md5($data['password']),
'status'=> 1
])->count();
if($adminCount > 0){
//echo "Success"; die;
Session::put('adminSession', $data['username']);
return redirect('/admin/dashboard');
}else{
//echo "failed"; die;
return redirect('/admin')->with('flash_message_error','Invalid Username or Password');
}
}
return view('admin.admin_login');
}
Reset Method
public function reset(ResetPasswordRequest $request)
{
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath())->with('status', trans($response));
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
You should try this:
public function reset(ResetPasswordRequest $request)
{
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath())->with('status', trans($response));
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}

Laravel: How to use redirect inside a function

I want to Redirect my views inside the function like when admin goes to admin page, teacher goes to teacher page and student goes to student page.
Im getting an unexpected error with the else :(
Here's my function
public function postLogin()
{
$validator = Validator::make(Input::all(), array(
'username' => 'required',
'pass1' => 'required'
));
if($validator->fails())
{
return Redirect::route('getLogin')->withErrors($validator)->withInput();
}
else
{
$remember = (Input::has('remember')) ? true : false;
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('pass1')
), $remember);
if($auth)
{
$admin = User::where('isTeacher', '0')->where('isAdmin', '1')->get();
$teacher = User::where('isTeacher', '1')->where('isAdmin', '0')->get()
if($admin)
{
return Redirect::route('admin.index');
}
else if($teacher)
{
return Redirect::route('teacher.index');
}
else
return Redirect::route('student.index');
}
else
{
return Redirect::route('getLogin')->with('fail','You entered the wrong login credentials. Please try again.');
}
}
}
I want to redirect the route using the function instead inside of my blade. Is this possible?
if($auth)
{
$admin = User::where('isTeacher', '0')->where('isAdmin', '1')->get();
$teacher = User::where('isTeacher', '1')->where('isAdmin', '0')->get(); <-----
you missed a ; in that line.
Additional info:
User::where('isTeacher', '0')
you have to use an operand as 2nd argument. e.g.
User::where('isTeacher','=', '0')

Laravel 4 Authentication does not work and gives NO ERROR

I have been searching for solutions and changing my code back and forth but nothing worked for me and I honestly have given up hope to fix it by myself.
It stays on the same page and does not Redirect::to('test2'), but stays in the same page and when I remove the else { return Redirect::to('login'), it gives me a blank page.
Any help would be extremely appreciated.
This is my user model file:
protected $fillable=['email', 'password'];
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
protected $primaryKey = 'id';
public static $rules = array(
'email' => 'required|email',
'password' => 'required',
);
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
This is my routing functions:
Route::get('/login', function(){
return View::make('login');
});
Route::post('/login', function(){
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$userData = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userData)) {
return Redirect::to('test2');
echo 'SUCCESS!';
} else {
return Redirect::to('login');
}
}
I have been struggling around with the hash at beginning.
1. If the length of your password column isn't 60 then it wouldn't allow you to login.
2. Before logging via Auth::attempt() instead try to fetch the data of the user using his username
and then compare the password using Hash::check()
try something this
Route::post('/login', function(){
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$email=Input::get('email');
$user=User::where('email','=',$email)->first();
$bool=Hash::check('your password for the email',$user->password);
if(bool)
{
if (Auth::attempt(Input::only('email','password')))
{
return Redirect::to('test2');
echo 'SUCCESS!';
}else{
return Redirect::to('login');
}
}else{
return echo 'password didn't matche';
}
}

Resources