Commit 9d22d3c8 authored by thibaut-felten's avatar thibaut-felten

Authentification working locally

parent 2d040a40
# projet-cdaw
# MVC API Documentation
## Open Endpoints
Open endpoints require no Authentication.
* Login : `POST /api/login/`
* Get all users infos : `GET /api.php/users/`
* Show info : `GET /api/user/{id}`
* Update info : `PUT /api/user/{id}`
## Endpoints that require Authentication
Closed endpoints require a valid Token to be included in the header of the
request.
## TP MVC
......@@ -10,7 +10,6 @@
// Load the Loader class to automatically load classes when needed
require_once(__ROOT_DIR . '/classes/AutoLoader.class.php');
// Reify the current request
$request = Request::getCurrentRequest();
Response::interceptEchos();
......
......@@ -38,6 +38,7 @@ class Request {
protected function initControllerAndParametersFromURI(){
$prefix = $_SERVER['SCRIPT_NAME'];
$uriParameters = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$i=0;
while($i<strlen($prefix) && $i<strlen($uriParameters))
if($prefix[$i]===$uriParameters[$i]){
......@@ -45,7 +46,6 @@ class Request {
}
$uriParameters = substr($uriParameters, $i);
$uriParameters = trim($uriParameters, '/');
$uriSegments = explode('/', $uriParameters);
$this->controllerName = array_shift($uriSegments) ?: "default";
......@@ -61,6 +61,10 @@ class Request {
return $this->controllerName;
}
public function getURIParams(){
return $this->uriParameters;
}
// retourne la méthode HTTP utilisée dans la requête courante
public function getHttpMethod() {
return $_SERVER["REQUEST_METHOD"];
......@@ -73,4 +77,18 @@ class Request {
return $this->jsonReceived;
}
// returns JWT token in Authorization header or throw an exception
public function getJwtToken() {
$headers = getallheaders();
$autorization = $headers['Authorization'];
$arr = explode(" ", $autorization);
if(count($arr)<2)
throw new Exception("Missing JWT token");
$jwt_token = $arr[1];
return $jwt_token;
}
}
\ No newline at end of file
......@@ -12,6 +12,10 @@ class Response {
return new Response(400,$message);
}
public static function unauthorizedResponse($message = "") {
return new Response(401,$message);
}
public static function serverErrorResponse($message = "")
{
return new Response(500,$message);
......
<?php
define('DB_HOST','localhost');
define('DB_PORT',3306);
define('DB_DBNAME','dbtest');
define('DB_USER','root');
define('DB_PASSWORD','root');
define('DB_DBNAME','thibaut_felten');
define('DB_USER','thibaut.felten');
define('DB_PASSWORD','YpIaegvG');
define( 'JWT_BACKEND_KEY', '6d8HbcZndVGNAbo4Ih1TGaKcuA1y2BKs-I5CmP' );
define( 'JWT_ISSUER', $_SERVER['HTTP_HOST'] . $_SERVER['CONTEXT_PREFIX']);
\ No newline at end of file
......@@ -23,9 +23,11 @@ class LoginController extends Controller {
}
$user = User::tryLogin($json->login);
if(empty($user) || !hash_equals($json->pwd,$user->password())) {
// print_r($user);
// exit;
if(empty($user) || !hash_equals($json->pwd,$user->USER_PASSWORD)) {
$r = new Response(422,"wrong credentials");
$r->sendWithLog();
$r->send();
}
// generate json web token
......@@ -37,10 +39,10 @@ class LoginController extends Controller {
"exp" => $expiration_time,
"iss" => JWT_ISSUER,
"data" => array(
"id" => $user->id(),
"firstname" => $user->firstname(),
"lastname" => $user->lastname(),
"email" => $user->email()
"id" => $user->USER_ID,
"firstname" => $user->USER_FIRSTNAME,
"lastname" => $user->USER_LASTNAME,
"email" => $user->USER_EMAIL
)
);
......
<?php
class UserController extends Controller {
public function __construct($name, $request) {
parent::__construct($name, $request);
}
// ==============
// Actions
// ==============
public function processRequest()
{
switch ($this->request->getHttpMethod()) {
case 'GET':
$id = $this->request->getURIParams()[0];
return $this->getUser($id);
break;
case 'POST':
$data = json_decode(file_get_contents("php://input"),TRUE);
return $this->createUser($data);
break;
case 'PUT':
$id = $this->request->getURIParams()[0];
$data = json_decode(file_get_contents("php://input"),TRUE);
return $this->updateUser($id,$data);
break;
case 'DELETE':
$id = $this->request->getURIParams()[0];
return $this->deleteUser($id);
break;
}
return Response::errorResponse("unsupported parameters or method in user");
}
protected function getUser($id)
{
$user = User::getUserById($id);
$response = new Response(200,json_encode($user));
return $response;
}
protected function deleteUser($id){
User::deleteUser($id);
$response = Response::okResponse("User deleted");
return $response;
}
protected function updateUser($id,$data)
{
$userValues = User::getUserById($id);
$userValues=($userValues[0]);
// print_r($userValues);
// exit;
if($userValues == []){
$response = Response::errorResponse("User not found");
return $response;
}else{
if(array_key_exists('USER_LOGIN',$data)){
$login = $data['USER_LOGIN'];
}else{
$login = $userValues->USER_LOGIN;
}
if(array_key_exists('USER_EMAIL',$data)){
$email = $data['USER_EMAIL'];
}else{
$email = $userValues->USER_EMAIL;
}
if(array_key_exists('USER_LASTNAME',$data)){
$lastname = $data['USER_LASTNAME'];
}else{
$lastname = $userValues->USER_LASTNAME;
}
if(array_key_exists('USER_FIRSTNAME',$data)){
$firstname = $data['USER_FIRSTNAME'];
}else{
$firstname = $userValues->USER_FIRSTNAME;
}
$user = User::updateUser(array("id" => $id, "login" => $login,"email" => $email,"lastname" => $lastname,"firstname" => $firstname));
$response = new Response(200,json_encode($user));
return $response;
}
}
protected function createUser($data)
{
$user = User::createUser(array( "login" => $data['USER_LOGIN'], "password" => $data['USER_PASSWORD'], "role" => $data['USER_ROLE'], "email" => $data['USER_EMAIL'],"lastname" => $data['USER_LASTNAME'],"firstname" => $data['USER_FIRSTNAME']));
$response = new Response(200,json_encode($user));
return $response;
}
}
<?php
include_once __ROOT_DIR . '/libs/php-jwt/src/BeforeValidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/ExpiredException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/SignatureInvalidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/JWT.php';
use \Firebase\JWT\JWT;
class ValidatetokenController extends Controller {
public function __construct($name, $request) {
parent::__construct($name, $request);
}
public function processRequest() {
try {
$jwt_token = $this->request->getJwtToken();
$decodedJWT = JWT::decode($jwt_token, JWT_BACKEND_KEY, array('HS256'));
$jsonResult = json_encode(array(
"message" => "Access granted.",
"data" => $decodedJWT
));
} catch (Exception $e){
header('WWW-Authenticate: Bearer realm="'.JWT_ISSUER.'"');
$jsonResult = json_encode(array(
"message" => "Access denied.",
"error" => $e->getMessage()
));
return Response::unauthorizedResponse($jsonResult);
}
$response = Response::okResponse($jsonResult);
return $response;
}
}
\ No newline at end of file
......@@ -12,4 +12,37 @@ class User extends Model {
$stm = parent::exec('USER_LIST');
return $stm->fetchAll();
}
public static function getUserByID($id) {
$stm = parent::exec('USER_BY_ID',array(':user_id' => $id));
return $stm->fetchAll();
}
public static function updateUser($values) {
$stm = parent::exec('USER_UPDATE',$values);
return "User updated";
}
public static function createUser($values) {
$stm = parent::exec('USER_CREATE',$values);
return "User created";
}
public static function deleteUser($id) {
$stm = parent::exec('USER_DELETE',array(':id' => $id));
return "User deleted";
}
public static function getListWithLogin($login) {
$stm = parent::exec('USER_GET_WITH_LOGIN',array(':login' => $login));
return $stm->fetchAll();
}
public static function tryLogin($login)
{
$users = static::getListWithLogin($login);
return $users[0];
}
}
\ No newline at end of file
<?php
User::addSqlQuery('USER_LIST',
'SELECT * FROM USERS ORDER BY ID');
'SELECT * FROM USER ORDER BY USER_ID');
User::addSqlQuery('USER_GET_WITH_LOGIN',
'SELECT * FROM USERS WHERE USER_LOGIN=:login');
User::addSqlQuery('USER_CREATE',
'INSERT INTO USERS (USER_ID, USER_LOGIN, USER_EMAIL, USER_ROLE, USER_PWD, USER_NAME, USER_SURNAME) VALUES (NULL, :login, :email, :role, :pwd, :name, :surname)');
'SELECT * FROM USER WHERE USER_LOGIN=:login');
User::addSqlQuery('USER_CONNECT',
'SELECT * FROM USERS WHERE USER_LOGIN=:login and USER_PWD=:password');
\ No newline at end of file
'SELECT * FROM USER WHERE USER_LOGIN=:login and USER_PASSWORD=:password');
User::addSqlQuery('USER_BY_ID',
'SELECT * FROM USER WHERE USER_ID=:user_id');
User::addSqlQuery('USER_UPDATE',
"UPDATE USER SET USER_LOGIN=:login, USER_EMAIL=:email, USER_LASTNAME=:lastname, USER_FIRSTNAME=:firstname WHERE USER_ID=:id");
User::addSqlQuery('USER_DELETE',
"DELETE FROM USER WHERE USER_ID=:id");
User::addSqlQuery('USER_CREATE',
"INSERT INTO USER (USER_ID, USER_LOGIN, USER_EMAIL, USER_ROLE, USER_PASSWORD, USER_FIRSTNAME, USER_LASTNAME) VALUES (NULL, :login, :email, :role, :password, :firstname, :lastname)");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TP 3.1</title>
</head>
<body>
<div id="board">
<div id="p1">
<div class="avatar_info"><img id="img" src="img.jpg"/></div>
<div class="hand">
<button class="tile" data-value="5" data-family="bamboo">5 b</button>
<button class="tile" data-value="5" data-family="bamboo">5 b</button>
<button class="tile" data-value="5" data-family="bamboo">5 b</button>
</div>
<div class="actionZone">
<p> Action zone </p>
<div class="pon" data-turn="3" data-status="visible">
<button class="tile" data-value="4" data-family="circle">4 c</button>
<button class="tile" data-value="4" data-family="circle">4 c</button>
<button class="tile" data-value="4" data-family="circle">4 c</button>
</div>
</div>
</div>
</div>
<button id="drawForExample"></button>
<button id="Kan">Kan</button>
</body>
<script src="script.js" ></script>
</html>
var drawButton = document.getElementById("drawForExample");
var img = document.getElementById("img");
let hand = document.querySelector(".hand");
let kanButton = document.querySelector("#Kan");
let actionZone = document.querySelector(".actionZone");
function draw(){
console.log(hand);
let tile = document.createElement("button");
tile.setAttribute("class", "tile");
tile.setAttribute("data-value", "5");
tile.setAttribute("data-family", "bamboo");
tile.textContent = "5 b";
console.log(tile);
let newTile = hand.appendChild(tile);
}
function countTiles(){
var par = document.querySelector(".avatar_info");
let count = hand.childElementCount;
let n = document.createElement("div");
n.setAttribute("class", "countIndic")
n.textContent = count + " tiles";
let ntnte = par.appendChild(n);
}
function deleteCount(){
var countIndicator = document.querySelector(".countIndic");
countIndicator.remove();
}
function kan(tiles){
// let value = tiles[0].dataset.value;
let value = 5;
let family = "bamboo";
tiles.forEach(element => {
element.remove();
});
let newKan = document.createElement("div");
newKan.setAttribute("class", "kan");
newKan.setAttribute("data-status", "visible");
newKan.setAttribute("data-turn", "4");
let kanZone = actionZone.appendChild(newKan);
for(let i = 0; i < 4; i++){
let tile = document.createElement("button");
tile.setAttribute("class", "tile");
tile.setAttribute("data-value", value);
tile.setAttribute("data-family", family);
tile.textContent= "5 b";
kanZone.appendChild(tile);
}
}
drawButton.addEventListener("click", () => draw());
img.addEventListener('mouseover', () => countTiles());
img.addEventListener('mouseleave', () => deleteCount())
kanButton.addEventListener('click', () => kan(tiles));
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment