Moodle API create user, generate password and email user - php

I am trying to create a new user in Moodle via the Web service API (version 2.7.1+ (Build: 20140829). I want to auto-generate the password and notify the user via email about his new account.
When I create a user via GUI there is a checkbox for doing exactly that: generating password and notifying user via email.
However, when I create a user via the API I do not know how to force password generation and the email notification. Unfortunately I cannot find anything in the Moodle API about how to automatically send email after user creation.
private function createUser($firstName, $lastName, $email){
$newUser = new stdClass();
$newUser->username = strtolower($email);
$newUser->password = getInitialPassword();
$newUser->firstname = $firstName ?: getRandomUsername();
$newUser->lastname = $lastName ?: '.';
$newUser->email = $email;
$newUser->preferences = array(array('type' =>'auth_forcepasswordchange', 'value' => true));
$users = array($newUser);
$params = array('users' => $users);
return post(buildServerUrl($create_user_command), $params);
}
Does anyone know how to do that?

it seems to be the same question asked at https://moodle.org/mod/forum/discuss.php?d=323422 , so here is the same answer:
"this improvement was introduced in 3.0, you may be interested in MDL-51182, it seems simple to backport."
Kind regards,
Daniel

Related

Create a contact in Xero and get its contact Id using php api (oauth2)

Just learning Xero API (php) but I'm unsure how to proceed. The docs are pretty good in general. I've successfully created the oauth2 integration and this connects no problem (even for multiple organisations/tenants), I'm able to get the existing contacts in Xero but I now need to create a new contact (I have the name of this conteact - call her Jane Doe) i then wish to update my database record with this new Contacts contactId.
So the docs are a bit confusing but looking at the php api i think i can use:
$response = $accountingApi->setContacts( $xeroTenantId, '{"Name": "Jane Doe"}' );
would this be the right kind of approach (where $accountingApi is defined in a call earlier in the cycle and is connected)? does anyone have an example on how to add a new contact to Xero and return this new contacts contactId?
The docs don't say what (if any) response is returned after adding a new contact.
Lastly somewhat related to this, Some of my contacts are in more than one linked organisations, would these have the same clientID or will i need to somehow define one for each connected organisation?
thanks in advance
ADDITONAL
the api docs on github have this snippet:
try {
$person = new XeroAPI\XeroPHP\Models\Accounting\ContactPerson;
$person->setFirstName("John")
->setLastName("Smith")
->setEmailAddress("john.smith#24locks.com")
->setIncludeInEmails(true);
$arr_persons = [];
array_push($arr_persons, $person);
$contact = new XeroAPI\XeroPHP\Models\Accounting\Contact;
$contact->setName('FooBar')
->setFirstName("Foo")
->setLastName("Bar")
->setEmailAddress("ben.bowden#24locks.com")
->setContactPersons($arr_persons);
$arr_contacts = [];
array_push($arr_contacts, $contact);
$contacts = new XeroAPI\XeroPHP\Models\Accounting\Contacts;
$contacts->setContacts($arr_contacts);
$apiResponse = $accountingApi->createContacts($xeroTenantId,$contacts);
$message = 'New Contact Name: ' . $apiResponse->getContacts()[0]->getName();
} catch (\XeroAPI\XeroPHP\ApiException $e) {
$error = AccountingObjectSerializer::deserialize(
$e->getResponseBody(),
'\XeroAPI\XeroPHP\Models\Accounting\Error',
[]
);
$message = "ApiException - " . $error->getElements()[0]["validation_errors"][0]["message"];
}
I require only the name on Xero (all other details are in my linked App) and to obtain the contactId.
Ok so having reviewed the docs I am going with:
$contact = new XeroAPI\XeroPHP\Models\Accounting\Contact;
$contact->setName('Jane Doe');
$arr_contacts = [];
array_push($arr_contacts, $contact);
$contacts = new XeroAPI\XeroPHP\Models\Accounting\Contacts;
$contacts->setContacts($arr_contacts);
$apiResponse = $accountingApi->createContacts($xeroTenantId,$contacts);
//$message = 'New Contact Name: ' . $apiResponse->getContacts()[0]->getName();
$contactId = $apiResponse->getContacts()[0]->getContactId();

Override the login Controller in FOSUserBundle (Symfony2)

I'm currently migrating from a WordPress to a Symfony2 website.
I imported all my WP user on Symfony2 but now I'm looking for a way to make additional checks when the user tries to log in (typically check if the user was imported from WP and check his old password).
What's the best way to add some checks on the User authentication ? (login_check on fosuserbundle).
I simply try to override the SecurityController, but it doesn't work as the login doesn't seem to be made here.
Thanks for your help.
Edit: I need to add my check during the login process, not after. During the login, if the user comes from WordPress, I want to check if the password he provides is the same as his old WordPress password (that is stored in the DB too).
I finaly found a solution, but not sure it's the best way to do the stuff.
I added a listener when the login failed and check if it's a user from WordPress.
Now I'm looking for a solution to handle the "remember me" checkbox because the user is a authenticate programmatically. Here is the code :
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$username = $request->request->get('_username');
$password = $request->request->get('_password');
$user = $this->doctrine->getRepository('AppBundle:User')->findOneByUsername($username);
if ($user instanceof User && $user->getFromWordpress() == true) {
//The class use by WordPress to check / encode passwords
$hasher = new PasswordHash(8, TRUE);
//User provide the right password
if ($hasher->CheckPassword($password, $user->getWordpressPassword())){
//Programmatically authenticate the user
$token = new UsernamePasswordToken($user, $user->getPassword(), "main", $user->getRoles());
$this->tokenStorage->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->eventDispacher->dispatch("security.interactive_login", $event);
//Set the password with the Symfony2 encoder
$encoder = $this->encoderFactory->getEncoder($user);
$password = $encoder->encodePassword($password, $user->getSalt());
$user->setPassword($password);
$user->setFromWordpress(false);
$this->doctrine->getManager()->persist($user);
$this->doctrine->getManager()->flush();
//Finnaly send login ok response
return $this->onAuthenticationSuccess($request, $token);
}
}
//Login failed code ...
//.....
}

