Advertisement
Guest User

Untitled

a guest
Oct 12th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. function mymodule_form_alter(&$form, $form_state, $form_id) {
  2. if ($form_id == 'user_login_block' || $form_id == 'user_login') {
  3. $form['#validate'] = array('user_login_name_validate', 'mymodule_login_validate', 'user_login_final_validate');
  4. }
  5. }
  6.  
  7. function mymodule_login_validate($form, &$form_state) {
  8. global $user;
  9. $username = $form_state['values']['name'];
  10. $password = $form_state['values']['pass'];
  11.  
  12. $ch = curl_init();
  13. curl_setopt($ch,CURLOPT_URL, "http://localhost/MYAPI/oauth/authenticate");
  14. curl_setopt($ch, CURLOPT_POST, 1);
  15. curl_setopt($ch, CURLOPT_POSTFIELDS,"username=" . $username . "&grant_type=password");
  16. curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Authorization:Basic xxxxxxxxxxxxxxx"));
  17.  
  18. // receive server response ...
  19. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  20. $server_output = curl_exec ($ch);
  21. curl_close ($ch);
  22. $postData = drupal_json_decode($server_output);
  23. $count = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name;", array(':name' =>$username))->fetchField();
  24.  
  25. if ($count == 0) {
  26. if (!empty($postData['access_token'])) {
  27. $ch = curl_init();
  28. curl_setopt($ch, CURLOPT_URL,"http://localhost/MYAPI/rest/user/1/get_user_details");
  29. curl_setopt($ch, CURLOPT_POST, 1);
  30. curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Authorization:Bearer ".$postData['access_token']));
  31.  
  32. // receive server response ...
  33. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  34. $server_output = curl_exec($ch);
  35. curl_close($ch);
  36. $postData = drupal_json_decode($server_output);
  37. $resRoleArr = $postData['userDetail']['role'];
  38. $resMail = $postData['userDetail']['email'];
  39. $roleArr = user_roles();
  40. $common_roles = array_intersect($resRoleArr,$roleArr);
  41.  
  42. if (count($common_roles) > 0) {
  43. user_external_login_register($username, 'mymodule');
  44. $user_fields = [
  45. 'pass' => $password,
  46. 'status' => 1,
  47. 'mail' => $resMail,
  48. 'init' => $resMail,
  49. 'roles' => [DRUPAL_AUTHENTICATED_RID => 'authenticated user'],
  50. ];
  51.  
  52. user_save((object) ['uid' => $user->uid], (array) $user_fields);
  53. $account = user_external_load($username);
  54. $form_state['uid'] = $account->uid;
  55. if ($role = user_role_load_by_name($common_roles)) {
  56. user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);
  57. }
  58. }
  59. }
  60. }
  61. else {
  62. user_login_authenticate_validate($form,$form_state);
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement