Joomla 2.5 create user in php script without email address - php

I have a a php function that works for creating a new user in Joomla 2.5. This function is used to synchronize an external customer database with Joomla.
The new requirement is that the email address needs to be an optional field. I can't seem to get the JFactory function to work without an email address. Is there another way to get the user created?
function add_joomla_user($username, $email, $name, $password, $group) {
// Creates a new user in Joomla database with passed in information
$return_message = '';
$mainframe =& JFactory::getApplication("site");
$mainframe->initialise();
$user = JFactory::getUser(0); // it's important to set the "0" otherwise your admin user information will be loaded
jimport('joomla.application.component.helper'); // include libraries/application/component/helper.php
$usersParams = &JComponentHelper::getParams( 'com_users' ); // load the Params
$userdata = array(); // place user data in an array for storing.
$userdata['username'] = $username;
$userdata['email'] = $email;
$userdata['name'] = $name;
$userdata['password'] = $password;
$userdata['password2'] = $password;
$defaultUserGroup = $usersParams->get('new_usertype', $group);
$userdata['groups']=array($defaultUserGroup);
$userdata['block'] = 0; // set this to 0 so the user will be added immediately.
if (!$user->bind($userdata)) { // bind the data and if it fails raise an error
JError::raiseWarning('', JText::_( $user->getError())); // something went wrong!!
$return_message = 'Error binding data: ' . $user->getError();
}
if (!$user->save()) {
JError::raiseWarning('', JText::_( $user->getError()));
$return_message = 'Error creating user: ' . $user->getError();
} else {
$return_message = 'Created user';
}
return $return_message;
}

Joomla user handling definitely requires a unique email address for each user. It's tricky and I somewhat hesitate to suggest this, but what you could do if it is missing is substitute a random string or a string generated based on information in your database (like the $userdata['email'] = $username . '#noemail';. That way they will be easy to find later. Of course this means password reset and other functions will never work, but that would be true anyway if the user has no email.

Related

Code From Book Doesn't Log Me in Automatically PHP & MariaDB

I register my user, but when I log in after registration I'm told to log in again. Please help.
Here's my code:
<?php
// include function files for this application
require_once('bookmark_fns.php');
session_start();
//create short variable names
if (!isset($_POST['username'])) {
//if not isset -> set with dummy value
$_POST['username'] = " ";
}
$username = $_POST['username'];
if (!isset($_POST['passwd'])) {
//if not isset -> set with dummy value
$_POST['passwd'] = " ";
}
$passwd = $_POST['passwd'];
if ($username && $passwd) {
// they have just tried logging in
try {
login($username, $passwd);
// if they are in the database register the user id
$_SESSION['valid_user'] = $username;
}
catch(Exception $e) {
// unsuccessful login
do_html_header('Problem:');
echo 'You could not be logged in.<br>
You must be logged in to view this page.';
do_html_url('login.php', 'Login');
do_html_footer();
exit;
}
}
do_html_header('Home');
check_valid_user();
// get the bookmarks this user has saved
if ($url_array = get_user_urls($_SESSION['valid_user'])) {
display_user_urls($url_array);
}
// give menu of options
display_user_menu();
do_html_footer();
?>
I tried using this member.php code but it doesn't work the way I want it to. Please help me get the book example to work properly and log me in right after registration

Implementing a check for user levels

