Create user but checking if exist in Active Directory with PHP - php

I'm working with Symfony 2.8.2, Doctrine.
I need to create users in my app data base, but first I need to check if those users exist on a external Active Directory database. Only if the user exist it will possible to create the user on the app data base. My code works for creat users, but now I'm trying to implementate the "check if the user exist first" section, I'm following some examples but I'm not sure if the way I'm doing it goes well. I've read that the usual sequence with LDAP is connect, bind, search, interpret search result, close connection. Could someone give me a hint on what should I do with my code, where should I do the search first, before or after the bind? and why.
public function createAction(Request $request){
$em = $this->getDoctrine()->getManager();
$post_send = $request->request->get('userbundle_user');
if (array_key_exists('id', $post_send)) {
$ldap_success = true;
$entity = $em->getRepository('UserBundle:User')->find($post_send['id']);
}else{
$ldapconn = ldap_connect("10.0.0.230");
$Pass= "XXXXXX";
$searchUser = "YYYYYY";
$ldap_success = false;
if (#ldap_bind($ldapconn, $searchUser, $Pass)) {
try{
$post_send['password'] = $Pass;
$attributes = ['cn'];
$filter = "(&(objectClass=user)(objectCategory=person)(userPrincipalName=".ldap_escape($post_send['username'], null, LDAP_ESCAPE_FILTER)."))";
$baseDn = "DC=XXX,DC=XX,DC=cl";
$results = #ldap_search($ldapconn, $baseDn, $filter);
//$info = #ldap_get_entries($ldapconn, $results);
if ( $results ) {
$ldap_success = true;
} else {
$ldap_success = false;//false, lo deje en true para que pudiera avanzar
}
}
catch(\Exception $e){
$ldap_success = false;
}
}
$entity = new User();
}
if( $ldap_success ){
$entity->setUsername($post_send['username']);
$entity->setRut($post_send['rut']);
//$entity->setSalt("ssss");
if (array_key_exists('password', $post_send)) {
if ( $post_send['password'] != "" ) {
$entity->setPassword($post_send['password']);
$this->setSecurePassword($entity);
}
}
$entity->setEmail($post_send['email']);
$entity->setDateAdded(new \DateTime());
$entity->setIsActive(true);
$entity->setIsAdmin(true);
$entity->setUserRoles($em->getRepository('UserBundle:Role')->find( $post_send['admin_roles_id'] ));
$entity->setWizardCompleted(true);
$entity->setPath("s");
$em->persist($entity);
$em->flush();
$json = new JsonUtils();
return $json->arrayToJson(array("id"=>$entity->getId()));
}
return $json->arrayToJson( array("sueccess"=>false ) );
}
There's a question here How do I make a ldap search with anonymous binding? related yo my problem, with no answers at all.

Regarding your AD query to check if the user exists (starting at the beginning of your else statement), I would make the logic something like this:
$ldapconn = ldap_connect("10.0.0.230");
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0)
// Use a LDAP service account with only read access...
$searchUser = 'user#myDomain.com';
$searchPass = '12345';
$ldap_success = false;
if (#ldap_bind($ldapconn, $searchUser, $searchPass)) {
$attributes = ['cn'];
$filter = "(&(objectClass=user)(objectCategory=person)(userPrincipalName=".ldap_escape($post_send['username'], null, LDAP_ESCAPE_FILTER)."))";
$baseDn = "DC=myDomain,DC=com";
$results = #ldap_search($ldapconn, $baseDn, $filter, $attributes);
$info = #ldap_get_entries($ldapconn, $results);
$ldap_success = ($info && $info['count'] === 1);
}
In that case $ldap_success would only be true if a user exists in AD with the UPN specified.
However, if you are requiring the user's password and binding to AD, then there is no reason to also verify that the user can be found via a query after binding. In that case simply binding to AD is evidence enough that they exist in AD.

Related

LDAP add user false success