How do I integrate OAuth client authentication alongside Laravel standard authentication?

I've been Googling for quite some time now for some ideas or a guide on how to integrate OAuth (v1.0 & v2.0) alongside the standard Laravel 4 Eloquent authentication driver.
Essentially, I'd like to be able for site visitors to create an account via their existing Google, Facebook, or Twitter accounts, or via the standard email/password authentication. Certain user information such as email, first and last names, and avatar are important for me to have stored in a unified users table.
So far the projects I've looked at seem to support only OAuth and do away with the standard method. These projects include: eloquent-oauth, and oauth-4-laravel.
At this point, I might just roll my own solution, but I'm hoping some of you guys might have better advice for me!
TL;DR: I'm stuck at trying to find a simple and secure way to allow OAuth and standard Eloquent user authentication in Laravel. Halp.
I think the easiest way would be to use this service provider that you mention "artdarek/oauth-4-laravel" and then store the values as usual and log them in.
/**
* Login user with facebook
*
* #return void
*/
public function loginWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
// store new user or login if user exists
$validator = Validator::make($result, array(
'email'=>'required|email|unique:users'
));
if ($validator->passes()) {
# Save user in DB
$user = new User;
$user->username = $result['name'];
$user->email = $result['email'];
$user->save();
}else {
$user = User::findByUsernameOrFail($result['name']);
}
Auth::login($user);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}

Google API BadAuthentication error with Zend gdata

