mirror of
https://github.com/pierre42100/ComunicAPI
synced 2024-12-25 13:08:58 +00:00
Handles user login and logout
This commit is contained in:
parent
3b0272a196
commit
033da4e0e3
104
RestControllers/userController.php
Normal file
104
RestControllers/userController.php
Normal file
@ -0,0 +1,104 @@
|
||||
<?php
|
||||
/**
|
||||
* Main user controller file
|
||||
*
|
||||
* @author Pierre HUBERT
|
||||
*/
|
||||
|
||||
//Enable access to exceptions handler
|
||||
use \Jacwright\RestServer\RestException;
|
||||
|
||||
class userController
|
||||
{
|
||||
/**
|
||||
* Try to connect user and return login tokens
|
||||
*
|
||||
* @url POST /user/connectUSER
|
||||
*/
|
||||
public function connectUSER(){
|
||||
//Check variables sent in request
|
||||
if(!isset($_POST['userMail']) OR !isset($_POST['userPassword']))
|
||||
throw new RestException(401, "Missing data !");
|
||||
|
||||
//Retrieve database connection
|
||||
$db = CS::get()->db;;
|
||||
|
||||
//Extract data
|
||||
$userMail = $_POST["userMail"];
|
||||
$userPassword = $_POST['userPassword'];
|
||||
|
||||
//Try to perform login
|
||||
$loginTokens = CS::get()->user->generateUserLoginTokens($userMail, $userPassword, APIServiceID, $db);
|
||||
|
||||
if(!$loginTokens)
|
||||
throw new RestException(401, "Invalid e-mail address / password !");
|
||||
|
||||
//Return result with tokens
|
||||
return array(
|
||||
"success" => "User logged in !",
|
||||
"tokens" => array(
|
||||
"token1" => $loginTokens[0],
|
||||
"token2" => $loginTokens[1],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request token delete (= disconnectUSER)
|
||||
*
|
||||
* @url POST /user/disconnectUSER
|
||||
*/
|
||||
public function disconnectUSER(){
|
||||
//Check variables sent in request
|
||||
if(!isset($_POST['token1']) OR !isset($_POST['token2']))
|
||||
throw new RestException(401, "Missing data !");
|
||||
|
||||
//Prepare data
|
||||
$tokens = array($_POST['token1'], $_POST['token2']);
|
||||
|
||||
//Try to delete token
|
||||
if(!CS::get()->user->deleteUserLoginToken($tokens, APIServiceID))
|
||||
throw new RestException(500, "Something went wrong while trying to logout user !");
|
||||
|
||||
//Everything is ok
|
||||
return array("success" => "The user has been disconnected !");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current user infos using tokens
|
||||
*
|
||||
* @url POST /user/getCurrentUserInfos
|
||||
* @return array The result
|
||||
*/
|
||||
public function getCurrentUserInfosWithTokens() : array{
|
||||
//Check variables sent in request (for login)
|
||||
if(!isset($_POST['token1']) OR !isset($_POST['token2']))
|
||||
throw new RestException(401, "Missing tokens !");
|
||||
|
||||
//Preparing data
|
||||
$tokens = array($_POST['token1'], $_POST['token2']);
|
||||
|
||||
//Try to get user infos from token
|
||||
$userInfos = CS::get()->user->getUserInfosFromToken($tokens, APIServiceID);
|
||||
|
||||
//Check if response is empty
|
||||
if(count($userInfos) == 0)
|
||||
throw new RestException(401, "Couldn't get user data !");
|
||||
|
||||
//Return result
|
||||
return array($userInfos);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current user infos using tokens
|
||||
*
|
||||
* @url POST /user/getCurrentUserID
|
||||
*/
|
||||
public function getCurrentUserIDUsingTokens(){
|
||||
//Get user infos
|
||||
$userInfos = $this->getCurrentUserInfosWithTokens();
|
||||
|
||||
//Return userID
|
||||
return array("userID" => $userInfos[0]["userID"]);
|
||||
}
|
||||
}
|
60
classes/tokens.php
Normal file
60
classes/tokens.php
Normal file
@ -0,0 +1,60 @@
|
||||
<?php
|
||||
/**
|
||||
* Tokens checker class
|
||||
*
|
||||
* @author Pierre HUBERT
|
||||
*/
|
||||
|
||||
class Tokens{
|
||||
|
||||
/**
|
||||
* Check request tokens
|
||||
*
|
||||
* @return Boolean Depends of the validity of the tokens
|
||||
*/
|
||||
public function checkRequestTokens(){
|
||||
if(!isset($_POST['serviceName']) OR !isset($_POST['serviceToken']))
|
||||
return false; //No token specified
|
||||
|
||||
//Check tokens
|
||||
if(!$serviceID = $this->validateTokens($_POST['serviceName'], $_POST['serviceToken']))
|
||||
return false;
|
||||
|
||||
//Save service ID in a constant
|
||||
define("APIServiceID", $serviceID);
|
||||
|
||||
//Else everything went good
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check API credentials (tokens)
|
||||
*
|
||||
* @param String $serviceName The name of the service
|
||||
* @param String $token The service's token
|
||||
* @return Boolean False or Tokens ID / Depending of validity of credentials
|
||||
*/
|
||||
private function validateTokens($serviceName, $token){
|
||||
//Prepare DataBase request
|
||||
$tableName = "API_ServicesToken";
|
||||
$conditions = "WHERE serviceName = ? AND token = ?";
|
||||
$values = array(
|
||||
$serviceName,
|
||||
$token
|
||||
);
|
||||
//Make request
|
||||
$requestResult = CS::get()->db->select($tableName, $conditions, $values);
|
||||
|
||||
//Analyse result
|
||||
if(count($requestResult) == 0){
|
||||
//There is no available entries
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
//The API is correctly identified
|
||||
return $requestResult[0]['ID'];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
171
classes/user.php
Normal file
171
classes/user.php
Normal file
@ -0,0 +1,171 @@
|
||||
<?php
|
||||
/**
|
||||
* Main user class
|
||||
*
|
||||
* @author Pierre HUBER
|
||||
*/
|
||||
|
||||
class User{
|
||||
/**
|
||||
* Try to login user with returning a service token
|
||||
*
|
||||
* @param String $email The e-mail address of the user
|
||||
* @param String $password The password of the user
|
||||
* @param String $serviceID The ID of the service
|
||||
* @return String Token if success, false if fails
|
||||
*/
|
||||
public function generateUserLoginTokens($email, $password, $serviceID){
|
||||
//Try to find user ID in the database
|
||||
$conditions = "WHERE mail = ? AND password = ?";
|
||||
$values = array(
|
||||
$email,
|
||||
$this->cryptPassword($password)
|
||||
);
|
||||
$userInfos = CS::get()->db->select("utilisateurs", $conditions, $values);
|
||||
|
||||
//Check if there is anything
|
||||
if(count($userInfos) == 0)
|
||||
return false; //Not any account was found
|
||||
|
||||
//Extract first value ID
|
||||
$userID = $userInfos[0]['ID'];
|
||||
|
||||
//Check if any other token already exists
|
||||
$existingTokens = $this->getUserLoginTokenByIDs($userID, $serviceID, CS::get()->db);
|
||||
|
||||
if(is_array($existingTokens)){
|
||||
//Return result
|
||||
return $existingTokens;
|
||||
}
|
||||
|
||||
//Generate random tokens
|
||||
$token1 = random_str(75);
|
||||
$token2 = random_str(75);
|
||||
|
||||
//Insert token in the database
|
||||
$tableName = "API_userLoginToken";
|
||||
$insertValues = array(
|
||||
"ID_utilisateurs" => $userID,
|
||||
"ID_API_ServicesToken" => $serviceID,
|
||||
"token1" => $token1,
|
||||
"token2" => $token2
|
||||
);
|
||||
if(!CS::get()->db->addLine($tableName, $insertValues))
|
||||
return false; //Something went wrong
|
||||
|
||||
//We can return tokens
|
||||
return array($token1, $token2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get token with the help of userID and serviceID
|
||||
*
|
||||
* @param Integer $userID The ID of the user
|
||||
* @param Integer $serviceID The ID of the service
|
||||
* @return False if it fails, or tokens if success
|
||||
*/
|
||||
function getUserLoginTokenByIDs($userID, $serviceID){
|
||||
//Prepare database request
|
||||
$conditions = "WHERE ID_utilisateurs = ? AND ID_API_ServicesToken = ?";
|
||||
$values = array(
|
||||
$userID,
|
||||
$serviceID
|
||||
);
|
||||
$tokenInfos = CS::get()->db->select("API_userLoginToken", $conditions, $values);
|
||||
|
||||
if(count($tokenInfos) == 0)
|
||||
return false; //There is nobody at this address
|
||||
else {
|
||||
//Return tokens
|
||||
$token1 = $tokenInfos[0]['token1'];
|
||||
$token2 = $tokenInfos[0]['token2'];
|
||||
return array($token1, $token2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete token from given informations
|
||||
*
|
||||
* @param Array $tokens The tokens to delete
|
||||
* @param String $serviceID The service ID
|
||||
* @return Boolean False if it fails
|
||||
*/
|
||||
function deleteUserLoginToken(array $tokens, $serviceID){
|
||||
//Check the number of given tokens
|
||||
if(count($tokens) != 2)
|
||||
return false;
|
||||
|
||||
//Prepare database request
|
||||
$condition = "token1 = ? AND token2 = ? AND ID_API_ServicesToken = ?";
|
||||
$values = array(
|
||||
$tokens[0],
|
||||
$tokens[1],
|
||||
$serviceID
|
||||
);
|
||||
|
||||
//Try to perform request
|
||||
if(!CS::get()->db->deleteEntry("API_userLoginToken", $condition, $values))
|
||||
return false; //Something went wrong during the request
|
||||
|
||||
//Everything is ok
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get User Infos from token
|
||||
*
|
||||
* @param Array $tokens The user login tokens
|
||||
* @param String $serviceID The ID of the service
|
||||
* @return Array The result of the function (empty one if it fails)
|
||||
*/
|
||||
function getUserInfosFromToken(array $tokens, $serviceID): array {
|
||||
//Check token number
|
||||
if(count($tokens) != 2)
|
||||
return array();
|
||||
|
||||
//Prepare database request
|
||||
$tablesName = "utilisateurs, API_userLoginToken";
|
||||
$conditions = "WHERE utilisateurs.ID = API_userLoginToken.ID_utilisateurs AND API_userLoginToken.ID_API_ServicesToken = ? AND API_userLoginToken.token1 = ? AND API_userLoginToken.token2 = ?";
|
||||
$conditionsValues = array(
|
||||
$serviceID,
|
||||
$tokens[0],
|
||||
$tokens[1]
|
||||
);
|
||||
|
||||
//Perform request
|
||||
$userInfos = CS::get()->db->select($tablesName, $conditions, $conditionsValues);
|
||||
|
||||
//Check if result is correct or not
|
||||
if(count($userInfos) == 0)
|
||||
return array(); //No result
|
||||
|
||||
//Prepare return
|
||||
$return = array();
|
||||
$return['userID'] = $userInfos[0]['ID_utilisateurs'];
|
||||
$return['firstName'] = $userInfos[0]['nom'];
|
||||
$return['lastName'] = $userInfos[0]['prenom'];
|
||||
$return['mailAdress'] = $userInfos[0]['mail'];
|
||||
$return['accountCreationDate'] = $userInfos[0]['date_creation'];
|
||||
$return['publicPage'] = $userInfos[0]['public'];
|
||||
$return['openPage'] = $userInfos[0]['pageouverte'];
|
||||
$return['noCommentOnHisPage'] = $userInfos[0]['bloquecommentaire'];
|
||||
$return['allowPostFromFriendOnHisPage'] = $userInfos[0]['autoriser_post_amis'];
|
||||
$return['virtualDirectory'] = $userInfos[0]['sous_repertoire'];
|
||||
$return['personnalWebsite'] = $userInfos[0]['site_web'];
|
||||
$return['publicFriendList'] = $userInfos[0]['liste_amis_publique'];
|
||||
|
||||
//Return result
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Crypt user password
|
||||
*
|
||||
* @param String $userPassword The password to crypt
|
||||
* @return String The encrypted password
|
||||
*/
|
||||
public function cryptPassword($userPassword){
|
||||
return crypt(sha1($userPassword), sha1($userPassword));
|
||||
}
|
||||
|
||||
}
|
30
functions/errors.php
Normal file
30
functions/errors.php
Normal file
@ -0,0 +1,30 @@
|
||||
<?php
|
||||
/**
|
||||
* Error functions
|
||||
*
|
||||
* @author Pierre HUBERT
|
||||
*/
|
||||
|
||||
/**
|
||||
* Display a rest fatal error
|
||||
*
|
||||
* @param Integer $errorCode The code of the error
|
||||
* @param String $errorMessage The message of the error
|
||||
*/
|
||||
function Rest_fatal_error($errorCode, $errorMessage){
|
||||
//Returns a fatal error code
|
||||
http_response_code($errorCode);
|
||||
|
||||
//Display message
|
||||
header("Content-Type: application/json");
|
||||
|
||||
echo json_encode(array(
|
||||
"error" => array(
|
||||
"code"=>$errorCode,
|
||||
"message" => $errorMessage,
|
||||
)
|
||||
), JSON_PRETTY_PRINT);
|
||||
|
||||
//Quit
|
||||
exit();
|
||||
}
|
25
functions/strings.php
Normal file
25
functions/strings.php
Normal file
@ -0,0 +1,25 @@
|
||||
<?php
|
||||
/**
|
||||
* API specific methods
|
||||
*
|
||||
* @author Pierre HUBERT
|
||||
*/
|
||||
|
||||
/**
|
||||
* Generate a random string, using a cryptographically secure
|
||||
* pseudorandom number generator (random_int)
|
||||
*
|
||||
* @param int $length How many characters do we want?
|
||||
* @param string $keyspace A string of all possible characters
|
||||
* to select from
|
||||
* @return string
|
||||
*/
|
||||
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
|
||||
{
|
||||
$str = '';
|
||||
$max = mb_strlen($keyspace, '8bit') - 1;
|
||||
for ($i = 0; $i < $length; ++$i) {
|
||||
$str .= $keyspace[random_int(0, $max)];
|
||||
}
|
||||
return $str;
|
||||
}
|
@ -27,6 +27,14 @@ header("Access-Control-Allow-Origin: *");
|
||||
if(!isset($_GET["format"]))
|
||||
$_GET['format'] = "json";
|
||||
|
||||
//Check tokens
|
||||
if($cs->config->get("site_mode") == "debug"){
|
||||
$_POST['serviceName'] = "testService";
|
||||
$_POST['serviceToken'] = "testPasswd";
|
||||
}
|
||||
if(!$cs->tokens->checkRequestTokens())
|
||||
Rest_fatal_error(401, "Please check your tokens!");
|
||||
|
||||
/**
|
||||
* Handle Rest requests
|
||||
*/
|
||||
|
14
init.php
14
init.php
@ -29,6 +29,7 @@ $cs->register("config", $config);
|
||||
foreach(glob(PROJECT_PATH."config/*.php") as $confFile){
|
||||
require $confFile;
|
||||
}
|
||||
unset($config);
|
||||
|
||||
//Connexion to the database
|
||||
$db = new DBLibrary(($cs->config->get("site_mode") == "debug"));
|
||||
@ -37,7 +38,14 @@ $db->openMYSQL($cs->config->get('mysql')['host'],
|
||||
$cs->config->get('mysql')['user'],
|
||||
$cs->config->get('mysql')['password'],
|
||||
$cs->config->get('mysql')['database']);
|
||||
|
||||
//Delete created elements (security)
|
||||
unset($config);
|
||||
unset($db);
|
||||
|
||||
//Add token object
|
||||
$tokens = new Tokens();
|
||||
$cs->register("tokens", $tokens);
|
||||
unset($tokens);
|
||||
|
||||
//Add user object
|
||||
$user = new User();
|
||||
$cs->register("user", $user);
|
||||
unset($user);
|
Loading…
Reference in New Issue
Block a user