i try to add a user to freeipa with the code below. the code return success but when i go to the freeipa UI the user is not visible. if i try to reinsert it will fail telling that user already exist. what can be? thanks
$con = ldap_connect($server);
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
// bind anon and find user by uid
$user_search = ldap_search($con,$dn,"(|(uid=admin))");
$user_get = ldap_get_entries($con, $user_search);
$user_entry = ldap_first_entry($con, $user_search);
$user_next = ldap_next_entry($con, $user_entry);
$user_dn = ldap_get_dn($con, $user_next);
if (ldap_bind($con, $user_dn, "adminpass") === false) {
$message[] = "Error E101 - Current Username or Password is wrong.";
}else{
$info['givenName'] = "test";
$info['cn'] = "test";
$info['sn'] = "user";
$info['mail'] = "test#localhost";
$info['objectclass'][0] = "inetorgperson";
if(ldap_add($con, "cn=test,cn=users,cn=accounts,dc=domain,dc=net", $info) === false){
$error = ldap_error($con);
$errno = ldap_errno($con);
$message[] = "$errno - $error";
}else{
$message[] = "ok";
}
}

LDAP Finding Members of a group PHP

I have a question regarding user membership of groups in Active directory and grabbing such memberships with PHP. My big question/situation is that I have a site I am making and essentially I am trying to assign administrators based off of groups in Active directory and I know how to check member of status on an account but my problem is that there are some groups that aren't displayed there, and one of the groups that is not displayed is the group I need. Is there a way I can check who is a member of that group instead of checking if that user is a member of that group. Alternatively if someone knows why certain groups are not appearing in my search I would prefer to search membership that way because then it would be a simple logic statement to check if the user is in that group, my code is below and it does work but as I said there are certain groups that don't appear and I think I read somewhere about how membership is stored and also if it is a direct membership or if you are a member of a group that is a member of another group. One group that we use as our default group is Domain users but no one has that in there memberOf array even though that group's membership is direct as in the members of that group are all users not other security groups containing the users.
At some point in this program I need to mark certain users as "managers" and the easiest way for me to do so would be to store a flag VIA session variable if they are a member of a certain manager group, as stated above the problem I am running into is users are not appearing in some of their groups so this isn't working, the group that would give access to managers is not appearing in my MemberOf area. During the final stage I will have to go through 5-6 groups and add all the members to the database, it is a similar problem and should have a similar solution so maybe I can kill two birds with 1 stone if I figure that one out too. What I mean by this problem is that I will need to grab a group such as something like 'users HR' and then upload them all to the database by givenname and surname and some default values for other fields but I don't know how to grab users from a group, I know how to grab groups of a user but even that doesn't grab 100% of the groups and if I can reverse that order and act as the group and check my own members that would make things real easy, our current application that we are using to do all this for us is in ASP.net but 10 years old or so and has an administrator account hard coded in to access groups and so on, even doing that I still am not sure how I would get members of a group.
Code:
<?php
$ldap = ldap_connect("192.168.1.**");
$ldap_dn = "DC=************,DC=local";
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option( $ldap, LDAP_OPT_PROTOCOL_VERSION, 3 );
$access = NULL;
if ($bind = ldap_bind($ldap, "***********\\" . $_POST['username'], $_POST['password'])) {
$filter = "(sAMAccountName=" . $_POST['username'] . ")";
$attr = array("memberof","givenname","sn","mail");
$result = ldap_search($ldap, $ldap_dn, $filter, $attr) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($ldap, $result);
$givenname = $entries[0]['givenname'][0] . " " . $entries[0]['sn'][0];
ldap_unbind($ldap);
//var_dump($entries[0]["sn"][0]);
//var_dump($givenname);
//var_dump($entries[0]);
// check groups
foreach($entries[0]['memberof'] as $grps) {
// is manager, break loop
//if (strpos($grps, $ldap_manager_group)) { $access = 2; break; }
// is user
//var_dump($grps);
if (strpos($grps, "****** * *** *****")) $access = "****** *";
if (strpos($grps, "*** Group")) $access = "***";
if (strpos($grps, "*** Group")) $access = "***";
if (strpos($grps, "***")) $access = "***";
if (strpos($grps, "*** Group")) $access = "***";
if (strpos($grps, "***")) $access = "***";
}
if ($access != NULL) {
// establish session variables
$_SESSION['user'] = $_POST['username'];
$_SESSION['access'] = $access;
$_SESSION['givenname'] = $givenname;
$_SESSION['email'] = $entries[0]['mail'][0];
return true;
} else {
//echo "No rights?";
// user has no rights
return false;
}
} else {
//header("Location: login.php?Error=Invalid Identity");
echo "Elese Here";
}
?>
Edit:
I have been trying to use this tutorial: samjlevy.com and I understand it for the most part but I am getting a few errors:
Warning: ldap_search(): Search: Operations error in C:\inetpub\wwwroot\InOutBoard\test.php on line 62
Warning: ldap_get_entries() expects parameter 2 to be resource, boolean given in C:\inetpub\wwwroot\InOutBoard\test.php on line 63
Warning: array_shift() expects parameter 1 to be array, null given in C:\inetpub\wwwroot\InOutBoard\test.php on line 66
Warning: Invalid argument supplied for foreach() in C:\inetpub\wwwroot\InOutBoard\test.php on line 72
Array ( )
They all seem to be with the search because it isn't working it's return a NULL set to result which isn't going to allow other parts to run. I am not sure if my $ldap_dn is correct as I am using the same one from the php code above. My layout is as follows (I am new to this I believe this is correct): DC=company,DC=local and so it should be for the group I want: CN=Group Looking For,OU=lowestLevel Ou,OU=Groups,OU=company,DC=Company,DC=local
Would I have to use that as my $ldap_dn?
EDIT 2: (Updated Code)
This code is displaying all the groups that a user is in and works very well, is there a way to write a second page that uses a similar page to take one of those groups and grabs all the members out of it?
<?php
$ldap = ldap_connect("192.168.1.**");
$ldap_dn = "DC=Company,DC=local";
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option( $ldap, LDAP_OPT_PROTOCOL_VERSION, 3 );
$access = NULL;
if ($bind = ldap_bind($ldap, "**********\\" . $_POST['username'], $_POST['password'])) {
$filter = "(sAMAccountName=" . $_POST['username'] . ")";
$attr = array("memberof","givenname","sn","mail","distinguishedname");
$result = ldap_search($ldap, $ldap_dn, $filter, $attr) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($ldap, $result);
$givenname = $entries[0]['givenname'][0] . " " . $entries[0]['sn'][0];
//ldap_unbind($ldap);
//var_dump($entries[0]["sn"][0]);
//var_dump($givenname);
//var_dump($entries[0]);
var_dump($entries[0]['distinguishedname'][0]);
$gFilter = "(&(objectClass=group)(member:1.2.840.113556.1.4.1941:=".$entries[0]['distinguishedname'][0]."))";
$gAttr = array("cn");
$result1 = ldap_search($ldap, $ldap_dn, $gFilter, $gAttr) or exit("Unable to search LDAP server");
$groups = ldap_get_entries($ldap, $result1);
var_dump($groups);
// check groups
foreach($entries[0]['memberof'] as $grps) {
// is manager, break loop
//if (strpos($grps, $ldap_manager_group)) { $access = 2; break; }
// is user
//var_dump($grps);
if (strpos($grps, "****** * *** *****")) $access = "****** *";
if (strpos($grps, "*** Group")) $access = "***";
if (strpos($grps, "*** Group")) $access = "***";
if (strpos($grps, "***")) $access = "***";
if (strpos($grps, "*** Group")) $access = "***";
if (strpos($grps, "***")) $access = "***";
}
if ($access != NULL) {
// establish session variables
$_SESSION['user'] = $_POST['username'];
$_SESSION['access'] = $access;
$_SESSION['givenname'] = $givenname;
$_SESSION['email'] = $entries[0]['mail'][0];
return true;
} else {
//echo "No rights?";
// user has no rights
return false;
}
} else {
//header("Location: login.php?Error=Invalid Identity");
echo "Elese Here";
}
?>
Second Page: This page is supposed to find members of a group which looks like it may be trying to do so but not picking out members of groups but one of our OU's instead. Look below to code for a layout and what it's grabbing.
<?php
function get_members($group=FALSE,$inclusive=FALSE) {
$ldap_host = "192.168.1.***";
$ldap_dn = "OU=******,OU=*****,OU=**********,DC=Company,DC=local";
$ldap_usr_dom = "#".$ldap_host;
$user = "*******";
$password = "******";
$keep = array(
"samaccountname",
"distinguishedname"
);
$ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP");
ldap_bind($ldap, "REGION5SYSTEMS\\" . $user, $password) or die("Could not bind to LDAP");ry
if($group) $query = "(&"; else $query = "";
$query .= "(&(objectClass=user)(objectCategory=person))";
if(is_array($group)) {
// Looking for a members amongst multiple groups
if($inclusive) {
$query .= "(|";
} else {
$query .= "(&";
}
foreach($group as $g) $query .= "(memberOf=CN=$g,$ldap_dn)";
$query .= ")";
} elseif($group) {
$query .= "(memberOf=CN=$group,$ldap_dn)";
}
if($group) $query .= ")"; else $query .= "";
$results = ldap_search($ldap,$ldap_dn,$query);
$entries = ldap_get_entries($ldap, $results);
array_shift($entries);
$output = array(); // Declare the output array
$i = 0; // Counter
// Build output array
foreach($entries as $u) {
foreach($keep as $x) {
// Check for attribute
if(isset($u[$x][0])) $attrval = $u[$x][0]; else $attrval = NULL;
$output[$i][$x] = $attrval;
}
$i++;
}
return $output;
}
// Example Output
print_r(get_members()); // Gets all users in 'Users'
print_r(get_members("Group I'm search for")); // Gets all members of 'Test Group'
?>
So our DC is DC=CompanyName,DC=Local and we then have folders and OU's and One of the OU's is named 'CompanyName' and nested in it are OU's such as Admins Computers, Contacts, Groups, ect ect... The OU I am looking at is Users and nested within that are different organizations in our building (They use our domian) and one extra OU that is made for this project. Background on the project is a employee inoutBoard and so we have 3 Security groups in that OU, one for other organization's members, one for our organizations members and one for those who are managers from both our Org and their org, basically people who can change status's of others if they forget to do so. What we would ideally want to do is have some sort of sync button which could go check members of those groups and then upload them to the database as well as some default values such as default status of out of office and no description or anything like that. Those groups do not contain people either, they contain other security groups. That's what we want to work, we want to be able to find the members of those groups, the second bit a code I attached will work sometimes, if I set $ldap_dn to "CN=Company,DC=Company,DC=Local" it will print all users in the Users OU and then go into all the OU's there and print the users from those OU's except the OU that we actually need which is that OU that has the groups for the in out board. If I specify that path as the $ldap_dn it just prints array() and nothing else. Any Idea?
The memberOf attribute will only contain direct group memberships, so recursive memberships will not be listed. However, you could specifically query for the recursive group memberships of a user like so (to adapt your code a bit directly after the bind):
$filter = "(sAMAccountName=" . $_POST['username'] . ")";
$attr = array("givenname","sn","mail", "distinguishedname");
$result = ldap_search($ldap, $ldap_dn, $filter, $attr) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($ldap, $result);
$gFilter = "(&(objectClass=group)(member:1.2.840.113556.1.4.1941:=".$entries[0]['distinguishedname'][0]."))";
$gAttr = array("cn");
$result = ldap_search($ldap, $ldap_dn, $gFilter, $gAttr) or exit("Unable to search LDAP server");
$groups = ldap_get_entries($ldap, $result);
Not tested at the moment, but that is the general filter and process for doing it. Get the DN of the user then use the matching rule OID 1.2.840.113556.1.4.1941 to get groups recursively.
The reason you are not getting the "Domain Users" group to show up is because that is a "special" primary group in AD, stored within the primaryGroupId attribute of a user. Additional info on that here:
https://support.microsoft.com/en-us/kb/297951