I'm attempted to create a login authentication system using PHP. So far I've managed to query the DB to check if a username/password given by the user matches any rows in the DB. However I have a column in the DB named "isadmin" which stores a boolean value. I want to implement a check if true/false. Depending on the result depends on which php file is loaded (included).
EDIT: I have two php files, both containing the same HTML displaying the index page of a website. However, one php file is for regular users, the other is for admin users which will contain added features. When a user enters their username and password, I want a check for the user level of that login, Once the check is done it should show the appropriate php page.
$stmt = $pdo->prepare('SELECT * FROM Reg_User WHERE username = :username AND password = :password');
$details = [
'username' => $_POST['username'],
'password' => sha1($_POST['password'])
];
unset($_POST['submit']);
$stmt->execute($details);
if ($stmt->rowCount() > 0) {
$user = $stmt->fetch();
$_SESSION['loggedin'] = $user['user_id'];
echo 'Logged in as ' . $_POST['username'];
include 'index.php';
}
else {
echo 'Sorry, your username and password could not be found Please <a href="login.html">try again
or register!</a>';
}
A simple if/else statement will do it.
if ($user["isadmin"]) {
echo "Logged in as an admin.";
#you can include your related php page here.
} else {
echo "Logged in as an user.";
#you can include your related php page here.
}
There's no sanitizing of user input in your code, this is a must in a login system, try this after your login form.
info: I don't use PDO, $con is the MYSQLI connection.
<?php
// Handle log in
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Sanitize username input
$username = strip_tags($username);
$username = trim($username);
$username = mysqli_real_escape_string($con, $username);
$username = urldecode($username);
// Sanitize password input
$password = strip_tags($password);
$password = trim($password);
$password = mysqli_real_escape_string($con, $password);
$password = urldecode($password);
}
?>
Your site should be set to https only, if it is ignore this link: htaccess redirect to https://www and you should be providing either a secure session cookie or a secure persistent cookie for users who are able to log in successfully. The code underneath this paragraph should be at the very top of your page before any html. This example is for time related persistent https secure cookie set to 1 day after which it will expire. You could use a session cookie but I find this annoys people if they frequent your site quite often, they don't want to have to log in again the same day if they close and reopen a browser or tab.
<?php
// All this code goes right at the top of your page before anything else!
function addcookie() {
global $condition;
if ($condition == "green") {
global $nameofcookie;
setrawcookie('loggedin', $nameofcookie, strtotime('+1 day'), '/', '', isset($_SERVER["HTTPS"]), true);
echo "<script>window.location.replace('https://example.com/mypage');</script>";
}
}
?>
The above code is will set a secure cookie using a function because you only want it firing after a successful login. The name of the cookie really should be random and unique, something based on microtime would work well. Make sure it's not anything important which could identify the user!IMPORTANT: the name of the cookie for reference should be created at the time of account creation and added to the users table so you can identify users and represent their login details.
Standard security measures should also include a separate table of the ip, time, date and username of who logged in. If your site is busy the table will fill quickly so you could set a cron job to clean old records to keep the size down, in that case you will need to add a column for datetime to identify the age of records.
Handling the login...
<?php
$condition = "red";
if (isset($_POST['login'])) {
$select_login = "select * from Reg_User where username='$username' and password='$password'";
$connect_login = mysqli_query($con, $select_login);
$rows_login = mysqli_num_rows($connect_login);
if ($rows_login == 0) {
// code here to handle failed logins, I would record them and use a 3 strike method
}
// Handle successful logins, add cookie
else {
while ($row_login=mysqli_fetch_array($connect_login)) {
// Retrieve cookie name here from table
$nameofcookie=$row_login['cookie'];
$condition = "green"; // This allows you to add the cookie
addcookie();
}
}
}
?>
Retrieving the cookie to authenticate users...
<?php
if (isset($_COOKIE['loggedin'])) {
$cookie = $_COOKIE['loggedin'];
$select_authenticated_user = "select * from Reg_User where cookie='$cookie'";
$connect_authenticated_user = mysqli_query($con, $select_authenticated_user);
while ($row_authenticated_user=mysqli_fetch_array($connect_authenticated_user)) {
// Retrieve values here from table
$logged_in_user=$row_authenticated_user['username'];
$logged_in_admin=$row_authenticated_user['isadmin'];
// Resolve admin status
if ($logged_in_admin == TRUE) {
$type = "admin";
} else {
$type = "member";
}
}
// Echo statement for logged in user with admin or not status, you could change the echo to a variable name if you want to use this in a specific place on your page.
echo "Welcome $logged_in_user<br/>
Type: $type
";
}
?>
Here's a link for obtaining IP's: How to get the client IP address in PHP

How to add user in group using LDAP php?

I tried much time to create a user in the group but could not have been. While I am able to create a user but not in a group. My Group name is RDP and Netmetric is the folder where I am creating a user.
if($ldapbind = ldap_bind($ldap_conn, $username, $password) == true)
{ // if ldap bind
$adduserAD["cn"] = $name;// Common name
$adduserAD["givenname"] = $name;
$adduserAD["sn"] = 'Kumar'; // Surname
$adduserAD["sAMAccountName"] = $name; // SamaAccountname declare here
$adduserAD['userPrincipalName'] = $name;
$adduserAD["objectClass"] = "User"; // Object class user
$adduserAD["displayname"] = "Test User";
$adduserAD['mail'] = $email;
$adduserAD["userPassword"] = $pwd; // set password here
$adduserAD["userAccountControl"] = "66080";
$base_dn = "cn=".$name.",ou=Netmetric,DC=ntop,DC=local";// base dn
// Attempt to add the user with ldap_add()
if(ldap_add($ldap_conn, $base_dn, $adduserAD) == true){
echo "User is created";
}
ldap_close($ldap_conn);
}else{
echo "Not connected with server";
}
Since you have a openldap tag on question, I'm assuming you are trying to add users in OpenLDAP database.
If that is the case you should get an error because sAMAccountName,userPrincipalName,userAccountControl attributes are not present in OpenLDAP schema.

Resolving a PHP PDO Error: SQLSTATE[42000] [1044]

