In yii login functionality when password is wrong - authentication

In yii i am creating login functionality. When user enters correct username but wrong password i want to make serach in database for this correct username and want to put that username's id into loginattemmpt table and display wrong password message to him. So can please someone help me.

in userIdentity.php save data in table .
public function authenticate() {
$user = User::model()->findByAttributes(array('username' => $this->username));
if ($user === null) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
}
elseif($user->password !== crypt($this->password, $salt))
{ // save $user->id in attempt table here .
$this->errorCode = self::ERROR_PASSWORD_INVALID;
}else{
//set id
}
and in file from where authenticate function is called setError.
$this->_identity = new UserIdentity($this->username, $this->password);
if (!$this->_identity->authenticate())
if ($this->_identity->errorCode === UserIdentity::ERROR_USERNAME_INVALID) {
$this->addError('password', 'Incorrect email Id');
}elseif($this->_identity->errorCode === UserIdentity::ERROR_PASSWORD_INVALID){
$this->addError('password', 'Incorrect Password');
}

Related

change password code is not working

I was just working on a password changing program for my website, it resulted in all my users passwords changed into the same password.
The code which I used is displayed below.
If any one could help me out it would be a big thanks to him/her.
//if form has been submitted process it
<br/>
if(isset($_POST['submit'])){
$stmt = $db->prepare('SELECT password FROM user WHERE password = :hashedpassword');
$stmt->execute(array(':hashedpassword' => $_POST['password']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(strlen($_POST['password']) < 3){
$error[] = 'Password is too short.';
}
if(strlen($_POST['passwordConfirm']) < 3){
$error[] = 'Confirm password is too short.';
}
if($_POST['password'] != $_POST['passwordConfirm']){
$error[] = 'Passwords do not match.';
}
//if no errors have been created carry on
if(!isset($error)){
//hash the password
$hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
try {
//insert into database with a prepared statement
$sql="UPDATE user SET password = :hashedpassword";
$stmt = $db->prepare($sql);
$stmt->execute(array(
':hashedpassword' => $hashedpassword
));
//redirect to index page
header('Location: login.php?action=resetAccount');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}

ZF2 - init or something that is called in every module controller

I have a Module called "Backend" and in this module I want to check for valid authentication on all pages except the backend_login page. How do I do this? I tried to add it to the onBootstrap in the Backend/Module.php , but it turns out that is called in my other modules as well... which is of course not what I want.
So how do I do this?
Thanks in advance!
To get clear information about zf2 authentication you can follow:
ZF2 authentication
adapter auth
database table auth
LDAP auth
digest auth....These all are different methods here is an example of database table auth:
in every controller's action, where you need user auth something should like this:
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Db\Adapter\Adapter as DbAdapter;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
public function login($credential)
{
$bcrypt = new Bcrypt();
$user = new User();
$auth = new AuthenticationService();
$user->exchangeArray($credential);
$password = $user->password;
$data = $this->getUserTable()->selectUser($user->username);
if (!$data){
$message = 'Username or password is not correct!';
}
elseif($auth->getIdentity() == $user->username){
$message = 'You have already logged in';
}
elseif($bcrypt->verify($password, $data->password)){
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$authAdapter = new AuthAdapter(
$dbAdapter,
'user',
'username',
'password'
);
$authAdapter -> setIdentity($user->username) -> setCredential($data->password);
$result = $auth->authenticate($authAdapter);
$message = "Login succesfull.Welcome ".$result->getIdentity();
} else {
$message = 'Username or password is not correct';
}
return new ViewModel(array("message" =>$message));
}
Like this in every action you can check whether it is authenticated or not
if($auth -> hasIdentity()){
//your stuff
}
else{
//redirected to your login route;
}
I had once a similar problem and figured it out within my Module.php in the onBootstrap() function. Try this, it worked for me:
class Module {
// white list to access with being non-authenticated
//the list may contain action names, controller names as well as route names
protected $whitelist = array('login');
//....
public function onBootstrap($e){
$app = $e->getApplication();
$em = $app->getEventManager();
$sm = $app->getServiceManager();
$list = $this->whitelist;
$auth = new AuthenticationService();
$em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
$match = $e->getRouteMatch();
// No route match, this is a 404
if (!$match instanceof RouteMatch) {
return;
}
// Route is whitelisted
$action = $match->getParam('action');
if (in_array($action, $list) ) {
return;
}
// User is authenticated
if ($auth->hasIdentity()){
return;
}
// the user isn't authenticated
// redirect to the user login page, as an example
$router = $e->getRouter();
$url = $router->assemble(array(
'controller' => 'auth',
'action'=>'login'
), array(
'name' => 'route_name',
));
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
return $response;
}, -100);
}
}
Or you may see bjyauthorize.

In yii how to send password reset link

In yii i am creating forget password functionality.For this user enters email id.If this email id is correct then i want to retrieve securityQuestion id from database and display that question to user.if his answer is correct then password reset link will get send to user's email id. In controller i had made action as
public function ActionForget{if(isset($_POST['email']))
{ $record=User::model()->find(array(
'select'=>'primaryEmail',
'condition'=>'PrimaryEmail=:email',
'params'=>array(':email'=>$_POST['email']))
); if($record===null) {
$error = 'Email invalid';
} else {
$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
$mailer->IsSMTP();
$mailer->IsHTML(true);
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = "ssl";
$mailer->Host = "smtp.gmail.com";
$mailer->Port = 465;
$mailer->CharSet = 'UTF-8';
$mailer->Username = "abc#shailani.com";
$mailer->Password = "abc";
$mailer->From = "xyz#shailani.com";
$mailer->FromName = "Balaee.com";
$mailer->AddAddress($record);
$mailer->Subject = "welcome to Balaee";
$mailer->IsHTML(true);
$mailer->Body = "<h1>Thanks to showing interest </h1><br>click on link for other detail ".$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if($mailer->Send()) {echo "Please check mail";}
else {echo "Fail to send your message!"; }}}
else{ $this->render('emailForm'); //show the view with the password field}}
I am having password.php as view file for entering primary email id and submit button
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'email-form',
'enableClientValidation'=>true,
));
echo CHtml::textField('email');
echo CHtml::submitButton('Send');
$this->endWidget();
But after submiiting primary email id by user,no action takes place. So can please someone tell me what changes i need to do
Shouldn't the name of the controller method be actionForgot instead of ActionForgot. PHP is case sensitive, also when you render the page send the model with it like this->render->('emailForm',$email) where $email is your model name
Ok I like the start, and here are some of the fixes to the existing code above.
However what was your plan once you successfully sent the e-mail; see the existing code gets you a url that looks like this http://yoursite.com/yourapp/user/forget and that will bring you right back to the form in which you enter your email, thus creating a giant loop.
See the link should in fact create be validated and thus giving the user access to their user record. You need some other function to validate and allow for the password change.
<code>
public function actionForget() {
if(isset($_POST['email'])) {
$record=User::model()->findByAttributes(array('email' => Yii::app()->request->getPost('email')));
if ($record != NULL) {
$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
$mailer->IsSMTP();
$mailer->IsHTML(true);
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = "ssl";
$mailer->Host = "smtp.gmail.com";
$mailer->Port = 465;
$mailer->CharSet = 'UTF-8';
$mailer->Username = "yourgmailacccount#gmail.com";
$mailer->Password = "P#ssWord";
$mailer->From = "yourfromemail#yourdomain.com";
$mailer->FromName = "HQ-DEV-01";
$mailer->AddAddress($_POST['email']);
$mailer->Subject = "welcome to CES Document Site";
$mailer->IsHTML(true);
$mailer->Body = "<h1>Thanks, please</h1><br>
click on link for other detail
".$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if($mailer->Send()) {
echo "Please check your email";
}
else {
echo "Fail to send your message!";
}
} else {
echo 'Email invalid';
}
else {
$this->render('password');
Yii::app()->user->setFlash('error', "Email is not valid!");
//echo 'Email invalid';
}
}
else{ $this->render('password'); //show the view with the password field}}
Yii::app()->user->setFlash('info', "Enter a valid e-mail!");
}
}

Login with Kohana auth module - what am I doing wrong?

I'm trying to login with the following controller action, but my login attempt keeps failing (I get the 'invalid username and/or password' message). What am I doing wrong? I also tried the other method given in the examples in the auth documentation, Auth::instance()->login($user->username, $form->password);, but I get the same result. Kohana version is 2.3.4.
public function login() {
$auth = Auth::instance();
if ($auth->logged_in()) {
url::redirect('/account/summary');
}
$view = new View('login');
$view->username = '';
$view->password = '';
$post = $this->input->post();
$form = new Validation($post);
$form->pre_filter('trim', 'username')
->pre_filter('trim', 'password')
->add_rules('username', 'required');
$failed = false;
if (!empty($post) && $form->validate()) {
$login = array(
'username' => $form->username,
'password' => $form->password,
);
if (ORM::factory('user')->login($login)) {
url::redirect('/accounts/summary');
} else {
$view->username = $form->username;
$view->message = in_array('required', $form->errors()) ?
'Username and password are required.' :
'Invalid username and/or password.';
}
}
$view->render(true);
}
Figured out my problem... Something in my registration process is missing, because it's creating the user record but not the role-to-user assoc record. Login needs a specific role to log in to, or it won't work even with a valid username and password. Manually inserting the record allowed my to log in, so I'll just have to debug my registration action a bit.

CakePHP Auth Component Using 2 Tables

CakePHP Version 1.2.5
I would like a single user to have multiple email addresses.
I would like a single user to have a single password.
I would like users to log in using any of their multiple email addresses and their single password.
I have created a users table with an id and a password field.
I have created a user_email_addresses table with an id field a user_id field and an email_address field.
Question:
How do I modify the auth component minimally to look for the "username" in this case, "email_address", in the user_email_addresses table and the "password" in the users table?
Seems as though modifying the identify method in the auth component might do it. But I think modifying the auth component directly is a bad idea - any ideas on how to extend and still possibly modify the identify method? http://cakebaker.42dh.com/2009/09/08/extending-cakephps-core-components/ or possibly nominate a different authenticate object?
Starting line 774:
function identify($user = null, $conditions = null) {
if ($conditions === false) {
$conditions = null;
} elseif (is_array($conditions)) {
$conditions = array_merge((array)$this->userScope, $conditions);
} else {
$conditions = $this->userScope;
}
if (empty($user)) {
$user = $this->user();
if (empty($user)) {
return null;
}
} elseif (is_object($user) && is_a($user, 'Model')) {
if (!$user->exists()) {
return null;
}
$user = $user->read();
$user = $user[$this->userModel];
} elseif (is_array($user) && isset($user[$this->userModel])) {
$user = $user[$this->userModel];
}
if (is_array($user) && (isset($user[$this->fields['username']]) || isset($user[$this->userModel . '.' . $this->fields['username']]))) {
if (isset($user[$this->fields['username']]) && !empty($user[$this->fields['username']]) && !empty($user[$this->fields['password']])) {
if (trim($user[$this->fields['username']]) == '=' || trim($user[$this->fields['password']]) == '=') {
return false;
}
$find = array(
$this->userModel.'.'.$this->fields['username'] => $user[$this->fields['username']],
$this->userModel.'.'.$this->fields['password'] => $user[$this->fields['password']]
);
} elseif (isset($user[$this->userModel . '.' . $this->fields['username']]) && !empty($user[$this->userModel . '.' . $this->fields['username']])) {
if (trim($user[$this->userModel . '.' . $this->fields['username']]) == '=' || trim($user[$this->userModel . '.' . $this->fields['password']]) == '=') {
return false;
}
$find = array(
$this->userModel.'.'.$this->fields['username'] => $user[$this->userModel . '.' . $this->fields['username']],
$this->userModel.'.'.$this->fields['password'] => $user[$this->userModel . '.' . $this->fields['password']]
);
} else {
return false;
}
$model =& $this->getModel();
$data = $model->find(array_merge($find, $conditions), null, null, 0);
if (empty($data) || empty($data[$this->userModel])) {
return null;
}
} elseif (!empty($user) && is_string($user)) {
$model =& $this->getModel();
$data = $model->find(array_merge(array($model->escapeField() => $user), $conditions));
if (empty($data) || empty($data[$this->userModel])) {
return null;
}
}
if (!empty($data)) {
if (!empty($data[$this->userModel][$this->fields['password']])) {
unset($data[$this->userModel][$this->fields['password']]);
}
return $data[$this->userModel];
}
return null;
}
AuthComponent::identify() takes two parameters, $user and $conditions
if ($conditions === false) {
$conditions = null;
} elseif (is_array($conditions)) {
$conditions = array_merge((array)$this->userScope, $conditions);
} else {
$conditions = $this->userScope;
}
Looking at the above snippet, if you pass false as the $conditions, the method will execute with no model conditions.
Also, looking at the rest of the code, if you pass a $user value of type string, it won't execute most of the user-related code until it gets here:
} elseif (!empty($user) && is_string($user)) {
$model =& $this->getModel();
$data = $model->find(array_merge(array($model->escapeField() => $user), $conditions));
if (empty($data) || empty($data[$this->userModel])) {
return null;
}
}
Here it runs Model::escapeField(), with no parameters, which returns an escaped version of User.id (by default) and maps this field to the string that was passed in. It then merges this with the $conditions array and performs a Model::find().
It should be safe to say that if the string is the user's ID and there are no conditions it will find the person with that ID every time.
As such, you should be able to extend AuthComponent to do what you want like so:
// app/controllers/components/app_auth.php
<?php
App::import('Component', 'Auth');
class AppAuthComponent extends AuthComponent {
/**
* Custom user identification
*/
function identify($user=null, $conditions=null) {
// get the model AuthComponent is configured to use
$model =& $this->getModel(); // default is User
// do a query that will find a User record when given successful login data
$user = $model->find('first', array('conditions' => array(
'EmailAddress.' . $this->fields['username'] => $user[$this->userModel][$this->fields['username']],
'User.' . $this->fields['password'] => $user[$this->userModel][$this->fields['password']],
));
// return null if user invalid
if (!$user) {
return null; // this is what AuthComponent::identify would return on failure
}
// call original AuthComponent::identify with string for $user and false for $conditions
return parent::identify($user[$this->userModel][$model->primaryKey], false);
}
}
?>
You will have to replace all references to Auth with AppAuth in your application unless you follow this handy tip (the approach in the comments is nice).