displaying server error messages on UI in php

I am very new to php programming. I have written a sign up html file where the user enters his email and password. If the user has already registered, I am redirecting to sign-in screen and if the user is new use, I am persisting in the database. Now if the user enters wrong password, he will again be redirected to sign-in screen but this time I want to show a message on the screen, that the password entered is incorrect. The sign in screen should not display the message when the user navigates directly to the sign in screen.
The code snippet is shown below:
<?php
define('DB_HOST', 'hostname');
define('DB_NAME', 'db_name');
define('DB_USER','username');
define('DB_PASSWORD','password');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser() {
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO WebsiteUsers (email,pass) VALUES ('$email','$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data) {
header('Location: reg-success.html');
}
}
function SignUp() {
if(!empty($_POST['email'])){
$emailQuery = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]'");
if($row = mysql_fetch_array($emailQuery)) {
$query = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]' AND pass = '$_POST[password]'");
if($row = mysql_fetch_array($query)) {
echo 'validated user. screen that is accessible to a registered user';
}else{
echo 'Redirect to the sign in screen with error message';
}
}else{
NewUser();
}
}
}
if(isset($_POST['submit']))
{
SignUp();
}
?>
Please let me know how to get this implementation using php
Here are a couple of classes that may help you prevent injection hacks plus get you going on how to do what you are trying to do in general. If you create classes for your tasks, it will be easier to re-use what your code elsewhere. I personally like the PDO method to connect and grab info from a DB (you will want to look up "binding" to help further prevent injection attacks), but this will help get the basics down. This is all very rough and you would want to expand out to create some error reporting and more usable features.
<?php
error_reporting(E_ALL);
// Create a simple DB engine
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
$rows = $query->fetchAll();
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
// Your user controller class
class UserControl
{
public $_error;
protected $db;
// Save the database connection object for use in this class
public function __construct($db)
{
$this->_error = array();
$this->db = $db;
}
// Add user to DB
protected function Add()
{
$email = htmlentities($_POST['email'],ENT_QUOTES);
// Provided you have a php version that supports better encryption methods, use that
// but you should do at least a very basic password encryption.
$password = hash('sha512',$_POST['password']);
// Use our handy DBEngine writer method to write your sql
$this->db->Write("INSERT INTO WebsiteUsers (`email`,`pass`) VALUES ('$email','$password')");
}
// Fetch user from DB
protected function Fetch($_email = '')
{
$_email = htmlentities($_email,ENT_QUOTES);
$password = hash('sha512',$_POST['password']);
// Use our handy DBEngine fetcher method to check your db
$_user = $this->db->Fetch("SELECT * FROM WebsiteUsers WHERE email = '$_email' and password = '$password'");
// Return true if not 0
return ($_user !== 0)? 1:0;
}
// Simple fetch user or set user method
public function execute()
{
// Check that email is a valid format
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// Save the true/false to error reporting
$this->_error['user']['in_db'] = $this->Fetch($_POST['email']);
// Asign short variable
$_check = $this->_error['user']['in_db'];
if($_check !== 1) {
// Add user if not in system
$this->Add();
// You'll want to expand your add feature to include error reporting
// This is just returning that it made it to this point
$this->_error['user']['add_db'] = 1;
}
else {
// Run some sort of login script
}
// Good email address
$this->_error['email']['validate'] = 1;
}
else
// Bad email address
$this->_error['email']['validate'] = 0;
}
}
// $_POST['submit'] = true;
// $_POST['email'] = 'jenkybad<script>email';
// $_POST['password'] = 'mypassword';
if(isset($_POST['submit'])) {
// Set up a db connection
$db = new DBEngine('hostname','dbname','dbuser','dbpass');
// Create instance of your user control
$_user = new UserControl($db);
// Execute instance
$_user->execute();
// Check for basic erroring
print_r($_user->_error);
} ?>

