PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/1.4.x/opauthmodule/callback.php

https://github.com/johnulist/PrestaShop-Opauth
PHP | 459 lines | 349 code | 76 blank | 34 comment | 50 complexity | bb0dbedd7dcf1f839b85a8f45d316290 MD5 | raw file
  1. <?php
  2. $opauth = new opauthmodule();
  3. define('CONF_FILE', dirname(__file__) . '/' . 'opauth.conf.php');
  4. define('OPAUTH_LIB_DIR', dirname(__file__) . '/lib/Opauth/');
  5. /**
  6. * Load config
  7. */
  8. if (!file_exists(CONF_FILE)) {
  9. trigger_error('Config file missing at ' . CONF_FILE, E_USER_ERROR);
  10. exit();
  11. }
  12. require CONF_FILE;
  13. /**
  14. * Instantiate Opauth with the loaded config but not run automatically
  15. */
  16. require OPAUTH_LIB_DIR . 'Opauth.php';
  17. $Opauth = new Opauth($config_op, false);
  18. /**
  19. * Fetch auth response, based on transport configuration for callback
  20. */
  21. if (isset($_POST['email_opthmodule'])) {
  22. $id_default_group = 1;
  23. // generate passwd
  24. srand((double)microtime() * 1000000);
  25. $passwd = substr(uniqid(rand()), 0, 12);
  26. $real_passwd = $passwd;
  27. $passwd = md5(pSQL(_COOKIE_KEY_ . $passwd));
  28. $last_passwd_gen = date('Y-m-d H:i:s', strtotime('-' . Configuration::get('PS_PASSWD_TIME_FRONT') .
  29. 'minutes'));
  30. $secure_key = md5(uniqid(rand(), true));
  31. $active = 1;
  32. $date_add = date('Y-m-d H:i:s'); //'2011-04-04 18:29:15';
  33. $date_upd = $date_add;
  34. $_data_user_exist = checkExist($_POST['email_opthmodule']);
  35. $_customer_id_exits = (int)$_data_user_exist['customer_id'];
  36. if (!$_customer_id_exits) {
  37. mysql_query("SET NAMES UTF8");
  38. $sql = 'insert into `' . _DB_PREFIX_ . 'customer` SET
  39. id_gender = ' . $_POST["gender"] . ', id_default_group = ' . $id_default_group .
  40. ',
  41. firstname = \'' . utf8_encode(html_entity_decode(($_POST["firstname"]))) .
  42. '\', lastname = \'' . utf8_encode(html_entity_decode(($_POST["lastname"]))) . '\',
  43. email = \'' . $_POST['email_opthmodule'] . '\', passwd = \'' . $passwd .
  44. '\',
  45. last_passwd_gen = \'' . $last_passwd_gen . '\',
  46. secure_key = \'' . $secure_key . '\', active = ' . $active . ',
  47. date_add = \'' . $date_add . '\', date_upd = \'' . $date_upd . '\' ';
  48. $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute($sql);
  49. $insert_id = Db::getInstance()->Insert_ID();
  50. $id_group = 1;
  51. $sql = 'INSERT into `' . _DB_PREFIX_ . 'customer_group` SET
  52. id_customer = ' . $insert_id . ', id_group = ' . $id_group . ' ';
  53. defined('_MYSQL_ENGINE_') ? $result = Db::getInstance()->ExecuteS($sql) : $result =
  54. Db::getInstance()->Execute($sql);
  55. $insert = Db::getInstance()->Execute('
  56. INSERT INTO `' . _DB_PREFIX_ . 'opauth_' . strtolower($_POST['provider']) .
  57. '_customer`
  58. (`' . strtolower($_POST['provider']) . '_id`,`user_id`)
  59. VALUES (' . $_POST["id"] . ',' . $insert_id . ')');
  60. } else {
  61. $insert_id = $_customer_id_exits;
  62. $insert = Db::getInstance()->Execute('
  63. INSERT INTO `' . _DB_PREFIX_ . 'opauth_' . strtolower($_POST['provider']) .
  64. '_customer`
  65. (`' . strtolower($_POST['provider']) . '_id`,`user_id`)
  66. VALUES (' . $_POST["id"] . ',' . $insert_id . ')');
  67. }
  68. ////// Envoie de mail /////
  69. global $cookie;
  70. $err = 2;
  71. $id_lang = $cookie->id_lang;
  72. $actkey = md5($_POST['email_opthmodule']); // La clé d'activation est un md5 de l'adresse mail du client
  73. $actlink = 'modules/opauthmodule/activate.php?id_lang=' . $id_lang . '&actkey=' .
  74. $actkey;
  75. // On rend le compte inactif et on enregistre la clé dans la base de donnée
  76. Db::getInstance()->Execute('UPDATE ' . _DB_PREFIX_ .
  77. 'customer SET active=0, act_key="' . $actkey . '" WHERE id_customer="' . $insert_id .
  78. '"');
  79. // Envoie du mail
  80. if (!Mail::Send((int)$cookie->id_lang, 'opauthmodule', Mail::l('Welcome!', (int)
  81. $cookie->id_lang), array(
  82. '{firstname}' => $_POST["firstname"],
  83. '{lastname}' => $_POST["lastname"],
  84. '{email}' => $_POST['email_opthmodule'],
  85. '{passwd}' => $real_passwd,
  86. '{actlink}' => $actlink), $_POST['email_opthmodule'], $_POST["firstname"] . ' ' .
  87. $_POST["lastname"], null, null, null, null, dirname(__file__) . '/mails/'))
  88. $err = 1; // si le mail n'est pas parti on le signalera au client
  89. $cookie->logout(); // On déconnecte le client puisque son compte n'est pas encore actif
  90. Tools::redirect('modules/opauthmodule/notify.php?id_lang=' . $id_lang . '&err=' .
  91. $err);
  92. /***********/
  93. } else {
  94. $response = null;
  95. switch ($Opauth->env['callback_transport']) {
  96. case 'session':
  97. session_start();
  98. $response = $_SESSION['opauth'];
  99. unset($_SESSION['opauth']);
  100. break;
  101. case 'post':
  102. $response = unserialize(base64_decode($_POST['opauth']));
  103. break;
  104. case 'get':
  105. $response = unserialize(base64_decode($_GET['opauth']));
  106. break;
  107. default:
  108. echo '<strong style="color: red;">Error: </strong>Unsupported callback_transport.' .
  109. "<br>\n";
  110. break;
  111. }
  112. /**
  113. * Check if it's an error callback
  114. */
  115. if (array_key_exists('error', $response)) {
  116. echo '<strong style="color: red;">Authentication error: </strong> Opauth returns error auth response.' .
  117. "<br>\n";
  118. }
  119. /**
  120. * Auth response validation
  121. *
  122. * To validate that the auth response received is unaltered, especially auth response that
  123. * is sent through GET or POST.
  124. */ else {
  125. if (empty($response['auth']) || empty($response['timestamp']) || empty($response['signature']) ||
  126. empty($response['auth']['provider']) || empty($response['auth']['uid'])) {
  127. // echo '<strong style="color: red;">Invalid auth response: </strong>Missing key auth response components.'."<br>\n";
  128. } elseif (!$Opauth->validate(sha1(print_r($response['auth'], true)), $response['timestamp'],
  129. $response['signature'], $reason)) {
  130. // echo '<strong style="color: red;">Invalid auth response: </strong>'.$reason.".<br>\n";
  131. } else {
  132. // echo '<strong style="color: green;">OK: </strong>Auth response is validated.'."<br>\n";
  133. /**
  134. * It's all good. Go ahead with your application-specific authentication logic
  135. */
  136. }
  137. }
  138. $_data = array();
  139. $_data['provider'] = $response['auth']['provider'];
  140. if ($response['auth']['provider'] == 'Twitter') {
  141. $_data['person/gender'] = 'male';
  142. $_data['namePerson/first'] = $response['auth']['info']['name'];
  143. $_data['namePerson/last'] = $response['auth']['info']['nickname'];
  144. $_data['contact/email'] = "nothing"; //$response['auth']['info']['nickname'];
  145. $_data['id'] = $response['auth']['uid'];
  146. } elseif ($response['auth']['provider'] == 'Facebook') {
  147. $_data['person/gender'] = $response['auth']['raw']['gender'];
  148. $_data['namePerson/first'] = $response['auth']['raw']['first_name'];
  149. $_data['namePerson/last'] = $response['auth']['raw']['last_name'];
  150. isset($response['auth']['raw']['email']) ? $_data['contact/email'] = $response['auth']['raw']['email'] :
  151. $_data['contact/email'] = "nothing";
  152. $_data['id'] = $response['auth']['uid'];
  153. } elseif ($response['auth']['provider'] == 'Google') {
  154. $_data['person/gender'] = $response['auth']['raw']['gender'];
  155. $_data['namePerson/first'] = $response['auth']['raw']['given_name'];
  156. $_data['namePerson/last'] = $response['auth']['raw']['family_name'];
  157. $_data['contact/email'] = $response['auth']['raw']['email'];
  158. $_data['id'] = $response['auth']['uid'];
  159. }
  160. }
  161. createUser($_data);
  162. function createUser($_data)
  163. {
  164. $result1 = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('select * FROM ' .
  165. _DB_PREFIX_ . 'opauth_' . strtolower($_data['provider']) . '_customer WHERE ' .
  166. strtolower($_data['provider']) . '_id="' . $_data["id"] . '" ');
  167. if (sizeof($result1)) {
  168. foreach ($result1 as $res) {
  169. global $cookie;
  170. // authentication
  171. $result = Db::getInstance()->GetRow('
  172. SELECT * FROM `' . _DB_PREFIX_ . 'customer`
  173. WHERE `active` = 1 AND `id_customer` = ' . $res["user_id"]);
  174. if ($result) {
  175. $customer = new Customer();
  176. $customer->id = $result['id_customer'];
  177. foreach ($result as $key => $value)
  178. if (key_exists($key, $customer))
  179. $customer->{$key} = $value;
  180. } else {
  181. $result3 = Db::getInstance()->GetRow('
  182. SELECT email FROM `' . _DB_PREFIX_ . 'customer`
  183. WHERE `id_customer` = ' . $res["user_id"]);
  184. Tools::redirect('modules/opauthmodule/resend.php?email=' . $result3['email']);
  185. }
  186. $cookie->id_customer = intval($customer->id);
  187. $cookie->customer_lastname = $customer->lastname;
  188. $cookie->customer_firstname = $customer->firstname;
  189. $cookie->logged = 1;
  190. $cookie->passwd = $customer->passwd;
  191. $cookie->email = $customer->email;
  192. if (Configuration::get('PS_CART_FOLLOWING') and (empty($cookie->id_cart) or Cart::
  193. getNbProducts($cookie->id_cart) == 0))
  194. $cookie->id_cart = intval(Cart::lastNoneOrderedCart(intval($customer->id)));
  195. Module::hookExec('authentication');
  196. Tools::redirect('index.php');
  197. }
  198. } else {
  199. //// create new user ////
  200. $gender = (isset($_data['person/gender']) && $_data['person/gender'] == 'male') ?
  201. 1 : 2;
  202. $id_default_group = 1;
  203. if (isset($_data['namePerson/first']) && isset($_data['namePerson/last'])) {
  204. $firstname = deldigit(pSQL($_data['namePerson/first']));
  205. $lastname = deldigit(pSQL($_data['namePerson/last']));
  206. }
  207. $email = $_data['contact/email'];
  208. // generate passwd
  209. srand((double)microtime() * 1000000);
  210. $passwd = substr(uniqid(rand()), 0, 12);
  211. $real_passwd = $passwd;
  212. $passwd = md5(pSQL(_COOKIE_KEY_ . $passwd));
  213. $last_passwd_gen = date('Y-m-d H:i:s', strtotime('-' . Configuration::get('PS_PASSWD_TIME_FRONT') .
  214. 'minutes'));
  215. $secure_key = md5(uniqid(rand(), true));
  216. $active = 1;
  217. $date_add = date('Y-m-d H:i:s'); //'2011-04-04 18:29:15';
  218. $date_upd = $date_add;
  219. $_data_user_exist = checkExist($email);
  220. $_customer_id_exits = (int)$_data_user_exist['customer_id'];
  221. if ($_customer_id_exits) {
  222. global $cookie;
  223. // authentication
  224. $result = Db::getInstance()->GetRow('
  225. SELECT * FROM `' . _DB_PREFIX_ . 'customer`
  226. WHERE `active` = 1 AND `email` = \'' . pSQL($email) . '\'
  227. AND `deleted` = 0 ' . (defined('_MYSQL_ENGINE_') ?
  228. "AND `is_guest` = 0" : "") . '
  229. ');
  230. if ($result) {
  231. $customer = new Customer();
  232. $customer->id = $result['id_customer'];
  233. foreach ($result as $key => $value)
  234. if (key_exists($key, $customer))
  235. $customer->{$key} = $value;
  236. }
  237. $cookie->id_customer = intval($customer->id);
  238. $cookie->customer_lastname = $customer->lastname;
  239. $cookie->customer_firstname = $customer->firstname;
  240. $cookie->logged = 1;
  241. $cookie->passwd = $customer->passwd;
  242. $cookie->email = $customer->email;
  243. if (Configuration::get('PS_CART_FOLLOWING') and (empty($cookie->id_cart) or Cart::
  244. getNbProducts($cookie->id_cart) == 0))
  245. $cookie->id_cart = intval(Cart::lastNoneOrderedCart(intval($customer->id)));
  246. Module::hookExec('authentication');
  247. Tools::redirect('index.php');
  248. } else {
  249. if ($email == "nothing") {
  250. echo "<script>
  251. $(document).ready(function() {
  252. $('#add_email').fancybox().trigger('click');({
  253. });
  254. });
  255. </script>";
  256. echo '<a href="'.$opauth->url.'/modules/opauthmodule/email.php?gender=' .
  257. $gender . '&firstname=' . $firstname . '&lastname=' . $lastname . '&provider=' .
  258. $_data['provider'] . '&idu=' . $_data["id"] . '" id="add_email"></a>';
  259. }
  260. if ($email != "nothing") {
  261. if (!isset($_POST['email_opthmodule'])) {
  262. $gender = (isset($_data['person/gender']) && $_data['person/gender'] == 'male') ?
  263. 1 : 2;
  264. $id_default_group = 1;
  265. if (isset($_data['namePerson/first']) && isset($_data['namePerson/last'])) {
  266. $firstname = deldigit(pSQL($_data['namePerson/first']));
  267. $lastname = deldigit(pSQL($_data['namePerson/last']));
  268. }
  269. $email = $_data['contact/email'];
  270. // generate passwd
  271. srand((double)microtime() * 1000000);
  272. $passwd = substr(uniqid(rand()), 0, 12);
  273. $real_passwd = $passwd;
  274. $passwd = md5(pSQL(_COOKIE_KEY_ . $passwd));
  275. $last_passwd_gen = date('Y-m-d H:i:s', strtotime('-' . Configuration::get('PS_PASSWD_TIME_FRONT') .
  276. 'minutes'));
  277. $secure_key = md5(uniqid(rand(), true));
  278. $active = 1;
  279. $date_add = date('Y-m-d H:i:s'); //'2011-04-04 18:29:15';
  280. $date_upd = $date_add;
  281. $_data_user_exist = checkExist($email);
  282. $_customer_id_exits = (int)$_data_user_exist['customer_id'];
  283. if (!$_customer_id_exits) {
  284. $sql = 'insert into `' . _DB_PREFIX_ . 'customer` SET
  285. id_gender = ' . $gender . ', id_default_group = ' . $id_default_group .
  286. ',
  287. firstname = \'' . $firstname . '\', lastname = \'' . $lastname . '\',
  288. email = \'' . $email . '\', passwd = \'' . $passwd . '\',
  289. last_passwd_gen = \'' . $last_passwd_gen . '\',
  290. secure_key = \'' . $secure_key . '\', active = ' . $active . ',
  291. date_add = \'' . $date_add . '\', date_upd = \'' . $date_upd . '\' ';
  292. defined('_MYSQL_ENGINE_') ? $result = Db::getInstance()->ExecuteS($sql) : $result =
  293. Db::getInstance()->Execute($sql);
  294. $insert_id = Db::getInstance()->Insert_ID();
  295. $id_group = 1;
  296. $sql = 'INSERT into `' . _DB_PREFIX_ . 'customer_group` SET
  297. id_customer = ' . $insert_id . ', id_group = ' . $id_group . ' ';
  298. defined('_MYSQL_ENGINE_') ? $result = Db::getInstance()->ExecuteS($sql) : $result =
  299. Db::getInstance()->Execute($sql);
  300. $insert = Db::getInstance()->Execute('
  301. INSERT INTO `' . _DB_PREFIX_ . 'opauth_' . strtolower($_data['provider']) .
  302. '_customer`
  303. (`' . strtolower($_data['provider']) . '_id`,`user_id`)
  304. VALUES (' . $_data["id"] . ',' . $insert_id . ')');
  305. } else {
  306. $insert_id = $_customer_id_exits;
  307. $insert = Db::getInstance()->Execute('
  308. INSERT INTO `' . _DB_PREFIX_ . 'opauth_' . strtolower($_data['provider']) .
  309. '_customer`
  310. (`' . strtolower($_data['provider']) . '_id`,`user_id`)
  311. VALUES (' . $_data["id"] . ',' . $insert_id . ')');
  312. }
  313. }
  314. // auth customer
  315. global $cookie;
  316. $customer = new Customer();
  317. $authentication = $customer->getByEmail(trim($email), trim($real_passwd));
  318. if (!$authentication or !$customer->id) {
  319. $status = 'error';
  320. echo 'Authentication failed!';
  321. } else {
  322. $cookie->id_customer = intval($customer->id);
  323. $cookie->customer_lastname = $customer->lastname;
  324. $cookie->customer_firstname = $customer->firstname;
  325. $cookie->logged = 1;
  326. $cookie->passwd = $customer->passwd;
  327. $cookie->email = $customer->email;
  328. if (Configuration::get('PS_CART_FOLLOWING') and (empty($cookie->id_cart) or Cart::
  329. getNbProducts($cookie->id_cart) == 0))
  330. $cookie->id_cart = intval(Cart::lastNoneOrderedCart(intval($customer->id)));
  331. Module::hookExec('authentication');
  332. Mail::Send(intval($cookie->id_lang), 'account', 'Welcome!', array(
  333. '{firstname}' => $customer->firstname,
  334. '{lastname}' => $customer->lastname,
  335. '{email}' => $customer->email,
  336. '{passwd}' => $real_passwd), $customer->email, $customer->firstname . ' ' . $customer->
  337. lastname);
  338. Tools::redirect('index.php');
  339. }
  340. }
  341. }
  342. }
  343. }
  344. function checkExist($email)
  345. {
  346. $sql = '
  347. SELECT * FROM `' . _DB_PREFIX_ . 'customer`
  348. WHERE `active` = 1 AND `email` = \'' . pSQL($email) . '\'
  349. AND `deleted` = 0 ' . (defined('_MYSQL_ENGINE_') ?
  350. "AND `is_guest` = 0" : "") . '
  351. ';
  352. $result = Db::getInstance()->GetRow($sql);
  353. $_customer = $result['id_customer'];
  354. return array('customer_id' => $_customer, 'result' => $result);
  355. }
  356. function deldigit($str)
  357. {
  358. $arr_out = array('');
  359. $arr_in = array(
  360. 0,
  361. 1,
  362. 2,
  363. 3,
  364. 4,
  365. 5,
  366. 6,
  367. 7,
  368. 8,
  369. 9,
  370. '_',
  371. '(',
  372. ')',
  373. ',',
  374. '«',
  375. '»',
  376. '.',
  377. '-',
  378. '+',
  379. '&');
  380. $textout = str_replace($arr_in, $arr_out, $str);
  381. return $textout;
  382. }
  383. ?>