/
index.php
executable file
·98 lines (84 loc) · 2.85 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
// Import fat free library.
$f3 = require(__DIR__ . "/lib/base.php");
// Import php-jwt library
require(__DIR__ . "/vendor/firebase/php-jwt/src/BeforeValidException.php");
require(__DIR__ . "/vendor/firebase/php-jwt/src/ExpiredException.php");
require(__DIR__ . "/vendor/firebase/php-jwt/src/SignatureInvalidException.php");
require(__DIR__ . "/vendor/firebase/php-jwt/src/JWT.php");
use \Firebase\JWT\JWT;
// Import SMS library
require(__DIR__ . "/engine/SMS.php");
require(__DIR__ . "/controllers/API.php");
// Load configuration (config.ini) file.
$f3->config(__DIR__ . "/config.ini");
$f3->route('POST /api/auth', function($f3) {
// Validate POST data
// TODO
// Set response type
header('Content-type: application/json');
// Get Bcrypt instance
$crypt = Bcrypt::instance();
// Instantiate DB object
$db = new DB\SQL($f3->get('main_db'), $f3->get('main_username'), $f3->get('main_password'));
$user = $db->exec("SELECT id, username, password, description FROM users WHERE username = ?", $f3->get('POST.username'));
if ($user) {
$user = $user[0];
// Verify password
if ($crypt->verify($f3->get('POST.password'), $user['password'])) {
// Generate token
$claim = $user;
$jwtToken = JWT::encode($claim, $f3->get('key'));
// Spit out the result
echo json_encode([
"status" => "OK",
"token" => $jwtToken
]);
} else {
// Send error: wrong username or password
echo json_encode([
"status" => "ERR",
"description" => "Invalid username or password."
]);
}
} else {
// Send error: wrong username or password
echo json_encode([
"status" => "ERR",
"description" => "Invalid username or password."
]);
}
});
$f3->route('GET /api/unauthorized', function() {
header('Content-type: application-json');
echo json_encode([
"status" => "ERR",
"description" => "You don't have access to this service."
]);
});
// DEVELOPMENT ONLY
// REGISTER USER
$f3->route('GET /api/@user/@password', function($f3) {
header('Content-type: application/json');
$db = new DB\SQL($f3->get('main_db'), $f3->get('main_username'), $f3->get('main_password'));
$crypt = Bcrypt::instance();
$success = $db->exec("INSERT INTO users (username, password) VALUES (:username, :password)",
[':username' => $f3->get('PARAMS.user'), ':password' => $crypt->hash($f3->get('PARAMS.password'))]);
if ($success) {
echo json_encode([
"status" => "OK"
]);
} else {
echo json_encode([
"status" => "ERR",
"description" => "Invalid username or password."
]);
}
});
// Route: POST /api/sms
// Args:
// - recipient_phone_number: string
// - message_content: string
$f3->route('POST /api/sms', 'API->sendSMS');
// Run the app
$f3->run();