Found lots of similar problems on this site, but the solutions for those issues don't seem to reply. The user in question has full access to the database, and from what I can tell I'm not missing any commas etc. A second set of eyes would be great.
Submitted signature is in an acceptable formatTrying to open a connectionError!: SQLSTATE[42000] [1044] Access denied for user 'emkinsti_user1'#'localhost' to database 'signatures'
<?php
// Tracks what fields have validation errors
$errors = array();
// Default to showing the form
$show_form = true;
// 1. Get the input from the form
// Using the PHP filters are the most secure way of doing it
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$output = filter_input(INPUT_POST, 'output', FILTER_UNSAFE_RAW);
// 2. Confirm the form was submitted before doing anything else
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 3. Validate that a name was typed in
if (empty($name)) {
$errors['name'] = true;
}
// 3. Validate that the submitted signature is in an acceptable format
if (!json_decode($output)) {
$errors['output'] = true;
}
}
// No validation errors exist, so we can start the database stuff
if (empty($errors)) {
echo "Submitted signature is in an acceptable format";"<br/>";
$dsn = 'mysql:host=localhost;dbname=signatures';
$user = 'emkinsti_user1';
$pass = '6nqq103t26';
}
// 4. Open a connection to the database using PDO
try {
echo "Trying to open a connection";
$db = new PDO($dsn, $user, $pass);
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// Make sure we are talking to the database in UTF-8
$db->exec('SET NAMES utf8');
// Create some other pieces of information about the user
// to confirm the legitimacy of their signature
$sig_hash = sha1($output);
$created = time();
$ip = $_SERVER['REMOTE_ADDR'];
// 5. Use PDO prepare to insert all the information into the database
$sql = $db->prepare('INSERT INTO signatures (signator, signature, sig_hash, ip, created)
VALUES (:signator, :signature, :sig_hash, :ip, :created)');
$sql->bindValue(':signator', $name, PDO::PARAM_STR);
$sql->bindValue(':signature', $output, PDO::PARAM_STR);
$sql->bindValue(':sig_hash', $sig_hash, PDO::PARAM_STR);
$sql->bindValue(':ip', $ip, PDO::PARAM_STR);
$sql->bindValue(':created', $created, PDO::PARAM_INT);
$sql->execute();
// 6. Trigger the display of the signature regeneration
$show_form = false;
// mysql_close($db);
$db = null;
?>
emkinsti_user1'#'localhost' to database 'signatures'
if you are using CPanel, CPanel uses prefixes also to the database name:
You used: emkinsti_user1 as users.
You should use: emkinsti_signatures as database name.
Log in into your CPanel and there you will find the database name with prefix
Try http://php.net/manual/en/pdo.getavailabledrivers.php to see if the database is supported by PDO.
<?php
print_r(PDO::getAvailableDrivers());
?>
Just an idea. I would expect another error message when it isn't. So, as far as I can tell, the user has no access when accessing the database from the local host.

Joomla 2.5 - Log user in without password

I'm building a custom joomla component and am looking into ways I can set a login session without using an account password. I already have:
$app = &JFactory::getApplication('site');
$result = $app->login(array(
'username' => 'james',
'password' => 'password'
));
Which obviously requires the users password. I have access to the user ID and username so either of these handles can be used. Is there another object or method I can use to log a user in or is there some custom solution I can use e.g manually set all required $_SESSION variables?
Thanks in advance, any help much appreciated :)
IMPORTANT: Is necesary to add the session Object after // Register the needed session variables
// Register the needed session variables
$session =& JFactory::getSession();
$session->set('user', $jUser);
Excellent, thx
//log user in
if(!JFactory::getUser()->id)
{
$email = (string)$response['linkedin']->{'email-address'};
$db = JFactory::getDbo();
$app = JFactory::getApplication();
$sql = "SELECT * FROM #__users WHERE email = " . $db->quote($email);
$db->setQuery($sql);
$result = $db->loadObject();
if($result->id)
{
$jUser = JFactory::getUser($result->id);
//$userarray = array();
//$userarray['username'] = $jUser->username;
//$userarray['password'] = $jUser->password;
//$app->login($userarray);
$instance = $jUser;
$instance->set('guest', 0);
// Register the needed session variables
$session =& JFactory::getSession();
$session->set('user',$jUser);
// Check to see the the session already exists.
$app->checkSession();
// Update the user related fields for the Joomla sessions table.
$db->setQuery(
'UPDATE '.$db->quoteName('#__session') .
' SET '.$db->quoteName('guest').' = '.$db->quote($instance->get('guest')).',' .
' '.$db->quoteName('username').' = '.$db->quote($instance->get('username')).',' .
' '.$db->quoteName('userid').' = '.(int) $instance->get('id') .
' WHERE '.$db->quoteName('session_id').' = '.$db->quote($session->getId())
);
$db->query();
// Hit the user last visit field
$instance->setLastVisit();
//return true;
$app->redirect('index.php?option=com_community&view=profile');
}
else
{
$url = "index.php?option=com_community&view=register";
$app->redirect($url,'We did not find your email address in our system. Please register.');
//echo "redirect to registration page";
//exit();
//$url = 'index.php?option=com_users&view=registration&name=' . $user_profile['name'] . '&username=' . $user_profile['username'] . '&email=' . $user_profile['email'];
//$url = JRoute::_($url);
//$app->redirect($url);
}
}

Categories