You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

253 lines
9.0 KiB

<?php
//from : https://api.wordpress.org/secret-key/1.1/salt
define('AUTH_KEY', '2(QMu)jt|2!(9t]V!4SB/y,+T]LcvGZ8-sV@vS6RUgR!_]&S}{6/RZjAmLeW28On');
function get_client_ip()
{
$ip = null;
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
return($ip);
}
$keyring = array(
'28__u`AAs51n2KqX?hk27/=|mQI-Sv;]nP%Sd:27+pd#eb{KUK+Vui&a_|$m{+8x',
'{KoCg/!0?7_|&pjyh!D%+IHpaB]rj|NA<^}mU|un= =}|`le[~f)&h-%Qpr>mYLA',
'0{-f_Z/)J?Dr-=B2G=+U-+&ZTvN2m[+){7nO&rd{t6+|8BW!(+&Lx!U{gF&t.m(8',
'TY@V>x3x6= |?K|.dBEt2U;9su-h4kS_-4~+AuDvV4<0.:}^o:l;*&WC6P:<58?t',
'?GOHK0|EpH`X1.1DZ,-r*`?(7+<4rbG?;W*ReX+<#CUuGiQ,G^c[SJh!Q#@aHB #',
'JdF?Zl=7tE{|+VDh%SzDVj[$nV$Emkt!T9&lhUM7Ty/yRadrv,T(S7CEk rIsx,$',
'y:XeG#<+>Jb+cqB*^doW[2|N]ju8l<4?$ek?M?0aFaY>W&TJw rNCz+L7+ZN;#f=',
'E|ngUL<N+f)Qfgs$ggG5ejS${9NN7-)qlH]iB;R]xvy%e3G`C+Lb $?K(5F-Rb%u',
'!|MuVONHh33|l|`|RqQ|r%sZgCUo?FIXlPBQ`4J/Ajc$fvyS>],O).^DqOWo~Jzy',
'i2El=I~}<o.qv;A8~ {i/3]j*XghY8K+}|M]mc-Q ~m$#bJY8NdA-jOUF=|+VLyg',
'}#]wSs]%9,I0SF7A5~|5,3S_,/-(#z+L@oxJ<PM|Jro~p=P.c^EMqDgDf-F4o?Xw',
'o6h{,vP2CQ&-)gc|Z2^U^{Y^htKH}[IS|&GUtY`E`a)D@kaJr$8,dKSSm@c2D7y+'
);
function is_valid_api_key2($key) {
global $keyring;
// la clef envoyé es de la forme un md5 : un sel
// on coupe la clef en deux
$keyset = explode(':',$key);
//la premiere partie est un md5
@ $coded_key = $keyset[0];
// la deuxième est un sel => en rélité la case de tableau à utiliser
@ $salt = (int) $keyset[1];
// on utiulise l'heure comme référence
$time = strftime('%Y%m%d%H');
// connection BDD
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'apib3';
@ $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// on protège les cractères sensible de la clef interne
$mysql_safe_salt = $mysqli->real_escape_string($keyring[$salt]);
// on protège les cractères sensible de la clef fournie
$mysql_safe_key = $mysqli->real_escape_string($coded_key);
//on fait le md5 + la comparaison dans le SQL directement
$sql = "SELECT * FROM `apikey` WHERE MD5(CONCAT(`api_key`,'".$mysql_safe_salt."','".$time."')) = '".$mysql_safe_key."'";
//die($sql);
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
$mysqli->close();
return true;
}
$mysqli->close();
return false;
}
function is_valid_api_key($key) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'apib3';
@ $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$sql = "SELECT * FROM `apikey` WHERE `api_key` LIKE '".$key."'";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
$mysqli->close();
return true;
}
$mysqli->close();
return false;
}
//header('Content-type: text/plain;charset=utf-8');
header('Content-type: application/json;charset=utf-8');
$vars=array();
foreach(array('REQUEST_METHOD',
'REDIRECT_URL',
'QUERY_STRING',
'REQUEST_URI',
'REQUEST_TIME_FLOAT',
'REQUEST_TIME') as $key)
{
if(isset($_SERVER[$key]))
{
$vars[$key] = $_SERVER[$key];
}
else
{
$vars[$key] = "";
}
}
//echo json_encode($vars);
$query = preg_replace("/^\/api/","",$vars['REDIRECT_URL']);
//echo $query;
switch($query)
{
case "/toto/" :
case "/test/" :
header('HTTP/1.1 200 OK');
echo json_encode( (object) array('status'=>'active') );
break;
case '/checksaltedkey/' :
if($vars['REQUEST_METHOD'] == "GET")
{
if(isset($_GET['key']))
{
header('HTTP/1.1 200 OK');
echo json_encode( (object) array(
'valid'=>is_valid_api_key2($_GET['key']),
'ip'=>get_client_ip() ));
}
else
{
header('HTTP/1.1 403 Forbidden');
echo json_encode( (object) array('error'=>'Please provide a valid key') );
}
}
else
{
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode( (object) array('error'=>'/checksaltedkey/ requires GET method') );
}
break;
case '/users/' :
if($vars['REQUEST_METHOD'] == "GET")
{
if(isset($_GET['key']) && is_valid_api_key($_GET['key']))
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'apib3';
//si je préfixe avec @je n'aurais pas le message d'erreur.
@ $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$sql = "SELECT COUNT(*) AS nbusers FROM `user`";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
header('HTTP/1.1 200 OK');
echo json_encode( (object) array('users'=>$row['nbusers']));
$result->free_result();
$mysqli->close();
}
}
else
{
header('HTTP/1.1 403 Forbidden');
echo json_encode( (object) array('error'=>'Please provide a valid key') );
}
}
else
{
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode( (object) array('error'=>'/users/ requires GET method') );
}
break;
case "/key/" :
case "/key" :
if($vars['REQUEST_METHOD'] == "POST")
{
if(!empty($_POST['user']) && !empty($_POST['password']))
{
$uid = null;
$user = $_POST['user'];
$password = md5($_POST['password'].AUTH_KEY);
$response = array('user'=>$user,'md5'=>$password);
//essayer de se connecter à ùysql (nb sur un xampp/wammp souvent l'utilisateur root avec mot de passe vide)
//https://www.tutorialspoint.com/mysqli/mysqli_connection.htm
// na pas oublier de convertir les → en ->
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'apib3';
//si je préfixe avec @je n'aurais pas le message d'erreur.
@ $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno ) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode( (object) array('error'=>"Connect failed: ".$mysqli->connect_error ));
exit();
}
else {
$response['connection'] = 'successful';
// vérifier si l'utilisateur existe
$sql = "SELECT * FROM `user` WHERE `user` LIKE '".$user."' AND `password` ='".$password."'";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
$response['uid'] = $row['id'];
$result->free_result();
}
else {
$sql ="INSERT INTO `user` VALUES (NULL,'".$user."','".$password."')";
$result = $mysqli->query($sql);
if($mysqli->connect_errno ) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode( (object) array('error'=>"Insert failed: ".$mysqli->connect_error ));
exit();
}
else {
$uid = $mysqli->insert_id;
$response['insert'] = 'successful user id is '.$uid;
$response['uid'] = $uid;
}
}
$apikey = md5(array_rand($keyring).$response['uid'].microtime(true));
$sql ="INSERT INTO `apikey` VALUES ('".$response['uid']."','".$apikey."')";
$result = $mysqli->query($sql);
$response = array('key'=>$apikey);
}
$mysqli->close();
header('HTTP/1.1 200 OK');
echo json_encode( (object) $response );
}
else
{
header('HTTP/1.1 403 Forbidden');
echo json_encode( (object) array('error'=>'PLease provide a valid user and matching password') );
}
}
else
{
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode( (object) array('error'=>'/key/ requires POST method') );
}
break;
default :
// header('HTTP/1.1 404 Not Found');
header('HTTP/1.1 501 Not Implemented');
echo json_encode( (object) array('error'=>'This path has not been implemented') );
break;
}