From e10993f7aad366e5b97766f5c367a5584c40092e Mon Sep 17 00:00:00 2001
From: Amol Thite <amol_thite@tekditechnologies.com>
Date: Thu, 12 Apr 2018 17:24:18 +0530
Subject: [PATCH 1/8] feat: 2.0 Decouple the CRUD operation

---
 src/users/user.php  | 360 ++++++++++++++++++++++++++++++++++++++++++++
 src/users/users.php |  26 +++-
 2 files changed, 382 insertions(+), 4 deletions(-)
 create mode 100644 src/users/user.php

diff --git a/src/users/user.php b/src/users/user.php
new file mode 100644
index 0000000..551d0cc
--- /dev/null
+++ b/src/users/user.php
@@ -0,0 +1,360 @@
+<?php
+
+/**
+ * @package     Joomla.Site
+ * @subpackage  com_api
+ *
+ * @copyright   Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
+ * @license     GNU General Public License version 2 or later; see LICENSE.txt
+ */
+// No direct access.
+defined('_JEXEC') or die();
+
+/**
+ * User Api.
+ * Creates a new user, updates an existing user and gets data of an user
+ *
+ * @package  Joomla.Site
+ *
+ * @since    1.1
+ */
+class UsersApiResourceUser extends ApiResource
+{
+	/**
+	 * Function to create and edit user record.
+	 *
+	 * @return object|void User details on success. Raise error on failure.
+	 */
+	public function post()
+	{
+		$app						= JFactory::getApplication();
+		$userIdentifier				= $app->input->get('id', 0, 'String');
+		$formData = array();
+		$formData['username']		= $app->input->get('username', 0, 'String');
+		$formData['name']			= $app->input->get('name', 0, 'String');
+		$formData['email']			= $app->input->get('email', 0, 'String');
+		$formData['enabled']		= $app->input->get('enabled', 0, 'int');
+		$formData['activation']		= $app->input->get('activation', 0, 'int');
+		$formData['password']		= $app->input->get('password', 0, 'String');
+		$formData['groups']			= $app->input->get('groups', 0, 'Array');
+
+		$params			= JComponentHelper::getParams("com_users");
+		$response		= new stdClass;
+
+		$xidentifier	= $app->input->server->get('HTTP_IDENTIFIER');
+		$fidentifier	= $app->input->server->get('HTTP_FOURCECREATE');
+
+		if ($formData['username'] == '' || $formData['name'] == '' || $formData['email'] == '')
+		{
+			ApiError::raiseError(400, JText::_('PLG_API_USERS_REQUIRED_DATA_EMPTY_MESSAGE'));
+
+			return;
+		}
+
+		// Get current logged in user.
+		$my = JFactory::getUser();
+
+		// Check if $userIdentifier is not set
+		if (empty($userIdentifier))
+		{
+			if ($formData['password'] == '')
+			{
+				ApiError::raiseError(400, JText::_('PLG_API_USERS_REQUIRED_DATA_EMPTY_MESSAGE'));
+
+				return;
+			}
+
+			// Set default group if nothing is passed for group.
+			if (empty($formData['groups']))
+			{
+				$formData['groups'] = array($params->get("new_usertype", 2));
+			}
+
+			// Get a blank user object
+			$user = new JUser;
+
+			// Create new user.
+			$response = $this->storeUser($user, $formData);
+			$this->plugin->setResponse($response);
+
+			return;
+		}
+		else
+		{
+			// Get a user object
+			$user = $this->retriveUser($xidentifier, $userIdentifier);
+			$passedUserGroups  = array();
+
+			// If user is already present then update it according to access.
+			if (!empty($user->id))
+			{
+				$iAmSuperAdmin	= $my->authorise('core.admin');
+
+				// Check if regular user is tring to update himself.
+				if ($my->id == $user->id || $iAmSuperAdmin)
+				{
+					// If present then update or else dont include.
+					if (!empty($formData['password']))
+					{
+						$formData['password2'] = $formData['password'];
+					}
+
+					// Add newly added groups and keep the old one as it is.
+					if (!empty($formData['groups']))
+					{
+						$passedUserGroups['groups'] = array_unique(array_merge($user->groups, $formData['groups']));
+					}
+
+					$response = $this->storeUser($user, $passedUserGroups, 1);
+					$this->plugin->setResponse($response);
+
+					return;
+				}
+				else
+				{
+					ApiError::raiseError(400, JText::_('JERROR_ALERTNOAUTHOR'));
+
+					return;
+				}
+			}
+			else
+			{
+				if ($fidentifier)
+				{
+					$user		= new JUser;
+
+					if ($formData['password'] == '')
+					{
+						ApiError::raiseError(400, JText::_('PLG_API_USERS_REQUIRED_DATA_EMPTY_MESSAGE'));
+
+						return;
+					}
+
+					// Set default group if nothing is passed for group.
+					if (empty($formData['groups']))
+					{
+						$formData['groups'] = array($params->get("new_usertype", 2));
+					}
+
+					// Create new user.
+					$response = $this->storeUser($user, $formData);
+					$this->plugin->setResponse($response);
+
+					return;
+				}
+				else
+				{
+					ApiError::raiseError(400, JText::_('PLG_API_USERS_USER_ABSENT_MESSAGE'));
+
+					return;
+				}
+			}
+		}
+	}
+
+	/**
+	 * Function get for user record.
+	 *
+	 * @return object|void User details on success otherwise raise error
+	 */
+	public function get()
+	{
+		$input = JFactory::getApplication()->input;
+		$id = $input->get('id', 0, 'int');
+
+		// If we have an id try to fetch the user
+		if ($id)
+		{
+			$user = JUser::getInstance($id);
+
+			if (! $user->id)
+			{
+				ApiError::raiseError(400, JText::_('PLG_API_USERS_USER_NOT_FOUND_MESSAGE'));
+
+				return;
+			}
+
+			$this->plugin->setResponse($user);
+		}
+		else
+		{
+			$user = JFactory::getUser();
+
+			if ($user->guest)
+			{
+				ApiError::raiseError(400, JText::_('JERROR_ALERTNOAUTHOR'));
+			}
+
+			$this->plugin->setResponse($user);
+		}
+	}
+
+	/**
+	 * Function to returns userid if a user exists depending on email
+	 *
+	 * @param   string  $email  The email to search on.
+	 *
+	 * @return  integer  The user id or 0 if not found.
+	 *
+	 * @since   2.0
+	 */
+	private function getUserId($email)
+	{
+		// Initialise some variables
+		$db		= JFactory::getDbo();
+		$query	= $db->getQuery(true)
+			->select($db->quoteName('id'))
+			->from($db->quoteName('#__users'))
+			->where($db->quoteName('email') . ' = ' . $db->quote($email));
+		$db->setQuery($query, 0, 1);
+
+		return $db->loadResult();
+	}
+
+	/**
+	 * Funtion for bind and save data and return response.
+	 *
+	 * @param   Object   $user      The user object.
+	 * @param   Array    $formData  Array of user data to be added or updated.
+	 * @param   Boolean  $flag      Flag to differnciate the update of create action.
+	 *
+	 * @return  object|void  $response  the response object created on after user saving. void and raise error
+	 *
+	 * @since   2.0
+	 */
+	private function storeUser($user, $formData, $flag = 0)
+	{
+		$response = new stdClass;
+
+		if (!$user->bind($formData))
+		{
+			ApiError::raiseError(400, $user->getError());
+
+			return;
+		}
+
+		if (!$user->save())
+		{
+			ApiError::raiseError(400, $user->getError());
+
+			return;
+		}
+
+		$response->id = $user->id;
+
+		if ($flag)
+		{
+			$response->message = JText::_('PLG_API_USERS_ACCOUNT_UPDATED_SUCCESSFULLY_MESSAGE');
+		}
+		else
+		{
+			$response->message = JText::_('PLG_API_USERS_ACCOUNT_CREATED_SUCCESSFULLY_MESSAGE');
+		}
+
+		return $response;
+	}
+
+	/**
+	 * Function delete is used to delete the respective user record.
+	 *
+	 * @return void
+	 */
+	public function delete()
+	{
+		$app = JFactory::getApplication();
+		$userIdentifier	= $app->input->get('id', 0, 'STRING');
+		$xidentifier	= $app->input->server->get('HTTP_IDENTIFIER');
+
+		$loggedUser  = JFactory::getUser();
+
+		// Check if I am a Super Admin
+		$iAmSuperAdmin = $loggedUser->authorise('core.admin');
+
+		$userToDelete = $this->retriveUser($xidentifier, $userIdentifier);
+
+		if ($userToDelete->id)
+		{
+			if ($loggedUser->id == $userToDelete->id)
+			{
+				ApiError::raiseError(400, JText::_('COM_USERS_USERS_ERROR_CANNOT_DELETE_SELF'));
+
+				return;
+			}
+
+			// Access checks.
+			$allow = $loggedUser->authorise('core.delete', 'com_users');
+
+			// Don't allow non-super-admin to delete a super admin
+			$allow = (!$iAmSuperAdmin && JAccess::check($userToDelete->id, 'core.admin')) ? false : $allow;
+
+			if ($allow)
+			{
+				if (!$userToDelete->delete())
+				{
+					ApiError::raiseError(400, $userToDelete->getError());
+
+					return;
+				}
+			}
+			else
+			{
+				ApiError::raiseError(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED'));
+
+				return;
+			}
+
+			$response = new stdClass;
+			$response->message = JText::_('PLG_API_USERS_USER_DELETE_MESSAGE');
+			$this->plugin->setResponse($response);
+
+			return;
+		}
+		else
+		{
+			ApiError::raiseError(400, JText::_('PLG_API_USERS_USER_NOT_FOUND_MESSAGE'));
+
+			return;
+		}
+	}
+
+	/**
+	 * Function retriveUser for get user details depending upon the identifier.
+	 *
+	 * @param   string  $xidentifier     Flag to differnciate the column value.
+	 *
+	 * @param   string  $userIdentifier  username
+	 *
+	 * @return  object  $user  the user object created on after user finding.
+	 */
+	private function retriveUser($xidentifier, $userIdentifier)
+	{
+		$user = new stdClass;
+
+		switch ($xidentifier)
+		{
+			case 'username':
+				$userId = JUserHelper::getUserId($userIdentifier);
+
+				if (!empty($userId))
+				{
+					$user = JFactory::getUser($userId);
+				}
+				break;
+
+			case 'email':
+				$userId = $this->getUserId($userIdentifier);
+
+				if (!empty($userId))
+				{
+					$user = JFactory::getUser($userId);
+				}
+			break;
+
+			default:
+				$user = JFactory::getUser($userIdentifier);
+				break;
+		}
+
+		return $user;
+	}
+}
diff --git a/src/users/users.php b/src/users/users.php
index 9ed8a02..f2d7f76 100644
--- a/src/users/users.php
+++ b/src/users/users.php
@@ -30,13 +30,15 @@
  * @package     Joomla.Administrator
  * @subpackage  com_api
  *
- * @since       1.0
+ * @since       1.1
  */
 class UsersApiResourceUsers extends ApiResource
 {
 	/**
 	 * Function delete for user record.
 	 *
+	 *@deprecated  2.0 use UsersApiResourceUser delete instead
+	 *
 	 * @return void
 	 */
 	public function delete()
@@ -101,6 +103,7 @@ public function delete()
 	/**
 		* Function for edit user record.
 		*
+		* @deprecated  2.0 use UsersApiResourceUser post instead
 		* @return void
 		*/
 	public function put()
@@ -212,7 +215,6 @@ public function post()
 		$data['activation']    = $app->input->get('activation', 0, 'INT');
 		$data['app']    = $app->input->get('app_name', 'Easysocial App', 'STRING');
 		$data['profile_id']    = $app->input->get('profile_id', 1, 'INT');
-		global $message;
 
 		$eobj = new stdClass();
 
@@ -342,6 +344,8 @@ public function post()
 	/**
 	 * Function get for users record.
 	 *
+	 * @deprecated  2.0 This will be move in the post method of UsersApiResourceUsers  with support for filters
+	 *
 	 * @return void
 	 */
 	public function get()
@@ -378,6 +382,8 @@ public function get()
 	/**
 	 * Function create easysocial profile.
 	 *
+	 * @deprecated  2.0 This will be move in the Easysocial API
+	 * 
 	 * @return user obj
 	 */
 	public function createEsprofile($log_user)
@@ -487,7 +493,13 @@ public function createEsprofile($log_user)
 
 	}
 
-	//create field array as per easysocial
+	/**
+	 * create field array as per easysocial
+	 *
+	 * @deprecated  2.0 This will be move in the Easysocial API
+	 *
+	 * @return object
+	 */
 	public function create_field_arr($fields,$post)
 	{
 		$fld_data = array();
@@ -545,7 +557,13 @@ public function create_field_arr($fields,$post)
 		return $fld_data;
 	}
 
-	//send registration mail
+	/**
+	 * send registration mail
+	 *
+	 * @deprecated  2.0 This will be move in the Easysocial API
+	 *
+	 * @return object
+	 */
 	public function sendRegisterEmail($base_dt)
 	{
 		$config = JFactory::getConfig();

From a96aaae2f3f2aaade2fceb0c22a522afc40f275f Mon Sep 17 00:00:00 2001
From: Amol Thite <amol_thite@tekditechnologies.com>
Date: Thu, 12 Apr 2018 17:50:45 +0530
Subject: [PATCH 2/8] feat: 2.0 Decouple the CRUD operation

---
 src/users/user.php | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/src/users/user.php b/src/users/user.php
index 551d0cc..9ef5c6b 100644
--- a/src/users/user.php
+++ b/src/users/user.php
@@ -1,12 +1,12 @@
 <?php
-
 /**
  * @package     Joomla.Site
  * @subpackage  com_api
  *
- * @copyright   Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
+ * @copyright   Copyright (C) 2009-2017 Techjoomla, Techjoomla Pvt. Ltd. All rights reserved.
  * @license     GNU General Public License version 2 or later; see LICENSE.txt
  */
+
 // No direct access.
 defined('_JEXEC') or die();
 
@@ -14,7 +14,7 @@
  * User Api.
  * Creates a new user, updates an existing user and gets data of an user
  *
- * @package  Joomla.Site
+ * @package  Joomla.Plugin
  *
  * @since    1.1
  */
@@ -23,7 +23,7 @@ class UsersApiResourceUser extends ApiResource
 	/**
 	 * Function to create and edit user record.
 	 *
-	 * @return object|void User details on success. Raise error on failure.
+	 * @return object|void User details on success. raise error on failure.
 	 */
 	public function post()
 	{
@@ -162,7 +162,10 @@ public function get()
 		$input = JFactory::getApplication()->input;
 		$id = $input->get('id', 0, 'int');
 
-		// If we have an id try to fetch the user
+		/*
+		 * If we have an id try to fetch the user
+		 * @TODO write user field mapping logic here
+		 */
 		if ($id)
 		{
 			$user = JUser::getInstance($id);
@@ -324,7 +327,7 @@ public function delete()
 	 *
 	 * @param   string  $userIdentifier  username
 	 *
-	 * @return  object  $user  the user object created on after user finding.
+	 * @return  object  $user  Juser object if user exist otherwise std class.
 	 */
 	private function retriveUser($xidentifier, $userIdentifier)
 	{

From fedb3bec85887b1667ae5cfbe5ebd1dfe7a0c16c Mon Sep 17 00:00:00 2001
From: Amol Thite <amol_thite@tekditechnologies.com>
Date: Thu, 12 Apr 2018 17:56:01 +0530
Subject: [PATCH 3/8] feat: 2.0 Decouple the CRUD operation

---
 src/users/user.php | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/src/users/user.php b/src/users/user.php
index 9ef5c6b..49f9bb6 100644
--- a/src/users/user.php
+++ b/src/users/user.php
@@ -16,7 +16,7 @@
  *
  * @package  Joomla.Plugin
  *
- * @since    1.1
+ * @since    2.0
  */
 class UsersApiResourceUser extends ApiResource
 {
@@ -24,6 +24,8 @@ class UsersApiResourceUser extends ApiResource
 	 * Function to create and edit user record.
 	 *
 	 * @return object|void User details on success. raise error on failure.
+	 *
+	 * @since   2.0
 	 */
 	public function post()
 	{
@@ -156,6 +158,8 @@ public function post()
 	 * Function get for user record.
 	 *
 	 * @return object|void User details on success otherwise raise error
+	 *
+	 * @since   2.0
 	 */
 	public function get()
 	{
@@ -261,6 +265,8 @@ private function storeUser($user, $formData, $flag = 0)
 	 * Function delete is used to delete the respective user record.
 	 *
 	 * @return void
+	 *
+	 * @since   2.0
 	 */
 	public function delete()
 	{
@@ -328,6 +334,8 @@ public function delete()
 	 * @param   string  $userIdentifier  username
 	 *
 	 * @return  object  $user  Juser object if user exist otherwise std class.
+	 *
+	 * @since   2.0
 	 */
 	private function retriveUser($xidentifier, $userIdentifier)
 	{

From c52452dc736603ffef5603a1b988a6b7cbe2db0f Mon Sep 17 00:00:00 2001
From: Amol Thite <amol_thite@tekditechnologies.com>
Date: Thu, 12 Apr 2018 19:01:24 +0530
Subject: [PATCH 4/8] feat: 2.0 Decouple the CRUD operation

---
 src/users/user.php | 122 ++++++++++++++++++++++-----------------------
 1 file changed, 59 insertions(+), 63 deletions(-)

diff --git a/src/users/user.php b/src/users/user.php
index 49f9bb6..607ed6c 100644
--- a/src/users/user.php
+++ b/src/users/user.php
@@ -1,8 +1,7 @@
 <?php
 /**
- * @package     Joomla.Site
- * @subpackage  com_api
- *
+ * @package     Com.Api
+ * @subpackage  users
  * @copyright   Copyright (C) 2009-2017 Techjoomla, Techjoomla Pvt. Ltd. All rights reserved.
  * @license     GNU General Public License version 2 or later; see LICENSE.txt
  */
@@ -14,7 +13,7 @@
  * User Api.
  * Creates a new user, updates an existing user and gets data of an user
  *
- * @package  Joomla.Plugin
+ * @package  Com.Api
  *
  * @since    2.0
  */
@@ -29,22 +28,22 @@ class UsersApiResourceUser extends ApiResource
 	 */
 	public function post()
 	{
-		$app						= JFactory::getApplication();
-		$userIdentifier				= $app->input->get('id', 0, 'String');
+		$app = JFactory::getApplication();
+		$userIdentifier = $app->input->get('id', 0, 'String');
 		$formData = array();
-		$formData['username']		= $app->input->get('username', 0, 'String');
-		$formData['name']			= $app->input->get('name', 0, 'String');
-		$formData['email']			= $app->input->get('email', 0, 'String');
-		$formData['enabled']		= $app->input->get('enabled', 0, 'int');
-		$formData['activation']		= $app->input->get('activation', 0, 'int');
-		$formData['password']		= $app->input->get('password', 0, 'String');
-		$formData['groups']			= $app->input->get('groups', 0, 'Array');
-
-		$params			= JComponentHelper::getParams("com_users");
-		$response		= new stdClass;
+		$formData['username'] = $app->input->get('username', 0, 'String');
+		$formData['name'] = $app->input->get('name', 0, 'String');
+		$formData['email'] = $app->input->get('email', 0, 'String');
+		$formData['enabled'] = $app->input->get('enabled', 0, 'int');
+		$formData['activation'] = $app->input->get('activation', 0, 'int');
+		$formData['password'] = $app->input->get('password', 0, 'String');
+		$formData['groups'] = $app->input->get('groups', 0, 'Array');
+
+		$params = JComponentHelper::getParams("com_users");
+		$response = new stdClass;
 
-		$xidentifier	= $app->input->server->get('HTTP_IDENTIFIER');
-		$fidentifier	= $app->input->server->get('HTTP_FOURCECREATE');
+		$xidentifier = $app->input->server->get('HTTP_IDENTIFIER');
+		$fidentifier = $app->input->server->get('HTTP_FOURCECREATE');
 
 		if ($formData['username'] == '' || $formData['name'] == '' || $formData['email'] == '')
 		{
@@ -76,7 +75,7 @@ public function post()
 			$user = new JUser;
 
 			// Create new user.
-			$response = $this->storeUser($user, $formData);
+			$response = $this->storeUser($user, $formData, 1);
 			$this->plugin->setResponse($response);
 
 			return;
@@ -85,7 +84,7 @@ public function post()
 		{
 			// Get a user object
 			$user = $this->retriveUser($xidentifier, $userIdentifier);
-			$passedUserGroups  = array();
+			$passedUserGroups = array();
 
 			// If user is already present then update it according to access.
 			if (!empty($user->id))
@@ -107,7 +106,7 @@ public function post()
 						$passedUserGroups['groups'] = array_unique(array_merge($user->groups, $formData['groups']));
 					}
 
-					$response = $this->storeUser($user, $passedUserGroups, 1);
+					$response = $this->storeUser($user, $passedUserGroups);
 					$this->plugin->setResponse($response);
 
 					return;
@@ -123,7 +122,7 @@ public function post()
 			{
 				if ($fidentifier)
 				{
-					$user		= new JUser;
+					$user = new JUser;
 
 					if ($formData['password'] == '')
 					{
@@ -139,7 +138,7 @@ public function post()
 					}
 
 					// Create new user.
-					$response = $this->storeUser($user, $formData);
+					$response = $this->storeUser($user, $formData, 1);
 					$this->plugin->setResponse($response);
 
 					return;
@@ -197,7 +196,7 @@ public function get()
 	}
 
 	/**
-	 * Function to returns userid if a user exists depending on email
+	 * Function to return userid if a user exists depending on email
 	 *
 	 * @param   string  $email  The email to search on.
 	 *
@@ -207,9 +206,8 @@ public function get()
 	 */
 	private function getUserId($email)
 	{
-		// Initialise some variables
-		$db		= JFactory::getDbo();
-		$query	= $db->getQuery(true)
+		$db = JFactory::getDbo();
+		$query = $db->getQuery(true)
 			->select($db->quoteName('id'))
 			->from($db->quoteName('#__users'))
 			->where($db->quoteName('email') . ' = ' . $db->quote($email));
@@ -223,13 +221,13 @@ private function getUserId($email)
 	 *
 	 * @param   Object   $user      The user object.
 	 * @param   Array    $formData  Array of user data to be added or updated.
-	 * @param   Boolean  $flag      Flag to differnciate the update of create action.
+	 * @param   Boolean  $isNew     Flag to differentiate the update of create action.
 	 *
 	 * @return  object|void  $response  the response object created on after user saving. void and raise error
 	 *
 	 * @since   2.0
 	 */
-	private function storeUser($user, $formData, $flag = 0)
+	private function storeUser($user, $formData, $isNew = 0)
 	{
 		$response = new stdClass;
 
@@ -249,13 +247,13 @@ private function storeUser($user, $formData, $flag = 0)
 
 		$response->id = $user->id;
 
-		if ($flag)
+		if ($isNew)
 		{
-			$response->message = JText::_('PLG_API_USERS_ACCOUNT_UPDATED_SUCCESSFULLY_MESSAGE');
+			$response->message = JText::_('PLG_API_USERS_ACCOUNT_CREATED_SUCCESSFULLY_MESSAGE');
 		}
 		else
 		{
-			$response->message = JText::_('PLG_API_USERS_ACCOUNT_CREATED_SUCCESSFULLY_MESSAGE');
+			$response->message = JText::_('PLG_API_USERS_ACCOUNT_UPDATED_SUCCESSFULLY_MESSAGE');
 		}
 
 		return $response;
@@ -271,65 +269,63 @@ private function storeUser($user, $formData, $flag = 0)
 	public function delete()
 	{
 		$app = JFactory::getApplication();
-		$userIdentifier	= $app->input->get('id', 0, 'STRING');
-		$xidentifier	= $app->input->server->get('HTTP_IDENTIFIER');
+		$userIdentifier = $app->input->get('id', 0, 'STRING');
+		$xidentifier = $app->input->server->get('HTTP_IDENTIFIER');
 
-		$loggedUser  = JFactory::getUser();
+		$loggedUser = JFactory::getUser();
 
 		// Check if I am a Super Admin
 		$iAmSuperAdmin = $loggedUser->authorise('core.admin');
 
 		$userToDelete = $this->retriveUser($xidentifier, $userIdentifier);
 
-		if ($userToDelete->id)
+		if (!$userToDelete->id)
 		{
-			if ($loggedUser->id == $userToDelete->id)
-			{
-				ApiError::raiseError(400, JText::_('COM_USERS_USERS_ERROR_CANNOT_DELETE_SELF'));
+			ApiError::raiseError(400, JText::_('PLG_API_USERS_USER_NOT_FOUND_MESSAGE'));
 
-				return;
-			}
+			return;
+		}
 
-			// Access checks.
-			$allow = $loggedUser->authorise('core.delete', 'com_users');
+		if ($loggedUser->id == $userToDelete->id)
+		{
+			ApiError::raiseError(400, JText::_('COM_USERS_USERS_ERROR_CANNOT_DELETE_SELF'));
 
-			// Don't allow non-super-admin to delete a super admin
-			$allow = (!$iAmSuperAdmin && JAccess::check($userToDelete->id, 'core.admin')) ? false : $allow;
+			return;
+		}
 
-			if ($allow)
-			{
-				if (!$userToDelete->delete())
-				{
-					ApiError::raiseError(400, $userToDelete->getError());
+		// Access checks.
+		$allow = $loggedUser->authorise('core.delete', 'com_users');
 
-					return;
-				}
-			}
-			else
+		// Don't allow non-super-admin to delete a super admin
+		$allow = (!$iAmSuperAdmin && JAccess::check($userToDelete->id, 'core.admin')) ? false : $allow;
+
+		if ($allow)
+		{
+			if (!$userToDelete->delete())
 			{
-				ApiError::raiseError(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED'));
+				ApiError::raiseError(400, $userToDelete->getError());
 
 				return;
 			}
-
-			$response = new stdClass;
-			$response->message = JText::_('PLG_API_USERS_USER_DELETE_MESSAGE');
-			$this->plugin->setResponse($response);
-
-			return;
 		}
 		else
 		{
-			ApiError::raiseError(400, JText::_('PLG_API_USERS_USER_NOT_FOUND_MESSAGE'));
+			ApiError::raiseError(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED'));
 
 			return;
 		}
+
+		$response = new stdClass;
+		$response->message = JText::_('PLG_API_USERS_USER_DELETE_MESSAGE');
+		$this->plugin->setResponse($response);
+
+		return;
 	}
 
 	/**
 	 * Function retriveUser for get user details depending upon the identifier.
 	 *
-	 * @param   string  $xidentifier     Flag to differnciate the column value.
+	 * @param   string  $xidentifier     Flag to differentiate the column value.
 	 *
 	 * @param   string  $userIdentifier  username
 	 *

From 6ceda71bb64fa79990a823e02d1b8d96c29fca66 Mon Sep 17 00:00:00 2001
From: Amol Thite <amol_thite@tekditechnologies.com>
Date: Wed, 18 Apr 2018 19:38:33 +0530
Subject: [PATCH 5/8] feat: 2.0 Decouple the CRUD operation

---
 src/users.php      |  1 +
 src/users/user.php | 12 ++----------
 2 files changed, 3 insertions(+), 10 deletions(-)

diff --git a/src/users.php b/src/users.php
index a46af06..bd8e736 100644
--- a/src/users.php
+++ b/src/users.php
@@ -26,5 +26,6 @@ public function __construct(&$subject, $config = array())
 		$this->setResourceAccess('login', 'public','get');
 		$this->setResourceAccess('users', 'public', 'post');
 		$this->setResourceAccess('config', 'public', 'get');
+		$this->setResourceAccess('user', 'public', 'post');
 	}
 }
diff --git a/src/users/user.php b/src/users/user.php
index 607ed6c..d0795e9 100644
--- a/src/users/user.php
+++ b/src/users/user.php
@@ -30,20 +30,12 @@ public function post()
 	{
 		$app = JFactory::getApplication();
 		$userIdentifier = $app->input->get('id', 0, 'String');
-		$formData = array();
-		$formData['username'] = $app->input->get('username', 0, 'String');
-		$formData['name'] = $app->input->get('name', 0, 'String');
-		$formData['email'] = $app->input->get('email', 0, 'String');
-		$formData['enabled'] = $app->input->get('enabled', 0, 'int');
-		$formData['activation'] = $app->input->get('activation', 0, 'int');
-		$formData['password'] = $app->input->get('password', 0, 'String');
-		$formData['groups'] = $app->input->get('groups', 0, 'Array');
-
+		$formData = $app->input->getArray();
 		$params = JComponentHelper::getParams("com_users");
 		$response = new stdClass;
 
 		$xidentifier = $app->input->server->get('HTTP_IDENTIFIER');
-		$fidentifier = $app->input->server->get('HTTP_FOURCECREATE');
+		$fidentifier = $app->input->server->get('HTTP_FORCECREATE');
 
 		if ($formData['username'] == '' || $formData['name'] == '' || $formData['email'] == '')
 		{

From 3f0d090d90349d80a178e405a1c966a4582aa28d Mon Sep 17 00:00:00 2001
From: Manoj L <manoj_l@techjoomla.com>
Date: Wed, 9 Jan 2019 15:35:33 +0530
Subject: [PATCH 6/8] Task #139177 feat: Generate JWT token during login

---
 src/users/login.php | 37 +++++++++++++++++++++++++++++++------
 1 file changed, 31 insertions(+), 6 deletions(-)

diff --git a/src/users/login.php b/src/users/login.php
index 568f36f..bb18d57 100644
--- a/src/users/login.php
+++ b/src/users/login.php
@@ -8,6 +8,10 @@
 
 defined('_JEXEC') or die( 'Restricted access' );
 
+require_once JPATH_SITE . '/components/com_api/vendors/php-jwt/src/JWT.php';
+
+use Firebase\JWT\JWT;
+
 jimport('joomla.plugin.plugin');
 jimport('joomla.html.html');
 jimport('joomla.application.component.controller');
@@ -39,7 +43,7 @@ public function keygen()
 		//init variable
 		$obj = new stdclass;
 		$umodel = new JUser;
-		$user = $umodel->getInstance();       
+		$user = $umodel->getInstance();
 
 		$app = JFactory::getApplication();
 		$username = $app->input->get('username', 0, 'STRING');
@@ -50,7 +54,7 @@ public function keygen()
 		if($id == null)
 		{
 			$model = FD::model('Users');
-			$id = $model->getUserId('email', $username);            
+			$id = $model->getUserId('email', $username);
 		}
 
 		$kmodel = new ApiModelKey;
@@ -83,7 +87,7 @@ public function keygen()
 
 				$result = $kmodel->save($data);
 				$key = $result->hash;
-				
+
 				//add new key in easysocial table
 				$easyblog = JPATH_ROOT . '/administrator/components/com_easyblog/easyblog.php';
 				if (JFile::exists($easyblog) && JComponentHelper::isEnabled('com_easysocial', true))
@@ -91,13 +95,34 @@ public function keygen()
 					$this->updateEauth( $user , $key );
 				}
 		}
-		
+
 		if( !empty($key) )
 		{
 			$obj->auth = $key;
 			$obj->code = '200';
 			//$obj->id = $user->id;
 			$obj->id = $id;
+
+			// Generate claim for jwt
+			$data = [
+				"id" => trim($id),
+				/*"iat" => '',
+				"exp" => '',
+				"aud" => '',
+				"sub" => ''"*/
+			];
+
+			// Using HS256 algo to generate JWT
+			$jwt = JWT::encode($data, trim($key), 'HS256');
+
+			if (isset($jwt) && $jwt != '')
+			{
+				$obj->jwt = $jwt;
+			}
+			else
+			{
+				$obj->jwt = false;
+			}
 		}
 		else
 		{
@@ -105,9 +130,9 @@ public function keygen()
 			$obj->message = JText::_('PLG_API_USERS_BAD_REQUEST_MESSAGE');
 		}
 		return( $obj );
-	
+
 	}
-	
+
 	/*
 	 * function to update Easyblog auth keys
 	 */

From 998c552dfceb8f9ad8d44abd146c38c7487e3463 Mon Sep 17 00:00:00 2001
From: Manoj L <manoj_l@techjoomla.com>
Date: Thu, 10 Jan 2019 10:33:06 +0530
Subject: [PATCH 7/8] Issue #139177 chore: Version change

---
 src/users.xml | 28 ++++++++++++++--------------
 1 file changed, 14 insertions(+), 14 deletions(-)

diff --git a/src/users.xml b/src/users.xml
index 5cfaa6a..fd0cf27 100644
--- a/src/users.xml
+++ b/src/users.xml
@@ -1,19 +1,19 @@
 <?xml version="1.0" encoding="utf-8"?>
 <extension version="3.0.0" type="plugin" group="api" method="upgrade">
-    <name>PLG_API_USERS</name>
-    <version>1.8.7</version>
-    <creationDate>10/11/2014</creationDate>
-    <author>Techjoomla</author> 
-    <authorEmail>extensions@techjoomla.com</authorEmail> 
-    <authorUrl>www.techjoomla.com</authorUrl> 
-    <copyright>Techjoomla. All rights reserved.</copyright> 
-    <license>http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL</license>
-    <description>PLG_API_USERS_DESCRIPTION</description>
-    <files>
-        <filename plugin="users">users.php</filename>
-        <folder>users</folder> 
-    </files>
-    <languages folder="language">
+	<name>PLG_API_USERS</name>
+	<version>2.0.0</version>
+	<creationDate>10th Jan 2019</creationDate>
+	<author>Techjoomla</author>
+	<authorEmail>extensions@techjoomla.com</authorEmail>
+	<authorUrl>www.techjoomla.com</authorUrl>
+	<copyright>Techjoomla. All rights reserved.</copyright>
+	<license>http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL</license>
+	<description>PLG_API_USERS_DESCRIPTION</description>
+	<files>
+		<filename plugin="users">users.php</filename>
+		<folder>users</folder>
+	</files>
+	<languages folder="language">
 		<language tag="en-GB">en-GB/en-GB.plg_api_users.ini</language>
 		<language tag="en-GB">en-GB/en-GB.plg_api_users.sys.ini</language>
 	</languages>

From e40b710f7ae08bdfa9ef26b4f9c0bbe3ba255c1b Mon Sep 17 00:00:00 2001
From: Manoj L <manojLondhe@users.noreply.github.com>
Date: Thu, 10 Jan 2019 14:25:36 +0530
Subject: [PATCH 8/8] fix: Use backend model to get / generate key/hash (#11)

* Task #139177 fix: Use backend model to get / generate key/hash

* Task #139177 fix: Scrutinizer issues
---
 src/users/login.php | 152 +++++++++++++++++++++++++++++---------------
 1 file changed, 102 insertions(+), 50 deletions(-)

diff --git a/src/users/login.php b/src/users/login.php
index bb18d57..ba2b5b8 100644
--- a/src/users/login.php
+++ b/src/users/login.php
@@ -1,12 +1,15 @@
 <?php
 /**
- * @package API plugins
- * @copyright Copyright (C) 2009 2014 Techjoomla, Tekdi Technologies Pvt. Ltd. All rights reserved.
- * @license GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
- * @link http://www.techjoomla.com
+ * @package     API
+ * @subpackage  plg_api_users
+ *
+ * @author      Techjoomla <extensions@techjoomla.com>
+ * @copyright   Copyright (C) 2009 - 2019 Techjoomla, Tekdi Technologies Pvt. Ltd. All rights reserved.
+ * @license     GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
  */
 
-defined('_JEXEC') or die( 'Restricted access' );
+// No direct access.
+defined('_JEXEC') or die('Restricted access');
 
 require_once JPATH_SITE . '/components/com_api/vendors/php-jwt/src/JWT.php';
 
@@ -23,84 +26,125 @@
 JModelLegacy::addIncludePath(JPATH_SITE . 'components/com_api/models');
 require_once JPATH_SITE . '/components/com_api/libraries/authentication/user.php';
 require_once JPATH_SITE . '/components/com_api/libraries/authentication/login.php';
-require_once JPATH_SITE . '/components/com_api/models/key.php';
-require_once JPATH_SITE . '/components/com_api/models/keys.php';
+require_once JPATH_ADMINISTRATOR . '/components/com_api/models/key.php';
+require_once JPATH_ADMINISTRATOR . '/components/com_api/models/keys.php';
 
+/**
+ * Login API resource class
+ *
+ * @package  API
+ * @since    1.6.0
+ */
 class UsersApiResourceLogin extends ApiResource
 {
+	/**
+	 * Get method
+	 *
+	 * @return  object
+	 */
 	public function get()
 	{
-		$this->plugin->setResponse( JText::_('PLG_API_USERS_GET_METHOD_NOT_ALLOWED_MESSAGE'));
+		$this->plugin->setResponse(JText::_('PLG_API_USERS_GET_METHOD_NOT_ALLOWED_MESSAGE'));
 	}
 
+	/**
+	 * Post method
+	 *
+	 * @return  object
+	 */
 	public function post()
 	{
 		$this->plugin->setResponse($this->keygen());
 	}
 
+	/**
+	 * Generate key method
+	 *
+	 * @return  object|boolean
+	 */
 	public function keygen()
 	{
-		//init variable
-		$obj = new stdclass;
+		// Init variable
+		$obj    = new stdclass;
 		$umodel = new JUser;
-		$user = $umodel->getInstance();
+		$user   = $umodel->getInstance();
 
-		$app = JFactory::getApplication();
+		$app      = JFactory::getApplication();
 		$username = $app->input->get('username', 0, 'STRING');
 
 		$user = JFactory::getUser();
-		$id = JUserHelper::getUserId($username);
+		$id   = JUserHelper::getUserId($username);
 
-		if($id == null)
+		if ($id == null)
 		{
 			$model = FD::model('Users');
-			$id = $model->getUserId('email', $username);
+			$id    = $model->getUserId('email', $username);
 		}
 
 		$kmodel = new ApiModelKey;
-		$model = new ApiModelKeys;
-		$key = null;
+		$model  = new ApiModelKeys;
+		$key    = null;
+
 		// Get login user hash
-		//$kmodel->setState('user_id', $user->id);
-		$kmodel->setState('user_id', $id);
-		$log_hash = $kmodel->getList();
-		$log_hash = (!empty($log_hash))?$log_hash[count($log_hash) - count($log_hash)]:$log_hash;
+		// $kmodel->setState('user_id', $user->id);
+
+		// $kmodel->setState('user_id', $id);
+		// $log_hash = $kmodel->getList();
+		$model->setState('user_id', $id);
+		$log_hash = $model->getItems();
+
+		$log_hash = (!empty($log_hash)) ? $log_hash[count($log_hash) - count($log_hash)] : $log_hash;
 
-		if( !empty($log_hash) )
+		if (!empty($log_hash))
 		{
 			$key = $log_hash->hash;
 		}
-		elseif( $key == null || empty($key) )
+		elseif ($key == null || empty($key))
 		{
-				// Create new key for user
-				$data = array(
+			// Create new key for user
+			$data = array (
 				'userid' => $user->id,
 				'domain' => '' ,
-				'state' => 1,
-				'id' => '',
-				'task' => 'save',
-				'c' => 'key',
-				'ret' => 'index.php?option=com_api&view=keys',
+				'state'  => 1,
+				'id'     => '',
+				'task'   => 'save',
+				'c'      => 'key',
+				'ret'    => 'index.php?option=com_api&view=keys',
 				'option' => 'com_api',
 				JSession::getFormToken() => 1
-				);
+			);
 
-				$result = $kmodel->save($data);
-				$key = $result->hash;
+			$result = $kmodel->save($data);
 
-				//add new key in easysocial table
-				$easyblog = JPATH_ROOT . '/administrator/components/com_easyblog/easyblog.php';
-				if (JFile::exists($easyblog) && JComponentHelper::isEnabled('com_easysocial', true))
-				{
-					$this->updateEauth( $user , $key );
-				}
+			// $key  = $result->hash;
+
+			if (!$result)
+			{
+				return false;
+			}
+
+			// Load api key table
+			JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_api/tables');
+			$table = JTable::getInstance('Key', 'ApiTable');
+			$table->load(array('userid' => $user->id));
+			$key = $table->hash;
+
+			// Add new key in easysocial table
+			$easyblog = JPATH_ROOT . '/administrator/components/com_easyblog/easyblog.php';
+
+			if (JFile::exists($easyblog) && JComponentHelper::isEnabled('com_easysocial', true))
+			{
+				$this->updateEauth($user, $key);
+			}
 		}
 
-		if( !empty($key) )
+		if (!empty($key))
 		{
 			$obj->auth = $key;
 			$obj->code = '200';
-			//$obj->id = $user->id;
+
+			// $obj->id = $user->id;
+
 			$obj->id = $id;
 
 			// Generate claim for jwt
@@ -129,21 +173,29 @@ public function keygen()
 			$obj->code = 403;
 			$obj->message = JText::_('PLG_API_USERS_BAD_REQUEST_MESSAGE');
 		}
-		return( $obj );
 
+		return ($obj);
 	}
 
-	/*
-	 * function to update Easyblog auth keys
+	/**
+	 * Method to update Easyblog auth keys
+	 *
+	 * @param   mixed  $user  User object
+	 * @param   mixed  $key   Key
+	 *
+	 * @return  integer
+	 *
+	 * @since   1.6
 	 */
-	public function updateEauth($user=null,$key=null)
+	public function updateEauth ($user = null, $key = null)
 	{
-		require_once JPATH_ADMINISTRATOR.'/components/com_easysocial/includes/foundry.php';
-		$model 	= FD::model('Users');
-		$id 	= $model->getUserId('username', $user->username);
-		$user 	= FD::user($id);
+		require_once JPATH_ADMINISTRATOR . '/components/com_easysocial/includes/foundry.php';
+
+		$model = FD::model('Users');
+		$id    = $model->getUserId('username', $user->username);
+		$user  = FD::user($id);
 		$user->alias = $user->username;
-		$user->auth = $key;
+		$user->auth  = $key;
 		$user->store();
 
 		return $id;