I am using gdata to add contacts to my gmail account using the Contact API. When I run the code on my development box as localhost, everything works fine. But when I move the code to a production server (www.somedomain.com) I get "ERROR:Authentication with Google failed. Reason: BadAuthentication".
Here's my code:
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_Feed');
// set credentials for ClientLogin authentication
$user = "something#gmail.com";
$pass = "somepassword";
try {
// perform login and set protocol version to 3.0
$client = Zend_Gdata_ClientLogin::getHttpClient(
$user, $pass, 'cp');
$gdata = new Zend_Gdata($client);
$gdata->setMajorProtocolVersion(3);
// create new entry
$doc = new DOMDocument();
$doc->formatOutput = true;
$entry = $doc->createElement('atom:entry');
$entry->setAttributeNS('http://www.w3.org/2000/xmlns/' ,
'xmlns:atom', 'http://www.w3.org/2005/Atom');
$entry->setAttributeNS('http://www.w3.org/2000/xmlns/' ,
'xmlns:gd', 'http://schemas.google.com/g/2005');
$entry->setAttribute('xmlns', 'http://www.w3.org/2005/Atom');
$entry->setAttribute('xmlns:gd', 'http://schemas.google.com/g/2005');
$entry->setAttribute('xmlns:gContact', 'http://schemas.google.com/contact/2008');
$doc->appendChild($entry);
// add name element
$name = $doc->createElement('gd:name');
$entry->appendChild($name);
$fullName = $doc->createElement('gd:fullName', 'Jack Frost');
$name->appendChild($fullName);
// add email element
$email = $doc->createElement('gd:email');
$email->setAttribute('address' ,'jack.frost#example.com');
$email->setAttribute('rel' ,'http://schemas.google.com/g/2005#home');
$entry->appendChild($email);
// add org name element
$org = $doc->createElement('gd:organization');
$org->setAttribute('rel' ,'http://schemas.google.com/g/2005#work');
$entry->appendChild($org);
$orgName = $doc->createElement('gd:orgName', 'Winter Inc.');
$org->appendChild($orgName);
//add to Friends list
$group = $doc->createElement('gContact:groupMembershipInfo');
$group->setAttribute('deleted' ,'false');
$group->setAttribute('href' ,'http://www.google.com/m8/feeds/groups/' .urlencode($user) . '/base/[groupid]');
//addd to my contacts
$entry->appendChild($group);
$group = $doc->createElement('gContact:groupMembershipInfo');
$group->setAttribute('deleted' ,'false');
$group->setAttribute('href' ,'http://www.google.com/m8/feeds/groups/' .urlencode($user) . '/base/6'); //adds to Friends
$entry->appendChild($group);
// insert entry
$entryResult = $gdata->insertEntry($doc->saveXML(),
'http://www.google.com/m8/feeds/contacts/default/full');
echo '<h2>Add Contact</h2>';
echo 'The ID of the new entry is: ' . $entryResult->id;
echo 'The link is: ".$entryResult->getLink('edit')."";
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
?>
Should I be using OAuth for Services instead? I haven't been able to find documentation on how to do this with Zend Gdata.
EDIT - ANSWER FOUND:
Ok - I still have a question about a better auth method but I figured out what the issue was in this case. Google was suspicious of my application logging in. When I checked gmail, I had received the following:
Hi Info,
Someone recently used your password to try to sign in to your Google Account [someone]#gmail.com. This person was using an application such as an email client or mobile device.
We prevented the sign-in attempt in case this was a hijacker trying to access your account. Please review the details of the sign-in attempt:
Saturday, November 2, 2013 9:43:52 PM UTC
IP Address: [xxx.xxx.xx.xxx] ([xxx.xxx.xx.xxx].unifiedlayer.com.)
Location: Unknown
If you do not recognize this sign-in attempt, someone else might be trying to access your account. You should sign in to your account and reset your password immediately.
Reset password
If this was you, and you are having trouble accessing your account, complete the troubleshooting steps listed at http://support.google.com/mail?p=client_login
Sincerely,
The Google Accounts team
I went into gmail security (through the link provided) and was able to authorize the app. Problem solved. Works perfectly now.
I'd still like some pointers on how to use my Client ID, Service Account and Private Key with Zend (if possible). I have connected using the Google API php library but I can't see how to use this within the Zend framework.
On my side, I solved the problem by entering my full email address as username (username#gmail.com).
Previously, I tried to access to my account only with the username...

zend_gdata: Get google calendar if already logged in an application

I have created one application in YiiFramework which has two functionalities.
1. Login to google
For login to google, I have followed the tutorial on below website.
Tutorial : https://github.com/Nodge/yii-eauth
Tutorial Demo : http://nodge.ru/yii-eauth/demo/login
2 Get calendar using Zend_Gdata Library
Tutorial : http://www.bcits.co.in/googlecalendar/index.php/site/install
Tutorial Demo : http://www.bcits.co.in/googlecalendar/index.php/site/page?view=about
[1st Step] I get successfully login to my application using yii-eauth.
[2nd Step] when I need to use calendar, I am giving hard coded gmail Id and password.
I am accessing calendar in this way.
<?php
$user = 'your gmail username';
$pass ='your gmail password';
Yii::app()->CALENDAR->login($user, $pass);
?>
login() in googlecalendar.php file.
public function login($user, $pass) {
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);// It uses hard-coded gmail/password to get login again
$calenderlist = $this->outputCalendarList($client);
$events = $this->outputCalendar($client);
$calendardate = $this->outputCalendarByDateRange($client, $startDate = '2011-05-01', $endDate = '2011-06-01');
.........
}
Does Zend_Gdata library contain any function which automatically gets calendar of current user without again logging in(hard-coded here).
Stuck with this. Appreciate helps. Thanks
From my understanding, Zend_Gdata_ClientLogin sets some parameters for $client which is the object returned. See the following excerpt from that function:
if ($loginToken || $loginCaptcha) {
if ($loginToken && $loginCaptcha) {
$client->setParameterPost('logintoken', (string) $loginToken);
$client->setParameterPost('logincaptcha', (string) $loginCaptcha);
} else {
require_once 'Zend/Gdata/App/AuthException.php';
throw new Zend_Gdata_App_AuthException(
'Please provide both a token ID and a user\'s response ' .
'to the CAPTCHA challenge.');
}
}
What you could do is store that token or that $client object (which is an instance of Zend_Gdata_HttpClient). Pretty much all of the Zend_Gdata components accept a $client argument.
Check out the __construct() method for Zend_Gdata_Calendar:
So anyway, you would want something similar to this logic (sorry I'm not familiar with Yii):
$client = Yii::app()->getClient();
if (!$client) {
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
Yii::app()->setClient($client);
}
Of course, you would have to then define that getClient() method somehow.
Hope this helps!

Categories