Verifying user is part of ldap/active directory security group

Ok... I've dug through the examples and etc on here and I'm still having issues.
<?php
// SHOW ERRORS 0=NO 1=YES
ini_set('display_errors', '1');
//USER
$valid_session_username = $_POST["username"];
$valid_session_password = $_POST["password"];
//MEMBER OF THIS GROUP
$dn = "DC=FLRC,DC=local";
$group = "CN=Internet-Purchasing-Allowed,OU=Security Groups,DC=FLRC,DC=LOCAL";
$filter = "(&(objectClass=user)(memberOf=$group))";
$ad = ldap_connect("srv-flc-dc03") or die("Couldn't connect to AD!");
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($ad, LDAP_OPT_REFERRALS,0);
$bd = ldap_bind( $ad, $valid_session_username."#flrc.local", $valid_session_password) or die("Can't bind to server.");
$sr = ldap_search($ad, $dn, $filter);
$found = false;
if ($sr !== false) {
$count = ldap_count_entries ($ad, $sr);
if ($count !== false && $count > 0) {
$found = true;
}
}
if ($found === true) {
print $valid_session_username.' does have access to this page';
} else {
print $valid_session_username.' does NOT have access to this page';
}
?>
I have no idea what I'm missing. When I submit my credentials it says "SRAY does have access to this page". Which is what it is suppose to say since SRAY is part of that group. It also says this for another username/pass that is NOT part of that security group.
Your filter is looking for any user that is a direct member of the Internet-Purchasing-Allowed group. You need to add (sAMAccountName=$valid_session_username) to your filter.
You must define sAMAccountname in your filter
//MEMBER OF THIS GROUP
$dn = "DC=FLRC,DC=local";
$group = "CN=Internet-Purchasing-Allowed,OU=Security Groups,DC=FLRC,DC=LOCAL";
$filter = "(&(objectClass=user)(sAMAccountname=".$valid_session_username.")(memberOf=".$group."))";
You must bind the LDAP with an account that has the necessary rights. Create an administrator account that has read permissions on all the "OU=Security Groups". Then bind with it in your code.
$bd = ldap_bind( $ad, $admin_session_username."#flrc.local", $admin_session_password) or die("Can't bind to server.");

