Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
P
projet-cdaw
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
1
Issues
1
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Quentin Vrel
projet-cdaw
Commits
e66ffa47
Commit
e66ffa47
authored
Nov 24, 2020
by
Zohten
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
prettier fix
parent
9e409e23
Changes
16
Hide whitespace changes
Inline
Side-by-side
Showing
16 changed files
with
395 additions
and
329 deletions
+395
-329
UserController.class.php
BackEnd/TPs/tp4/controller/UserController.class.php
+21
-16
AutoLoader.class.php
BackEnd/src/classes/AutoLoader.class.php
+15
-12
DatabasePDO.class.php
BackEnd/src/classes/DatabasePDO.class.php
+23
-19
Dispatcher.class.php
BackEnd/src/classes/Dispatcher.class.php
+10
-7
Request.class.php
BackEnd/src/classes/Request.class.php
+79
-71
Response.class.php
BackEnd/src/classes/Response.class.php
+56
-50
config.php
BackEnd/src/config/config.php
+15
-13
Controller.class.php
BackEnd/src/controller/Controller.class.php
+9
-9
DefaultController.class.php
BackEnd/src/controller/DefaultController.class.php
+13
-12
LoginController.class.php
BackEnd/src/controller/LoginController.class.php
+27
-24
UserController.class.php
BackEnd/src/controller/UserController.class.php
+21
-16
ValidateTokenController.class.php
BackEnd/src/controller/ValidateTokenController.class.php
+21
-20
index.php
BackEnd/src/index.php
+2
-2
Model.class.php
BackEnd/src/model/Model.class.php
+13
-8
User.class.php
BackEnd/src/model/User.class.php
+46
-38
User.sql.php
BackEnd/src/sql/User.sql.php
+24
-12
No files found.
BackEnd/TPs/tp4/controller/UserController.class.php
View file @
e66ffa47
...
...
@@ -4,9 +4,11 @@ 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
UserController
extends
Controller
{
public
function
__construct
(
$name
,
$request
)
{
class
UserController
extends
Controller
{
public
function
__construct
(
$name
,
$request
)
{
parent
::
__construct
(
$name
,
$request
);
}
...
...
@@ -16,16 +18,18 @@ class UserController extends Controller {
public
function
processRequest
()
{
switch
(
$this
->
request
->
getHttpMethod
())
{
switch
(
$this
->
request
->
getHttpMethod
())
{
case
'GET'
:
if
(
$this
->
request
->
getUriParams
())
if
(
$this
->
request
->
getUriParams
())
{
return
$this
->
getUser
(
$this
->
request
->
getUriParams
()[
0
]);
}
return
$this
->
getAllUsers
();
break
;
case
'PUT'
:
if
(
$this
->
request
->
getUriParams
())
return
$this
->
updateUser
(
array_merge
(
$this
->
request
->
getData
(),[
'id'
=>
$this
->
request
->
getUriParams
()[
0
]]));
if
(
$this
->
request
->
getUriParams
())
{
return
$this
->
updateUser
(
array_merge
(
$this
->
request
->
getData
(),
[
'id'
=>
$this
->
request
->
getUriParams
()[
0
]]));
}
break
;
}
return
Response
::
errorResponse
(
"unsupported parameters or method in users"
);
...
...
@@ -40,25 +44,26 @@ class UserController extends Controller {
return
$response
;
}
protected
function
getUser
(
$id
){
protected
function
getUser
(
$id
)
{
$user
=
User
::
getRow
(
$id
);
$response
=
Response
::
okResponse
(
json_encode
(
$user
));
return
$response
;
}
protected
function
updateUser
(
$array
){
protected
function
updateUser
(
$array
)
{
try
{
//var_dump($array);die;
$jwt_token
=
$this
->
request
->
getJwtToken
();
// echo "jwt = $jwt_token";
$decodedJWT
=
JWT
::
decode
(
$jwt_token
,
JWT_BACKEND_KEY
,
array
(
'HS256'
));
if
(
$decodedJWT
->
data
->
id
!=
$array
[
'id'
])
{
if
(
$decodedJWT
->
data
->
id
!=
$array
[
'id'
])
{
throw
new
Exception
(
"You don't have access to this account."
,
1
);
}
}
User
::
updateUser
(
$array
);
}
catch
(
Exception
$e
){
}
catch
(
Exception
$e
)
{
header
(
'WWW-Authenticate: Bearer realm="'
.
JWT_ISSUER
.
'"'
);
$jsonResult
=
json_encode
(
array
(
...
...
@@ -66,8 +71,8 @@ class UserController extends Controller {
"error"
=>
$e
->
getMessage
()
));
return
Response
::
unauthorizedResponse
(
$jsonResult
);
}
$response
=
Response
::
okResponse
(
'User succesfully updated !'
);
return
$response
;
}
$response
=
Response
::
okResponse
(
'User succesfully updated !'
);
return
$response
;
}
}
\ No newline at end of file
}
BackEnd/src/classes/AutoLoader.class.php
View file @
e66ffa47
<?php
class
AutoLoader
{
public
function
__construct
()
{
spl_autoload_register
(
array
(
$this
,
'load'
)
);
class
AutoLoader
{
public
function
__construct
()
{
spl_autoload_register
(
array
(
$this
,
'load'
)
);
// spl_autoload_register(array($this, 'loadComplete'));
}
// This method will be automatically executed by PHP whenever it encounters an unknown class name in the source code
private
function
load
(
$className
)
{
if
(
in_array
(
$className
.
'.class.php'
,
scandir
(
"model"
))){
private
function
load
(
$className
)
{
if
(
in_array
(
$className
.
'.class.php'
,
scandir
(
"model"
)))
{
require_once
"model/
$className
.class.php"
;
if
(
is_readable
(
"sql/
$className
.sql.php"
))
if
(
is_readable
(
"sql/
$className
.sql.php"
))
{
require_once
"sql/
$className
.sql.php"
;
}
}
if
(
in_array
(
$className
.
'.class.php'
,
scandir
(
"classes"
)))
if
(
in_array
(
$className
.
'.class.php'
,
scandir
(
"classes"
)))
{
require_once
"classes/
$className
.class.php"
;
}
if
(
in_array
(
$className
.
'.class.php'
,
scandir
(
"controller"
)))
if
(
in_array
(
$className
.
'.class.php'
,
scandir
(
"controller"
)))
{
require_once
"controller/
$className
.class.php"
;
}
// TODO : compute path of the file to load (cf. PHP function is_readable)
// it is in one of these subdirectory '/classes/', '/model/', '/controller/'
// if it is a model, load its sql queries file too in sql/ directory
}
}
$__LOADER
=
new
AutoLoader
();
\ No newline at end of file
$__LOADER
=
new
AutoLoader
();
BackEnd/src/classes/DatabasePDO.class.php
View file @
e66ffa47
<?php
class
DatabasePDO
extends
PDO
{
class
DatabasePDO
extends
PDO
{
protected
static
$singleton
=
null
;
protected
static
$singleton
=
NULL
;
public
static
function
singleton
()
{
if
(
is_null
(
static
::
$singleton
))
{
static
::
$singleton
=
new
static
();
}
public
static
function
singleton
(){
if
(
is_null
(
static
::
$singleton
))
static
::
$singleton
=
new
static
();
return
static
::
$singleton
;
}
return
static
::
$singleton
;
}
public
function
__construct
()
{
// $db = new PDO("sqlite::memory");
public
function
__construct
()
{
// $db = new PDO("sqlite::memory");
$connectionString
=
"mysql:host="
.
DB_HOST
;
$connectionString
=
"mysql:host="
.
DB_HOST
;
if
(
defined
(
'DB_PORT'
))
{
$connectionString
.=
";port="
.
DB_PORT
;
}
if
(
defined
(
'DB_PORT'
))
$connectionString
.=
";port="
.
DB_PORT
;
$connectionString
.=
";dbname="
.
DB_DATABASE
;
$connectionString
.=
";charset=utf8"
;
$connectionString
.=
";dbname="
.
DB_DATABASE
;
$connectionString
.=
";charset=utf8"
;
parent
::
__construct
(
$connectionString
,
DB_USERNAME
,
DB_PASSWORD
);
$this
->
setAttribute
(
PDO
::
ATTR_ERRMODE
,
PDO
::
ERRMODE_EXCEPTION
);
}
}
\ No newline at end of file
parent
::
__construct
(
$connectionString
,
DB_USERNAME
,
DB_PASSWORD
);
$this
->
setAttribute
(
PDO
::
ATTR_ERRMODE
,
PDO
::
ERRMODE_EXCEPTION
);
}
}
BackEnd/src/classes/Dispatcher.class.php
View file @
e66ffa47
...
...
@@ -4,18 +4,21 @@
* Analyses a request, created the right Controller passing it the request
*/
class
Dispatcher
{
public
static
function
dispatch
(
$request
)
{
return
static
::
dispatchToController
(
$request
->
getControllerName
(),
$request
);
class
Dispatcher
{
public
static
function
dispatch
(
$request
)
{
return
static
::
dispatchToController
(
$request
->
getControllerName
(),
$request
);
}
public
static
function
dispatchToController
(
$controllerName
,
$request
)
{
public
static
function
dispatchToController
(
$controllerName
,
$request
)
{
$controllerClassName
=
ucfirst
(
$controllerName
)
.
'Controller'
;
if
(
!
class_exists
(
$controllerClassName
))
if
(
!
class_exists
(
$controllerClassName
))
{
throw
(
new
Exception
(
"Class
$controllerName
does not exist"
));
}
return
new
$controllerClassName
(
$controllerName
,
$request
);
}
}
\ No newline at end of file
}
BackEnd/src/classes/Request.class.php
View file @
e66ffa47
<?php
class
Request
{
class
Request
{
protected
$controllerName
;
protected
$uriParameters
;
protected
$data
;
protected
static
$_instance
;
public
static
function
getCurrentRequest
(){
if
(
is_null
(
self
::
$_instance
))
{
self
::
$_instance
=
new
Request
();
}
public
static
function
getCurrentRequest
()
{
if
(
is_null
(
self
::
$_instance
))
{
self
::
$_instance
=
new
Request
();
}
return
self
::
$_instance
;
return
self
::
$_instance
;
}
public
function
__construct
()
{
$this
->
initBaseURI
();
$this
->
initControllerAndParametersFromURI
();
$this
->
initData
();
}
public
function
__construct
()
{
$this
->
initBaseURI
();
$this
->
initControllerAndParametersFromURI
();
$this
->
initData
();
}
// intialise baseURI
// e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/api.php => __BASE_URI = /~luc.fabresse
// e.g. http://localhost/CDAW/api.php => __BASE_URI = /CDAW
protected
function
initBaseURI
()
{
$this
->
baseURI
=
parse_url
(
$_SERVER
[
'REQUEST_URI'
],
PHP_URL_QUERY
);
}
// intialise controllerName et uriParameters
// controllerName contient chaîne 'default' ou le nom du controleur s'il est présent dans l'URI (la requête)
// uriParameters contient un tableau vide ou un tableau contenant les paramètres passés dans l'URI (la requête)
// e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/api.php
// => controllerName == 'default'
// uriParameters == []
// e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/api.php/user/1
// => controllerName == 'user'
// uriParameters == [ 1 ]
protected
function
initControllerAndParametersFromURI
(){
// intialise baseURI
// e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/api.php => __BASE_URI = /~luc.fabresse
// e.g. http://localhost/CDAW/api.php => __BASE_URI = /CDAW
protected
function
initBaseURI
()
{
$this
->
baseURI
=
parse_url
(
$_SERVER
[
'REQUEST_URI'
],
PHP_URL_QUERY
);
}
// intialise controllerName et uriParameters
// controllerName contient chaîne 'default' ou le nom du controleur s'il est présent dans l'URI (la requête)
// uriParameters contient un tableau vide ou un tableau contenant les paramètres passés dans l'URI (la requête)
// e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/api.php
// => controllerName == 'default'
// uriParameters == []
// e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/api.php/user/1
// => controllerName == 'user'
// uriParameters == [ 1 ]
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
])
$i
++
;
while
(
$i
<
strlen
(
$prefix
)
&&
$i
<
strlen
(
$uriParameters
))
{
if
(
$prefix
[
$i
]
===
$uriParameters
[
$i
])
{
$i
++
;
}
}
$uriParameters
=
substr
(
$uriParameters
,
$i
);
...
...
@@ -55,50 +60,53 @@ class Request {
$this
->
uriParameters
=
$uriSegments
;
}
// ==============
// Public API
// ==============
// ==============
// Public API
// ==============
// retourne le name du controleur qui doit traiter la requête courante
public
function
getControllerName
()
{
return
$this
->
controllerName
;
}
public
function
getUriParams
()
{
return
$this
->
uriParameters
;
}
public
function
initData
()
{
if
(
$this
->
getHttpMethod
()
===
'PUT'
||
$this
->
getHttpMethod
()
===
'POST'
){
$jsondata
=
file_get_contents
(
"php://input"
);
$this
->
data
=
json_decode
(
$jsondata
,
true
);
}
}
public
function
getControllerName
()
{
return
$this
->
controllerName
;
}
// retourne la méthode HTTP utilisée dans la requête courante
public
function
getHttpMethod
()
{
return
$_SERVER
[
"REQUEST_METHOD"
]
;
}
public
function
getUriParams
()
{
return
$this
->
uriParameters
;
}
public
function
getData
()
{
return
$this
->
data
;
}
// returns JWT token in Authorization header or throw an exception
public
function
getJwtToken
()
{
$headers
=
getallheaders
();
$autorization
=
$headers
[
'Authorization'
];
$arr
=
explode
(
" "
,
$autorization
);
public
function
initData
()
{
if
(
$this
->
getHttpMethod
()
===
'PUT'
||
$this
->
getHttpMethod
()
===
'POST'
)
{
$jsondata
=
file_get_contents
(
"php://input"
);
$this
->
data
=
json_decode
(
$jsondata
,
true
);
}
}
if
(
count
(
$arr
)
<
2
)
throw
new
Exception
(
"Missing JWT token"
);
// retourne la méthode HTTP utilisée dans la requête courante
public
function
getHttpMethod
()
{
return
$_SERVER
[
"REQUEST_METHOD"
];
}
$jwt_token
=
$arr
[
1
];
public
function
getData
()
{
return
$this
->
data
;
}
// returns JWT token in Authorization header or throw an exception
public
function
getJwtToken
()
{
$headers
=
getallheaders
();
$autorization
=
$headers
[
'Authorization'
];
$arr
=
explode
(
" "
,
$autorization
);
return
$jwt_token
;
}
if
(
count
(
$arr
)
<
2
)
{
throw
new
Exception
(
"Missing JWT token"
);
}
$jwt_token
=
$arr
[
1
];
}
\ No newline at end of file
return
$jwt_token
;
}
}
BackEnd/src/classes/Response.class.php
View file @
e66ffa47
<?php
class
Response
{
protected
$code
;
protected
$body
;
class
Response
{
protected
$code
;
protected
$body
;
public
function
__construct
(
$code
=
404
,
$msg
=
""
)
{
$this
->
code
=
$code
;
$this
->
body
=
$msg
;
}
public
function
__construct
(
$code
=
404
,
$msg
=
""
)
{
$this
->
code
=
$code
;
$this
->
body
=
$msg
;
}
public
static
function
errorResponse
(
$message
=
""
)
{
return
new
Response
(
400
,
$message
);
}
public
static
function
errorResponse
(
$message
=
""
)
{
return
new
Response
(
400
,
$message
);
}
public
static
function
serverErrorResponse
(
$message
=
""
)
{
return
new
Response
(
500
,
$message
);
}
public
static
function
serverErrorResponse
(
$message
=
""
)
{
return
new
Response
(
500
,
$message
);
}
public
static
function
okResponse
(
$message
=
""
)
{
return
new
Response
(
200
,
$message
);
}
public
static
function
okResponse
(
$message
=
""
)
{
return
new
Response
(
200
,
$message
);
}
public
static
function
notFoundResponse
(
$message
=
""
)
{
return
new
Response
(
404
,
$message
);
}
public
static
function
notFoundResponse
(
$message
=
""
)
{
return
new
Response
(
404
,
$message
);
}
public
static
function
errorInParametersResponse
(
$message
=
""
)
{
return
new
Response
(
400
,
$message
);
}
public
static
function
errorInParametersResponse
(
$message
=
""
)
{
return
new
Response
(
400
,
$message
);
}
public
static
function
unauthorizedResponse
(
$message
=
""
)
{
return
new
Response
(
401
,
$message
);
}
public
static
function
unauthorizedResponse
(
$message
=
""
)
{
return
new
Response
(
401
,
$message
);
}
public
static
function
interceptEchos
()
{
ob_start
();
}
public
static
function
interceptEchos
()
{
ob_start
();
}
public
static
function
getEchos
()
{
return
ob_get_clean
();
}
public
static
function
getEchos
()
{
return
ob_get_clean
();
}
public
function
send
()
{
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
header
(
"Access-Control-Allow-Origin: *"
);
public
function
send
()
{
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
header
(
"Access-Control-Allow-Origin: *"
);
header
(
"Content-Type: application/json; charset=UTF-8"
);
header
(
"Content-Type: application/json; charset=UTF-8"
);
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
header
(
"Access-Control-Allow-Methods: GET,POST,PUT,DELETE"
);
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
header
(
"Access-Control-Allow-Methods: GET,POST,PUT,DELETE"
);
header
(
"Access-Control-Max-Age: 3600"
);
// Maximum number of seconds the results can be cached.
header
(
"Access-Control-Max-Age: 3600"
);
// Maximum number of seconds the results can be cached.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
header
(
"Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
);
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
header
(
"Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
);
http_response_code
(
$this
->
code
);
echo
$this
->
body
;
exit
;
// do we keep that?
}
}
\ No newline at end of file
http_response_code
(
$this
->
code
);
echo
$this
->
body
;
exit
;
// do we keep that?
}
}
BackEnd/src/config/config.php
View file @
e66ffa47
<?php
define
(
'DB_HOST'
,
'127.0.0.1'
);
define
(
'DB_PORT'
,
3306
);
define
(
'DB_DATABASE'
,
'dbtest'
);
define
(
'DB_USERNAME'
,
'root'
);
define
(
'DB_PASSWORD'
,
''
);
define
(
'DB_HOST'
,
'127.0.0.1'
);
define
(
'DB_PORT'
,
3306
);
define
(
'DB_DATABASE'
,
'dbtest'
);
define
(
'DB_USERNAME'
,
'root'
);
define
(
'DB_PASSWORD'
,
''
);
// define('__DEBUG', false);
define
(
'__DEBUG'
,
true
);
define
(
'JWT_BACKEND_KEY'
,
'6d8HbcZndVGNAbo4Ih1TGaKcuA1y2BKs-I5CmP'
);
define
(
'JWT_ISSUER'
,
$_SERVER
[
'HTTP_HOST'
]
.
$_SERVER
[
'CONTEXT_PREFIX'
]);
define
(
'JWT_BACKEND_KEY'
,
'6d8HbcZndVGNAbo4Ih1TGaKcuA1y2BKs-I5CmP'
);
define
(
'JWT_ISSUER'
,
$_SERVER
[
'HTTP_HOST'
]
.
$_SERVER
[
'CONTEXT_PREFIX'
]);
// ================================================================================
// Debug utilities
// ================================================================================
if
(
__DEBUG
)
{
if
(
__DEBUG
)
{
error_reporting
(
E_ALL
);
ini_set
(
"display_errors"
,
E_ALL
);
}
else
{
...
...
@@ -24,14 +24,16 @@ if(__DEBUG) {
ini_set
(
"display_errors"
,
0
);
}
function
myLog
(
$msg
)
{
if
(
__DEBUG
)
{
function
myLog
(
$msg
)
{
if
(
__DEBUG
)
{
echo
$msg
;
}
}
function
myDump
(
$var
)
{
if
(
__DEBUG
)
{
function
myDump
(
$var
)
{
if
(
__DEBUG
)
{
var_dump
(
$var
);
}
}
\ No newline at end of file
}
BackEnd/src/controller/Controller.class.php
View file @
e66ffa47
...
...
@@ -11,26 +11,26 @@
* - return the response
*/
abstract
class
Controller
{
abstract
class
Controller
{
protected
$name
;
protected
$request
;
public
function
__construct
(
$name
,
$request
)
{
public
function
__construct
(
$name
,
$request
)
{
$this
->
request
=
$request
;
$this
->
name
=
$name
;
}
public
abstract
function
processRequest
();
abstract
public
function
processRequest
();
public
function
execute
()
{
public
function
execute
()
{
$response
=
$this
->
processRequest
();
if
(
empty
(
$response
))
{
if
(
empty
(
$response
))
{
// $response = Response::serverErrorResponse("error processing request in ". self::class); // Oh my PHP!
$response
=
Response
::
serverErrorResponse
(
"error processing request in "
.
static
::
class
);
}
return
$response
;
}
}
\ No newline at end of file
}
BackEnd/src/controller/DefaultController.class.php
View file @
e66ffa47
<?php
class
DefaultController
extends
Controller
{
public
function
__construct
(
$name
,
$request
)
{
parent
::
__construct
(
$name
,
$request
);
}
class
DefaultController
extends
Controller
{
public
function
__construct
(
$name
,
$request
)
{
parent
::
__construct
(
$name
,
$request
);
}
// ==============
// Actions
// ==============
// ==============
// Actions
// ==============
public
function
processRequest
()
{
return
Response
::
errorResponse
(
'{ "message" : "Unsupported endpoint"}'
);
public
function
processRequest
()
{
return
Response
::
errorResponse
(
'{ "message" : "Unsupported endpoint"}'
);
}
}
\ No newline at end of file
}
BackEnd/src/controller/LoginController.class.php
View file @
e66ffa47
...
...
@@ -5,33 +5,36 @@ 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
LoginController
extends
Controller
{
public
function
__construct
(
$name
,
$request
)
{
parent
::
__construct
(
$name
,
$request
);
}
class
LoginController
extends
Controller
{
public
function
__construct
(
$name
,
$request
)
{
parent
::
__construct
(
$name
,
$request
);
}
public
function
processRequest
()
{
if
(
$this
->
request
->
getHttpMethod
()
!==
'POST'
)
return
Response
::
errorResponse
(
'{ "message" : "Unsupported endpoint" }'
);
public
function
processRequest
()
{
if
(
$this
->
request
->
getHttpMethod
()
!==
'POST'
)
{
return
Response
::
errorResponse
(
'{ "message" : "Unsupported endpoint" }'
);
}
$json
=
$this
->
request
->
getData
();
if
(
!
isset
(
$json
[
'login'
])
||
!
isset
(
$json
[
'login'
]))
{
$r
=
new
Response
(
422
,
"login and pwd fields are mandatory"
);
$json
=
$this
->
request
->
getData
();
if
(
!
isset
(
$json
[
'login'
])
||
!
isset
(
$json
[
'login'
]))
{
$r
=
new
Response
(
422
,
"login and pwd fields are mandatory"
);
$r
->
send
();
}
}
$user
=
User
::
tryLogin
(
$json
[
'login'
]);
if
(
empty
(
$user
)
||
!
hash_equals
(
$json
[
'pwd'
],
$user
->
password
()))
{
$r
=
new
Response
(
422
,
"wrong credentials"
);
$user
=
User
::
tryLogin
(
$json
[
'login'
]);
if
(
empty
(
$user
)
||
!
hash_equals
(
$json
[
'pwd'
],
$user
->
password
()))
{
$r
=
new
Response
(
422
,
"wrong credentials"
);
$r
->
send
();
}
}
// generate json web token
$issued_at
=
time
();
$expiration_time
=
$issued_at
+
(
60
*
60
);
// valid for 1 hour
// generate json web token
$issued_at
=
time
();
$expiration_time
=
$issued_at
+
(
60
*
60
);
// valid for 1 hour
$token
=
array
(
$token
=
array
(
"iat"
=>
$issued_at
,
"exp"
=>
$expiration_time
,
"iss"
=>
JWT_ISSUER
,
...
...
@@ -43,13 +46,13 @@ class LoginController extends Controller {
)
);
$jwt
=
JWT
::
encode
(
$token
,
JWT_BACKEND_KEY
);
$jsonResult
=
json_encode
(
$jwt
=
JWT
::
encode
(
$token
,
JWT_BACKEND_KEY
);
$jsonResult
=
json_encode
(
array
(
"jwt_token"
=>
$jwt
)
);
);
return
Response
::
okResponse
(
$jsonResult
);
}
}
\ No newline at end of file
}
BackEnd/src/controller/UserController.class.php
View file @
e66ffa47
...
...
@@ -4,9 +4,11 @@ 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
UserController
extends
Controller
{
public
function
__construct
(
$name
,
$request
)
{
class
UserController
extends
Controller
{
public
function
__construct
(
$name
,
$request
)
{
parent
::
__construct
(
$name
,
$request
);
}
...
...
@@ -16,16 +18,18 @@ class UserController extends Controller {
public
function
processRequest
()
{
switch
(
$this
->
request
->
getHttpMethod
())
{
switch
(
$this
->
request
->
getHttpMethod
())
{
case
'GET'
:
if
(
$this
->
request
->
getUriParams
())
if
(
$this
->
request
->
getUriParams
())
{
return
$this
->
getUser
(
$this
->
request
->
getUriParams
()[
0
]);
}
return
$this
->
getAllUsers
();
break
;
case
'PUT'
:
if
(
$this
->
request
->
getUriParams
())
return
$this
->
updateUser
(
array_merge
(
$this
->
request
->
getData
(),[
'id'
=>
$this
->
request
->
getUriParams
()[
0
]]));
if
(
$this
->
request
->
getUriParams
())
{
return
$this
->
updateUser
(
array_merge
(
$this
->
request
->
getData
(),
[
'id'
=>
$this
->
request
->
getUriParams
()[
0
]]));
}
break
;
}
return
Response
::
errorResponse
(
"unsupported parameters or method in users"
);
...
...
@@ -40,25 +44,26 @@ class UserController extends Controller {
return
$response
;
}
protected
function
getUser
(
$id
){
protected
function
getUser
(
$id
)
{
$user
=
User
::
getRow
(
$id
);
$response
=
Response
::
okResponse
(
json_encode
(
$user
));
return
$response
;
}
protected
function
updateUser
(
$array
){
protected
function
updateUser
(
$array
)
{
try
{
//var_dump($array);die;
$jwt_token
=
$this
->
request
->
getJwtToken
();
// echo "jwt = $jwt_token";
$decodedJWT
=
JWT
::
decode
(
$jwt_token
,
JWT_BACKEND_KEY
,
array
(
'HS256'
));
if
(
$decodedJWT
->
data
->
id
!=
$array
[
'id'
])
{
if
(
$decodedJWT
->
data
->
id
!=
$array
[
'id'
])
{
throw
new
Exception
(
"You don't have access to this account."
,
1
);
}
}
User
::
updateUser
(
$array
);
}
catch
(
Exception
$e
){
}
catch
(
Exception
$e
)
{
header
(
'WWW-Authenticate: Bearer realm="'
.
JWT_ISSUER
.
'"'
);
$jsonResult
=
json_encode
(
array
(
...
...
@@ -66,8 +71,8 @@ class UserController extends Controller {
"error"
=>
$e
->
getMessage
()
));
return
Response
::
unauthorizedResponse
(
$jsonResult
);
}
$response
=
Response
::
okResponse
(
'User succesfully updated !'
);
return
$response
;
}
$response
=
Response
::
okResponse
(
'User succesfully updated !'
);
return
$response
;
}
}
\ No newline at end of file
}
BackEnd/src/controller/ValidateTokenController.class.php
View file @
e66ffa47
...
...
@@ -6,32 +6,33 @@ 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
);
}
class
ValidateTokenController
extends
Controller
{
public
function
__construct
(
$name
,
$request
)
{
parent
::
__construct
(
$name
,
$request
);
}
public
function
processRequest
()
{
try
{
$jwt_token
=
$this
->
request
->
getJwtToken
();
// echo "jwt = $jwt_token";
$decodedJWT
=
JWT
::
decode
(
$jwt_token
,
JWT_BACKEND_KEY
,
array
(
'HS256'
));
$jsonResult
=
json_encode
(
array
(
public
function
processRequest
()
{
try
{
$jwt_token
=
$this
->
request
->
getJwtToken
();
// echo "jwt = $jwt_token";
$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
.
'"'
);
}
catch
(
Exception
$e
){
header
(
'WWW-Authenticate: Bearer realm="'
.
JWT_ISSUER
.
'"'
);
$jsonResult
=
json_encode
(
array
(
$jsonResult
=
json_encode
(
array
(
"message"
=>
"Access denied."
,
"error"
=>
$e
->
getMessage
()
));
return
Response
::
unauthorizedResponse
(
$jsonResult
);
}
$response
=
Response
::
okResponse
(
$jsonResult
);
return
$response
;
return
Response
::
unauthorizedResponse
(
$jsonResult
);
}
$response
=
Response
::
okResponse
(
$jsonResult
);
return
$response
;
}
}
\ No newline at end of file
}
BackEnd/src/index.php
View file @
e66ffa47
...
...
@@ -4,7 +4,7 @@
// of the directory that contains this file (index.php)
// e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/index.php => __ROOT_DIR = /home/luc.fabresse/public_html
$rootDirectoryPath
=
realpath
(
dirname
(
__FILE__
));
define
(
'__ROOT_DIR'
,
$rootDirectoryPath
);
define
(
'__ROOT_DIR'
,
$rootDirectoryPath
);
// Load all application config
require_once
(
__ROOT_DIR
.
"/config/config.php"
);
...
...
@@ -25,4 +25,4 @@
$response
=
Response
::
errorResponse
(
$log
);
}
$response
->
send
();
\ No newline at end of file
$response
->
send
();
BackEnd/src/model/Model.class.php
View file @
e66ffa47
<?php
class
Model
{
protected
static
function
db
(){
class
Model
{
protected
static
function
db
()
{
return
DatabasePDO
::
singleton
();
}
// *** Queries in sql/model.sql.php ****
protected
static
$requests
=
array
();
public
static
function
addSqlQuery
(
$key
,
$sql
){
public
static
function
addSqlQuery
(
$key
,
$sql
)
{
static
::
$requests
[
$key
]
=
$sql
;
}
public
static
function
sqlQueryNamed
(
$key
){
public
static
function
sqlQueryNamed
(
$key
)
{
return
static
::
$requests
[
$key
];
}
protected
static
function
query
(
$sql
){
protected
static
function
query
(
$sql
)
{
$st
=
static
::
db
()
->
query
(
$sql
)
or
die
(
"sql query error ! request : "
.
$sql
);
$st
->
setFetchMode
(
PDO
::
FETCH_CLASS
|
PDO
::
FETCH_PROPS_LATE
,
get_called_class
());
return
$st
;
}
protected
static
function
exec
(
$sqlKey
,
$values
=
array
()){
protected
static
function
exec
(
$sqlKey
,
$values
=
array
())
{
$sth
=
static
::
db
()
->
prepare
(
static
::
sqlQueryNamed
(
$sqlKey
));
$sth
->
setFetchMode
(
PDO
::
FETCH_CLASS
|
PDO
::
FETCH_PROPS_LATE
,
get_called_class
());
$sth
->
execute
(
$values
);
return
$sth
;
}
}
\ No newline at end of file
}
BackEnd/src/model/User.class.php
View file @
e66ffa47
<?php
class
User
extends
Model
{
class
User
extends
Model
{
// ===========
// = Statics =
// ===========
protected
static
$table_name
=
'USER'
;
// load all users from Db
public
static
function
getList
()
{
$stm
=
parent
::
exec
(
'USER_LIST'
);
return
$stm
->
fetchAll
();
}
public
static
function
getRow
(
$id
)
{
$stm
=
parent
::
exec
(
'USER_GET_WITH_ID'
,
[
'id'
=>
$id
]);
return
$stm
->
fetchAll
();
}
// = Statics =
// ===========
protected
static
$table_name
=
'USER'
;
public
static
function
updateUser
(
$array
)
{
$stm
=
parent
::
exec
(
'USER_UPDATE'
,
$array
);
}
// load all users from Db
public
static
function
getList
()
{
$stm
=
parent
::
exec
(
'USER_LIST'
);
return
$stm
->
fetchAll
();
}
public
static
function
getRow
(
$id
)
{
$stm
=
parent
::
exec
(
'USER_GET_WITH_ID'
,
[
'id'
=>
$id
]);
return
$stm
->
fetchAll
();
}
public
static
function
tryLogin
(
$login
){
$stm
=
parent
::
exec
(
'USER_GET_WITH_LOGIN'
,
[
'login'
=>
$login
]);
return
$stm
->
fetchAll
(
PDO
::
FETCH_CLASS
,
'User'
)[
0
]
;
}
public
static
function
updateUser
(
$array
)
{
$stm
=
parent
::
exec
(
'USER_UPDATE'
,
$array
)
;
}
public
function
password
(){
return
trim
(
$this
->
USER_PWD
);
}
public
function
id
(){
return
trim
(
$this
->
USER_ID
);
}
public
function
firstname
(){
return
trim
(
$this
->
USER_NAME
);
}
public
function
lastname
(){
return
trim
(
$this
->
USER_SURNAME
);
}
public
function
email
(){
return
trim
(
$this
->
USER_EMAIL
);
}
public
static
function
tryLogin
(
$login
)
{
$stm
=
parent
::
exec
(
'USER_GET_WITH_LOGIN'
,
[
'login'
=>
$login
]);
return
$stm
->
fetchAll
(
PDO
::
FETCH_CLASS
,
'User'
)[
0
];
}
}
\ No newline at end of file
public
function
password
()
{
return
trim
(
$this
->
USER_PWD
);
}
public
function
id
()
{
return
trim
(
$this
->
USER_ID
);
}
public
function
firstname
()
{
return
trim
(
$this
->
USER_NAME
);
}
public
function
lastname
()
{
return
trim
(
$this
->
USER_SURNAME
);
}
public
function
email
()
{
return
trim
(
$this
->
USER_EMAIL
);
}
}
BackEnd/src/sql/User.sql.php
View file @
e66ffa47
<?php
User
::
addSqlQuery
(
'USER_LIST'
,
'SELECT * FROM USER ORDER BY USER_LOGIN'
);
User
::
addSqlQuery
(
'USER_LIST'
,
'SELECT * FROM USER ORDER BY USER_LOGIN'
);
User
::
addSqlQuery
(
'USER_GET_WITH_LOGIN'
,
'SELECT * FROM USER WHERE USER_LOGIN=:login'
);
User
::
addSqlQuery
(
'USER_GET_WITH_LOGIN'
,
'SELECT * FROM USER WHERE USER_LOGIN=:login'
);
User
::
addSqlQuery
(
'USER_GET_WITH_ID'
,
'SELECT * FROM USER WHERE USER_ID=:id'
);
User
::
addSqlQuery
(
'USER_GET_WITH_ID'
,
'SELECT * FROM USER WHERE USER_ID=:id'
);
User
::
addSqlQuery
(
'USER_CREATE'
,
'INSERT INTO USER (USER_ID, USER_LOGIN, USER_EMAIL, USER_ROLE, USER_PWD, USER_NAME, USER_SURNAME) VALUES (NULL, :login, :email, :role, :pwd, :name, :surname)'
);
User
::
addSqlQuery
(
'USER_CREATE'
,
'INSERT INTO USER (USER_ID, USER_LOGIN, USER_EMAIL, USER_ROLE, USER_PWD, USER_NAME, USER_SURNAME) VALUES (NULL, :login, :email, :role, :pwd, :name, :surname)'
);
User
::
addSqlQuery
(
'USER_CONNECT'
,
'SELECT * FROM USER WHERE USER_LOGIN=:login and USER_PWD=:password'
);
User
::
addSqlQuery
(
'USER_CONNECT'
,
'SELECT * FROM USER WHERE USER_LOGIN=:login and USER_PWD=:password'
);
User
::
addSqlQuery
(
'USER_UPDATE'
,
'UPDATE USER SET USER_EMAIL = :email WHERE USER_ID = :id'
);
\ No newline at end of file
User
::
addSqlQuery
(
'USER_UPDATE'
,
'UPDATE USER SET USER_EMAIL = :email WHERE USER_ID = :id'
);
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment