I've inherited a joomla 1.5 site that has a reset password component that isn't functioning optimally. ATM I'm able to have password resets sent to the user inputted email, but the component is missing a function that checks against existing users to see if the email is valid. I'm rather new to PHP, so I'm not 100% sure how to introduce an additional if statement.
Here's how's it looking so far:
public function submitemail() {
$db = JFactory::getDBO() ;
$requestedEmail = JRequest::getVar('emailaddr' , '') ;
$db->setQuery('select id , username, name, email from #__users where block = 0 and email = "'.$requestedEmail.'"') ;
if( $user = $db->loadObject() ) {
// Make sure the user isn't a Super Admin.
$juser = JFactory::getUser($user->id) ;
//joomla 1.6 and 1.5 check
if ($juser->authorize('core.admin') || $juser->usertype == 'Super Administrator') {
$this->setRedirect( 'index.php?option=com_resetpassword' , 'Email is not valid' ) ;
}
else {
$result = $this->sendPasswordResetEmail( $user ) ;
$this->setRedirect( 'index.php?option=com_resetpassword&layout=success' //, 'Please check your email and follow the instructions to reset your password '
) ;
}
}
else {
$this->setRedirect( 'index.php?option=com_resetpassword' );
}
}
And I happened across a related post where I found this snippet. How would I go about checking against email addresses that are currently in my database against the user inputted email for the reset?
function validate()
{ jimport('joomla.mail.helper');
$valid = true;
if ($this->_data->email && !JMailHelper::isEmailAddress($this->_data->email))
{
$this->_app->enqueueMessage(JText::_('Invalid Email Address'),'error');
$valid = false;
}
return $valid;
}
That is actually exactly what it is doing already. The top loads the row for the user based on the email address that is submitted:
$requestedEmail = JRequest::getVar('emailaddr' , '') ;
$db->setQuery('select id , username, name, email from #__users where block = 0 and email = "'.$requestedEmail.'"') ;
if( $user = $db->loadObject() ) {
...
All you likely need to do is add a message for when this fails to the else statement at the bottom:
else {
$this->_app->enqueueMessage(JText::_('Invalid Email Address'),'error');
$this->setRedirect( 'index.php?option=com_resetpassword' );
}
If $this->_app isn't set, you should be able to get that by using this instead:
JFactory::getApplication()->enqueueMessage(JText::_('Invalid Email Address'),'error');
Related
I have a login script I want if user attempt 3 invalid password then the username associated to them would be disabled or blocked for a day / 24hrs.
Since I make a if condition in php login code where status=3 alert your account is blocked for a day.
status is my database column name which count the value of invalid login of user from 1 to 3 maximum.
But issue is my here that is how I make the status automatically count or increase like 1, 2, 3 in user invalid login.
How to I add this function with my login code
I have not idea about that. On YouTube there is not any video regards this even in other website.
Stackoverflow is my last hope where someone helps user.
Please have a look at this question and help to create satatus count automatic when user inter invalid password.
My login PHP is : https://pastebin.com/QpwDtjBg
Thank you in advance
You're gonna want to use PHP's $_SESSION object.
In the code block where you detect bad user/pass combos, add an iterator to the session.
First, add a session entry to the top of your script (Or wherever you define global variables), for bad_logins, and start your session.
session_start();
$_SESSION['bad_logins'] = 0;
Then in the part of your code where you detect a bad login, increment the bad logins by 1.
$_SESSION['bad_logins']++;
This will allow you to then check for bad attempts with an if statement
if($_SESSION['bad_logins'] > 3) {
// Do something here.
}
The script you linked has some other issues you may want to address prior to adding this in though.
You just need to add an update to the field 'status' on the database with 1, 2 or 3, on the IF condition:
if($data == NULL || password_verify($password, $data['Password']) == false) {
And read that same field, when the submit form is sent every single time... if it is already 3, then just skip to the IF condition
if($data['Status'] == "//auto count//")
Something like this (haven't tested the code) and the code should be function based, at least...
`
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(isset($_POST['submit'])) {
$messages = array(
'INVALID_EMAIL' => "<div class='alert-box warning error'><span>Invalid format, re-enter valid email.</span></div>",
'ALL_FIELDS_REQUIRED' => "All field is mandatory! case sensitive.",
'VERIFY_EMAIL' => "Please verify your email!",
'INVALID_COMBINATION' => "Invalid username or password combinations.",
'BLOCKED' => "you are blocked for a day. <a href='#'><span>Know why?<span></a>",
);
$msg = "";
$error = false;
$con = new mysqli("localhost", "softwebs_softweb", "test#123", "softwebs_cms");
$email = $con->real_escape_string(htmlspecialchars($_POST['username']));
$password = $con->real_escape_string(htmlspecialchars($_POST['password']));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = $messages['INVALID_EMAIL'];
$error = true;
}
if ($email == "" || $password == "") {
$msg = $messages['ALL_FIELDS_REQUIRED'];
$error = true;
}
if(!$error) {
$sql = $con->query("SELECT * FROM users where Email_ID = '$email' ");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
// Blocked
if ($date['status'] === 3) {
$msg = $messages['BLOCKED'];
$error = true;
}
if ($data['isEmailConfirm'] == "0") {
$msg = $messages['VERIFY_EMAIL'];
$error = true;
}
if ($data == NULL || password_verify($password, $data['Password']) == false) {
$msg = $messages['INVALID_COMBINATION'];
$error = true;
// Update the status + 1
$sql = $con->query("UPDATE users SET status = " . $statusData['status'] + 1 . " WHERE Email_ID = '$email' ");
}
}
}
if($error && trim($msg) !== "") {
$msg = "<div class='alert-box error'><span>$msg</span></div>";
} else {
session_start();
$_SESSION['login']=$_POST['username'];
$_SESSION['id']=$data['id'];
header('location: ./account/dashboard.php');
}
}
?>
`
I can't find it anywhere in the documentation of Code Igniter - Community Auth how to check user credentials by using simple function. I want to just call a function.
Example: checkIfValid('username', 'mypassword123')
$uid = array_key_exists('uid', $_POST) ? (empty($_POST['uid']) ? '' : $_POST['uid']) : '';
$pwd = array_key_exists('pwd', $_POST) ? (empty($_POST['pwd']) ? '' : $_POST['pwd']) : '';
if ($uid == '' || $pwd == '') { echo $error_response; return; };
$auth_model = $this->authentication->auth_model;
// HOW CAN I LOGIN WITH BOTH USERNAME AND PASSWORD LIKE CALLING A FUNCTION? THIS CODE ONLY LOGS IN USER UID ONLY
$auth_data = $this->{$auth_model}->get_auth_data($uid);
if ($auth_data) {
$this->authentication->maintain_state($auth_data);
echo 'login';
return;
}
On your controller Authentication takes place here
$this->load->library('authentication');
$res = $this->authentication->login( $requirement, $user_string, $passwd ); // requirement is user level
if ($res)
{
echo "User authenticated"; // or do something here
}
else
{
print_r($res); // or do something what ever
}
I'm not sure but try this.
// Get normal authentication data using username or password
if( $auth_data = $this->{$auth_model}->get_auth_data( $uid,$pwd ) )
{
/**
* If redirect param exists, user redirected there.
* This is entirely optional, and can be removed if
* no redirect is desired.
*/
$_GET['redirect'] = 'somewhere';
$this->authentication->redirect_after_login();
// Set auth related session / cookies
$this->authentication->maintain_state( $auth_data );
}
}
else
{
echo 'Example requires that you set a username or password.';
}
My login system md5 hashes the username and I password_hash the password. Therefore I cannot fetch the row based on the username? My client then enters an email address which I base64encode. I then offer a lost password change option. However, when I UPDATE the field using the same type of hash but, using the email field as an identifier, the new password is incorrect?
Below is a sample of my UPDATE, but hard coded for illustration(PS this does not work either?).
$em = 'example#example.com';
$em1 = base64_encode($em);
$ps = 'some password';
$password_hash = password_hash($ps, PASSWORD_BCRYPT);
$qu = "UPADTE table SET field = '$password_hash' WHERE email = '$em1'";
$res = mysqli_query($link, $qu);
Edited question to include my code after verifying that the user exists and sending out an email for them to positively identify themselves as the owner of the account. Here is the final processor page.
if(EMPTY($_POST[psw1]) ) {
echo "New password must be supplied"; }
elseif(EMPTY($_POST[psw2]) ) {
echo "Repeat password must be entered"; }
elseif($_POST[psw1] != $_POST[psw2]) {
echo "Passwords entered do not match";
} elseif(EMPTY($_POST[eu])) {
echo "Essential data is missing in order to complete this process.";
}
elseif (strlen($_POST['psw1']) < 6) {
echo "Password must be at least six characters in length";
}
elseif (preg_replace("/[^a-zA-Z0-9]/", "", $_POST['psw1']) != $_POST['psw1']) {
echo "Password may only contain letters and numbers";
}
elseif(!EMPTY($_POST[psw1]) && !EMPTY($_POST[psw2]) && !EMPTY($_POST[eu]) && $_POST[pw1] == $_POST[pw2] ) {
include "conn.php";
echo "$_POST[eu]<br />";
$eu = $_POST[eu];
$pdw = password_hash($_POST[pw1], PASSWORD_BCRYPT);
$sq = mysqli_query($link, "UPDATE str1 SET pf = '$pdw', cu_pw_status = '2' WHERE cu_type = '$eu'");
echo "Your password has been changed, you may now login <a href='login2.php'>Login</a>";
} else {
echo "An error occured. Contact Site Admin"; }
Check if you have column 'field' in your users table. Seems suspicios.
Check your update string, now it misses table name.
Check if you have user before updating:
$exists = mysqli_query("SELECT id FROM users WHERE email='$em1');
if (!is_empty($exists)) {
mysqli_query("UPDATE TABLE users SET password = '$ps' WHERE id='$exists');
echo 'updated' . "\n";
} else {
echo 'no user with such email hash' . "\n";
}
I have a CMS, I am creating a forgotten password page, the page will require a user to enter an email address and the code will find it in the database and send them an email, in my database, i have multiple users accounts assigned to one email address.
I want it so that if the user enters an email address and it was more than one account assigned to it, to error a message saying please contact your admin, but atm, it is not doing this. Any suggestions?
Here is my forgotten password page code:
if ($lookup) {
$user->sendPasswordResetEmail();
echo"sent email";
} elseif ($lookup) {
echo "please contact your admin";
}else{
$echo"Can't find user";
}
}
}else{
echo "please enter an email address";
}
}
I take the information from a different file, here is the snippet for the code where I take the database:
$resetsystem = $db->query($qry);
if ($resetsystem && $resetsystem->num_rows == 1) {
$that->setUserData($rs->fetch_assoc());
return true;
}
if ($resetsystem && $resetsystem->num_rows > 1) {
return;
}
return false;
}
update following code:
function lookupByEmail($userID) {
global $db;
$this->id = $userID; $qry = " SELECT user_id, user_first_name, user_last_name, user_username, user_email, user_suspended FROM cms_users WHERE user_email = " . $db->SQLString($this->id) . " AND user_deleted
= 0;";
$rs = $db->query($qry);
if ($rs && $rs->num_rows == 1) {
$this->setUserData($rs->fetch_assoc());
return 1;
}
if ($rs && $rs->num_rows > 1) {
return 2;
}
return 0;
}
and then where you are checking the $found variable do these updates
if ((int)$found == 1) {
$user->sendPasswordResetEmail();
$str_Message = '<div class="success_message">User found, an email has been dispatched to you.</div>';
} elseif ((int)$found > 1) {
$errors->defineError("too_many_users", "please contact your admin", array());
}else{
$errors->defineError("user_not_found", "The specified user could not be found. Please try again.", array());
}
I'd like to make a registration input field that only accepts certain types of email addresses (e.g., one that only accepts email addresses that end with #yahoo.com) so that I can provide some security in terms of who can access my website (e.g., I want to only accept email addresses that are from students from my school, i.e., they must end in #school.edu).
Here's what i have so far, but this does not discriminate for a specific type of email:
<?php
// configuration
require("../includes/config.php");
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// validate inputs
if (empty($_POST["username"]))
{
apologize("You must provide a username.");
}
else if (empty($_POST["password"]))
{
apologize("You must provide a password.");
}
else if (empty($_POST["confirmation"]) || $_POST["password"] != $_POST["confirmation"])
{
apologize("Those passwords did not match.");
}
// try to register user
$results = query("INSERT INTO users (username, hash, cash) VALUES(?, ?, 10000.0000)",
$_POST["username"], crypt($_POST["password"])
);
if ($results === false)
{
apologize("That username appears to be taken.");
}
// get new user's ID
$rows = query("SELECT LAST_INSERT_ID() AS id");
if ($rows === false)
{
apologize("Can't find your ID.");
}
$id = $rows[0]["id"];
// log user in
$_SESSION["id"] = $id;
// redirect to portfolio
redirect("/");
}
else
{
// else render form
render("register_form.php", ["title" => "Register"]);
}
?>
You can use the substr() function combined with the strrpos() to get the last part of the email:
if(substr($email, strrpos($email, "#")) == "#school.edu") {
//all good
}
Once you have done that, you can email them a confirmation link to the email provided to make sure it's not a bogus one.
You can also use simple regex to verify user's email
if(preg_match('#^(.*)\#school\.edu$#', $_POST['email'])) {
echo 'email is valid';
} else {
echo 'this is not valid email!';
}