Joomla 2.5 authentication Plugin Fatal error: Call to a member function get() on a non-object

I wrote a simple authentication plugin that uses a SOAP webservice to check the username and the password. That works fine.
I wanted to have some parameter like the SOAP password in the admin of joomla. So I have added the params in the xml, it shows fine in the admin. When I try to get the value of it the php, I get:
Fatal error: Call to a member function get() on a non-object
So I compared with other authentication and I do it exactly the same way.... I do not understand why it is so.
Here is the code of the Plugin:
public function __construct() {
$nusoap = JPATH_SITE . '/plugins/authentication/ers/nusoap/lib/nusoap.php';
if (! file_exists ( $nusoap )){
$response->error_message = "No such file";
return;
}
require_once ($nusoap);
}
function onUserAuthenticate($credentials, $options, &$response)
{
//Without defaults (the plugin crashes on the first get() bellow)
$webservice = $this->params->get('webservice', '');
$group = $this->params->get('group', '');
$whitepaw = $this->params->get('whitepaw', '');
JRequest::checkToken() or die( 'Invalid Token' );
// For JLog
$response->type = 'ERS SOAP Webservice';
// MyCompany does not like blank passwords (So does Joomla ;))
if (empty($credentials['password'])) {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED');
return false;
}
if (empty($credentials['username'])) {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('Please enter a username');
return false;
}
// Add a user to joomla
function addJoomlaUser($name, $username, $password, $email, $group) {
$data = array(
"name"=>$name,
"username"=>$username,
"password"=>$password,
"password2"=>$password,
"email"=>$email,
"block"=>0,
"groups"=>array("1","2", $group) // the uer is added into the group "public" and "registered" as well as a group of the user's choice.
);
$user = clone(JFactory::getUser());
//Write to database
if(!$user->bind($data)) {
throw new Exception("Could not bind data. Error: " . $user->getError());
}
if (!$user->save()) {
throw new Exception("Could not save user. Error: " . $user->getError());
}
return $user->id;
}
// Pour supprimer le cache du web-service
ini_set('soap.wsdl_cache_enabled', 0);
// Nouveau Client SOAP
try {
// Nouvelle instance de la classe soapClient
$client = new SoapClient($webservice, array('trace' => true));
$username = $credentials['username'];
$password = $credentials['password'];
$result = $client->CheckLogin(array('whitepaw'=>$whitepaw, 'username'=>$username, 'password'=>$password));
if($result->isInDB){
$name = $result->fname.' '.$result->lname;
$email = $result->email;
$response->error_message = $username.'<br>'.$password.'<br>'.$name.'<br>'.$email."<br><br>".
"<b>Request :</b><br>".htmlentities($client->__getLastRequest())."<br><br>".
"<b>RESPONSE :</b><br>".htmlentities($client->__getLastResponse())."<br><br>";
if(!$result->email == '' || empty ($result)) {
//Todo: check if the user is already in joomla db
$user_id = addJoomlaUser($name, $username, $password, $email,$group);
$response->status = JAuthentication::STATUS_SUCCESS;
//for testing purposes
$response->error_message = $user_id;
} else {
$response->error_message = "The webservice did not return data".$email.'did you see it?';
}
} else {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = 'You do not have yet an account in myers. Please register.<br>';
$response->error_message .= $result->isInDB;
}
} catch (Exception $fault) {
$response->error_message = $fault->getMessage();
}
}
}
Since you have your own constructor, you need to call the parent constructor like this:
public function __construct(& $subject, $params = array()) {
$nusoap = JPATH_SITE . '/plugins/authentication/ers/nusoap/lib/nusoap.php';
if (! file_exists ( $nusoap )){
$response->error_message = "No such file";
return;
}
require_once ($nusoap);
// call the parent constructor
parent::__construct($subject, $params);
}
The parent constructor is where the $this->params object gets set, so if you don't call it then $this->params is never set. That's why you get the error saying params is not an object.

Categories