Welcome Guest, Not a member yet? Register   Sign In
My first login in CI, after couple hours
#1
Exclamation 

Hello, after i read a lot of articles about CI, finally think i ended (partial) my login method.
I don't know if the logic is good, or maybe is another correct way to do that.

This is my controller

PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');
class 
Login extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('login_model');
    }
    public function index() {
        //check if i can pass some data to view
        $data['title_header'] = 'Login title';
        $this->load->view('foundation/header'$data);

        //security inputs in controller, if some data are sents
        $this->check_login();

        //loading login page
        $this->load->view("login_view");
        $this->load->view('foundation/footer');
    }
    private function check_login() {
        //check if is not empty
        if (!$this->input->post('username') && !$this->input->post('password')) {
            return;
        }
        //if i have some value i begin the test...
        $this->load->library('form_validation');
        $this->form_validation->set_rules('username''Name''required|max_length[20]');
        $this->form_validation->set_rules('password''Password''required|max_length[20]');
        //
        if ($this->form_validation->run()) {
            //if everything is ok, let's check in db
            $params = array(
                'username' => $this->input->post('username'),
                'password' => $this->input->post('password'), 
                /* and username and password is secure by form validation? */
            );
            
            $this
->login_model->check_login_database($params);
        } else {
            //how i know what is wrong?name or password?i'm confuse
            $this->session->set_flashdata('login', array('class' => 'alert alert-danger''message' => 'Something is wrong'));
        }
    }


Model :

PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');
class 
login_model extends CI_Model{
    function __construct(){
        parent::__construct();
    }
    public function check_login_database($params){
        $query =   $this->db->query("SELECT * FROM  users WHERE name='".$params['username']."' AND password='".$params['password']."'");
        if($query->num_rows()>0){
            //succesfully logged
            //here i will set session and other
            redirect();
        }
        else{
            $this->session->set_flashdata('login', array('class' => 'alert alert-danger''message' => 'Username or password are wrong'));
        }
    }



And view

PHP Code:
<div class="container">
    <div class="row">
        <div class="col-sm-6 col-md-4 col-md-offset-4">
            <h1 class="text-center login-title">Sign in to continue</h1>
            <?php if ($this->session->flashdata('login')) {
                ?>

                <div class="alert <?php echo $this->session->flashdata('login')['class']; ?>"><?php echo $this->session->flashdata('login')['message']; ?></div>
                <?php
            
}
            ?>


            <div class="account-wall">
                <img class="profile-img" src="https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=120"
                     alt="">
                     <?php
                     
//open a new form
                     echo form_open('', ['action' => '''id' => 'frmUsers''autocomplete' => 'off''class' => 'form-signin']);


                     echo form_input(['name' => 'username''class' => 'form-control''placeholder' => 'username''required' => 'required']);
                     echo form_input(['name' => 'password''class' => 'form-control''type' => 'password''required' => 'required']);
                     $data = array(
                         "type" => "submit",
                         "name" => "login",
                         "value" => "Sign in",
                         "class" => "btn btn-lg btn-primary btn-block",
                     );
                     echo form_submit($data);
                     ?>
                <label class="checkbox pull-left">
                    <?php
                    $data 
= array(
                        "id" => "remember",
                        "name" => "remember",
                        "type" => "checkbox",
                        "value" => "1",
                    );
                    echo form_input($data);
                    echo form_label('Remember''remember');
                    ?>
                </label>
                <?php
                
echo anchor('''Need Help?', array("class" => "pull-right need-help"));
                ?>
                <span class="clearfix"></span>
                <?php
                
echo form_close();
                ?>
            </div>


            <a href="#" class="text-center new-account">Create an account </a>
        </div>
    </div>
</div> 



Also available on :
Login_controller https://pastebin.com/8d9zZDxu
Login_model https://pastebin.com/NzqYuaVF
Login_view https://pastebin.com/vhurzFJE

I waiting for a review and some tips.
Thank you, and apologize for my eng.
Reply
#2

(This post was last modified: 01-05-2020, 02:41 AM by jreklund.)

Your model contains SQL injections and you don't utilize encryption of your passwords.

SQL Injection; You will need to do query bindings or use the "Query Builder" class.
https://codeigniter.com/user_guide/datab...y-bindings
https://codeigniter.com/user_guide/datab...ilder.html

Passwords; Need to be encrypted in your database, not stored as plain text.

Use password_hash to save passwords:
https://www.php.net/manual/en/function.p...d-hash.php

Use password_verify to match passwords:
https://www.php.net/manual/en/function.p...verify.php

1. Select * from users where username... (you shouldn't put password here)
2. If there is a match, check the encrypted password with password_verify (against your param['password'])

Passwords should not be limited to 20 characters.

set_rules should return FALSE if there aren't a match. Use a callback to validate the password.

This code is inside a library so $this->CI should be $this-> in your case.

PHP Code:
    public function login()
    {
        
$this->CI->load->helper('form');
        
$this->CI->load->library('form_validation');
        
        
$validation_rules = array(
            array(
                
'field' => 'login_email',
                
'label' => lang('login_email'),
                
'rules' => array(
                    
'trim',
                    
'valid_email'
                
)
            ),
            array(
                
'field' => 'login_password',
                
'label' => lang('login_password'),
                
'rules' => array(
                    
'trim',
                    
'required',
                    array(
'validate_auth', array( $this'_validate_auth' ) )
                )
            )
        );
        
        
$this->CI->form_validation->set_rules$validation_rules );
        
        if( 
$this->CI->form_validation->run() === TRUE )
        {
            return 
TRUE;
        }
        return 
FALSE;
    }

    public function 
_validate_auth()
    {
        
$user_email        $this->CI->input->post('login_email');
        
$user_password    $this->CI->input->post('login_password');
        
        if( empty(
$user_email) OR empty($user_password) )
        {
            
$this->CI->form_validation->set_message('validate_auth'lang('error_missing_fields'));                
            return 
FALSE;
        }
        
        if( 
$auth_data $this->CI->auth_model->get_auth_data$user_email ) )
        {
            if( 
$auth_data->banned === '1' )
            {
                
$this->CI->form_validation->set_message('validate_auth'lang('error_username_password'));
            }
            if( ! 
$this->check_password$auth_data->passwd$user_password ) )
            {
                
$this->CI->form_validation->set_message('validate_auth'lang('error_username_password'));
            }
            else
            {
                
// Setup redirection if redirect required
                
$this->redirect_after_login();
                        
                
// Set session cookie and remember me
                
$this->maintain_state$auth_data );
                
                
// Send the auth data back to the controller
                
return TRUE;
            }
        }
        else
        {
            
$this->CI->form_validation->set_message('validate_auth'lang('error_username_password'));
        }
        
        return 
FALSE;
    } 
Reply
#3

Thank u very much.I will fix this problem , and for now i want to know if the logic is good,i mean functions is in the right place (controller, model ), because i don't want to start with bad idea.
Reply
#4

It depends on how clean you want your Login controller (or you want to use it another project). If you want it cleaner you should create a Authentication library.

Model should only return the user content, the logic of verifying should be handled in your controller (or library).

This should happen before any view have been loaded. So you can get a correct redirect without sending unwanted HTML before the redirect.
PHP Code:
//security inputs in controller, if some data are sent.
 
$this->check_login(); 

You should use form_validation->set_message instead of flash message.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB