I am trying this code. I am already save user name and Hash::make('123') in database.
it's my controller
class EntriesController extends BaseController {
public function getIndex()
{
$username = 'saqib';
$password = '123';
$hashPassword = Hash::make($password);
if (Auth::attempt(array('username' => $username, 'password' => $hashPassword), true))
{
echo "Correct";
}
else
{
echo "Wrong";
$queries = DB::getQueryLog();
print_r(end($queries));
}
}
}
and it's routes:
Route::get('/', 'EntriesController#getIndex');
The password not in hashed.
if (Auth::attempt(array('username' => $username, 'password' => $password), true))
if you are using Auth::attempt() you don't need to hash the password. Instead just do
if (Auth::attempt(array('username' => $username, 'password' => $password), true))
Please don't hash password. Please find your below code:-
class EntriesController extends BaseController {
public function getIndex()
{
$username = 'saqib';
$password = '123';
$hashPassword = Hash::make($password);
if (Auth::attempt(array('username' => $username, 'password' => $password), true))
{
echo "Correct";
}
else
{
echo "Wrong";
$queries = DB::getQueryLog();
print_r(end($queries));
}
}
}
Note: Please check you database table "password" field its should allow 64 characters to store into it.(Hash password contains 64 characters)
Related
I have a problem about login multi user in my sistem. The sistem login is not worked as a flowchart below (language is Indonesia):
Flowchart Login Multi User
And the controller code is this:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Controllers\BaseController;
use App\Models\LoginModel;
/**
*
*/
class Login extends BaseController
{
public function index()
{
helper(['form']);
echo view('formlogin');
}
public function auth()
{
$session = session();
$model = new LoginModel();
$username = $this->request->getVar('username');
$password = $this->request->getVar('password');
$data = $model->where('username', $username)->get()->getRowArray();
//$data = $model->get()->getResultArray();
if ($data) {
//$pass = $data['password'];
$pass = password_hash($data['password'], PASSWORD_DEFAULT);
$verify = password_verify($password, $pass);
if ($verify) {
$session_data = [
'id_login' => $data['id_login'],
'username' => $data['username'],
'password' => $data['password'],
'level' => $data['level'],
'logged_in' => TRUE
];
$session->set($session_data);
if ($level = 'adminsuper') {
return redirect()->to(base_url('/adminsuper'));
}elseif ($level = 'admin') {
return redirect()->to(base_url('/admin'));
}
//return redirect()->to(base_url('/adminsuper'));
}else{
$session->setFlashdata('msg', '<div class="alert alert-danger text-center">Username dan Password Salah</div>');
return redirect()->to(base_url('/login'));
}
}else{
$session->setFlashdata('msg','<div class="alert alert-danger text-center">Pengguna Tidak Terdaftar</div>');
return redirect()->to(base_url('/login'));
}
}
public function logout()
{
$session = session();
$session->destroy();
return redirect()->to(base_url('/login'));
}
}
?>
What should I do, in order to be able to login multi user based on user level?
The level of admin are adminsuper and admin.
this way log in log out is outdatae use jwt(jwt.io) its modern
way login and secure
I have the following error in my code:
1) the data i am storing over session is not showing up in view
2) the form validation set rules is not working.. The required is not working. Whenever i press login without entering any field it prints a.
I have auto loaded session and form validation.
Should I use php sessions or ci sessions?
Controller:
public function loginFormValidation()
{
$this->form_validation->set_rules('email','Username','required'); //not working
$this->form_validation->set_rules('pass','Password','required');
$this->form_validation->set_error_delimiters('<div class = "text-danger">', '</div>');
if($this->form_validation->run())
{
$email = $this->input->post('email');
$pass = $this->input->post('pass');
$this->load->model('loginModel');
$result = $this->loginModel->loginValidation($email,$pass);
$user_id = $result->user_id;
$user_name = $result->user_name;
$password = $result->password;
$arrayDb = array(
'user_id' => $user_id,
'user_name' => $user_name,
'password' => $password,
);
$this->session->set_userdata('row', $arrayDb);
header("location:".base_url()."/Users/dashboard");
}
else
{
echo "a";
}
}
Model:
class loginModel extends CI_Model
{
public function loginValidation($email,$pass)
{
$q = $this->db->where(['email' => $email, 'password' => $pass])
->get('users');
if($q->num_rows())
{
return $q->row();
}
else
{
return false;
}
}
}
Controller where i am printing it for testing:
class Users extends CI_Controller
{
public function dashboard()
{
echo $this->session->userdata('user_name'); // Empty no data showing
exit;
}
}
Your code has a few errors and oversights.
You should NEVER store plaintext passwords, let alone add them to a session variable. There is no need for that. Check out: http://php.net/manual/en/function.password-verify.php
You need to check whether or not the login function actually returned data, otherwise just anyone can "login" as long as they pass form validation.
You are setting session data with an array incorrectly according to the way you want to access the variables.
Controller:
public function loginFormValidation() {
$this->form_validation->set_rules('email', 'Username', 'required');
$this->form_validation->set_rules('pass', 'Password', 'required');
$this->form_validation->set_error_delimiters('<div class = "text-danger">', '</div>');
if ($this->form_validation->run()) {
$email = $this->input->post('email');
$pass = $this->input->post('pass'); // do not store plaintext!!!
$this->load->model('loginModel');
$result = $this->loginModel->loginValidation($email, $pass);
if ($result) {
$user_id = $result->user_id;
$user_name = $result->user_name;
$password = $result->password;
//https://www.codeigniter.com/user_guide/libraries/sessions.html#adding-session-data
$arrayDb = array(
'user_id' => $user_id,
'user_name' => $user_name,
'password' => $password, // why are you storing their PLAINTEXT password in a session?!
);
$this->session->set_userdata($arrayDb);
header("location:" . base_url() . "/Users/dashboard");
} else {
echo 'login failed; bad username/password.';
}
} else {
echo validation_errors();
}
}
Model:
public function loginValidation($email, $pass) {
$q = $this->db->where(['email' => $email, 'password' => $pass])
->get('users');
if ($q->num_rows() == 1) {
return $q->row();
}
return false;
}
Rather than reinventing the wheel check out: https://github.com/benedmunds/CodeIgniter-Ion-Auth
I personally use it an recommend it.
I'm trying to make a new Login/Register System. My users are able to register now but i cant get the information when they try to login
if(Input::exists()){
if (Token::check(Input::get('token'))){
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
if($validation->passed()){
// log user in
$user = new User();
$login = $user->login(Input::get('username'), md5('password'));
if($login){
echo "succes";
} else {
echo '<p>Sorry, logging in failed</p>';
}
}else{
foreach($validation->errors() as $error){
echo $error, "<br>";
}
}
}
}
This it the code why can't they login? I think it's something with the md5('password').
Because i always get the Error: Sorry, logging in failed.
This is the Passed()
public function passed() {
return $this->_passed;
}
And this is the one for the login()
public function login($username = null, $password = null){
$user = $this->find($username);
if($user){
if($this->data()->password === Hash::make($password, $this->data()->salt)){
echo 'OK!';
}
}
return false;
}
private function data(){
return $this->_data;
}
i used to use salts but it took very long to generate one i i also don't know that either why that is like that i will also make soon an topic about that but for now i want to use MD5 just to make my other functionality.
Looks as though you are using Laravel? or something similar.
Try this instead:
$login = $user->login(Input::get('username'), 'password');
or perhaps you want:
$login = $user->login(Input::get('username'), Input::get('password'));
The login() function seems to be already doing the conversion to hash with Hash::make
I have a log in form that checks the user email and password through the database, if it matches, it allow the user to log in. The problem is it checks the email that matches any password in the database or the password that matches any emails in the database. I want it to check this specific user email to match his password, not matches any password that exists in database.
Here's my controller that I think I did it wrong:
$loginForm = new Application_Form_UserLogin();
if ($this->getRequest()->isPost('loginForm'))
{
$email_adrress = $this->getRequest()->getParam('email_address');
$password = $this->getRequest()->getParam('password');
/************ Login Form ************/
if ($loginForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($loginForm->getValues());
$user = $this->_helper->model('Users')->fetchRowByFields(array('email' => $email_adrress, 'hash' => $password));
if($user)
{
Zend_Session::rememberMe(86400 * 14);
Zend_Auth::getInstance()->getStorage()->write($user);
$this->getHelper('redirector')->gotoRoute(array(), 'invite');
return;
}
else {
}
}
}$this->view->loginForm = $loginForm;
My form:
class Application_Form_UserLogin extends Zend_Form
{
public $email, $password, $submit;
public function init()
{
$this->setName('loginForm');
$EmailExists = new Zend_Validate_Db_RecordExists(
array(
'table' => 'users',
'field' => 'email'
)
);
//$EmailExists->setMessage('Invalid email address, please try again. *');
$PasswordExists = new Zend_Validate_Db_RecordExists(
array(
'table' => 'users',
'field' => 'hash'
)
);
$PasswordExists->setMessage('Invalid password, please try again. *');
$this->email = $this->createElement('text', 'email_address')
->setLabel('Email')
->addValidator($EmailExists)
->addValidator('EmailAddress')
->setRequired(true);
$this->password = $this->createElement('text', 'password')
->setLabel('Password')
->addValidator($PasswordExists)
->setRequired(true);
$this->submitButton = $this->createElement('button', 'btn_login')
->setLabel('Login')
->setAttrib('type', 'submit');
$this->addElements(array($this->email, $this->password, $this->submit));
$elementDecorators = array(
'ViewHelper'
);
$this->setElementDecorators($elementDecorators);
}
}
I wouldn't add this login processing as a validator on one of the elements. Instead, I would create an Zend_Auth authentication adapter with your User model, email, and password as constructor arguments. Then, in controller, call Zend_Auth::authenticate($adapter).
Something like:
class Application_Model_AuthAdapter implements Zend_Auth_Adapter_Interface
{
protected $userModel;
protected $email;
protected $pass;
public function __construct($userModel, $email, $pass)
{
$this->userModel = $userModel;
$this->email = $email;
$this->pass = $pass;
}
public function authenticate()
{
$user = $this->userModel->getByEmailAndPassword($this->email, $this->pass);
if ($user){
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $user);
} else {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, null);
}
}
}
Then in your controller:
public function loginAction()
{
$form = new Application_Form_UserLogin();
if ($this->_request->isPost()) {
if ($form->isValid($this->_request->getPost())) {
$data = $form->getValues();
$email = $data['email'];
$pass = $data['pass'];
$userModel = $this->_helper->model('Users');
$authAdapter = new Application_Model_AuthAdapter($userModel, $email, $pass);
$result = Zend_Auth::getInstance()->authenticate($adapter);
if ($result->isValid()){
// $user= $result->getIdentity(). Use it how you like.
// Redirect someplace
} else {
$this->view->error = 'Invalid login';
}
}
}
$this->view->form = $form;
}
See Zend_Auth reference for more details.
I'm not familiar with the way you're trying to do it. Is the fetchRowByFields method one you have written yourself? If so, it's difficult to help you without seeing the code.
Have you considered using the mechanism provided by Zend Framework to perform authentication against a database?
The Zend Framework official manual contains a brief tutorial on how to implement authentication:
http://framework.zend.com/manual/1.12/en/learning.multiuser.authentication.html
You use an adapter with the Zend_Auth class to do what you want.
Hi there I am new to laravel and I am trying to code functionality of my login form here are the codes:
this is how I create new user (works well)
public function action_newuser()
{
$email = Input::get('email');
$password = Input::get('password');
$new_user = Input::get('new_user', 'off');
$first_name= Input::get('firstname');
$last_name= Input::get('last_name');
$username= Input::get('username');
$user = new User();
$user->email = $email;
$user->password = Hash::make($password);
$user->first_name =$first_name;
$user->last_name= $last_name;
$user->username= $username;
try{
$user->save();
}
catch(Exception $e) {
echo "Failed to create new user!";
}
This is my login function:
public function action_login()
{
$password = Input::get('password');
$username= Input::get('username');
$remember= Input::get('remember', 'off');
if($remember =='off') $remember=FALSE;
if($remember =='on') $remember=TRUE;
$credentials = array(
'username' => $username,
'password' => $password,
'remember' => $remember
);
if( Auth::attempt($credentials))
{
return Redirect::to('dashboard/index');
}
else
{
#I put this line to check are the values passed from my form are correct.
echo $password.' ' .$username.' '. $remember;
}
}
When I submit login form it always shows a blank page has values of $password, $username and $remember values. This means Auth::attempt() is not working well.
What can be the problem?
Fool me!
Although I have checked it many times, I could not see the line 'username' => 'email', in auth config file.
it should be 'username' => 'username', since I am going to use username for login.
Check to make sure that your database password field is 60 characters.
To all laravel 4 developers who are facing the Auth::attempt() login failure with valid creditials!
Solution:
In app/config/app.php change type: 'cipher' => MCRYPT_RIJNDAEL_128 to 'cipher' => MCRYPT_RIJNDAEL_256 and re-hash all passwords
In Model add method:
public function setPasswordAttribute($pass) {
$this->attributes['password'] = Hash::make($pass);
}
In UserController:
//Create User or Register
public function postCreate() {
$input = Input::all();
$user = new User;
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user = User::create($input);
return Redirect::action("Frontend\HomeController#index");
}
//Login or Sign in
public function postSignin() {
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if (Auth::attempt($userdata, true)) {
Session::put('username', Auth::user()->username);
return Redirect::action("Frontend\HomeController#index");
} else {
return Redirect::action("Frontend\UserController#getLogin")
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
Hope i have helped someone out there