added json handler for login

This commit is contained in:
2024-09-25 11:26:47 -05:00
parent daf8dd16a4
commit 1c496e7d41

View File

@@ -44,7 +44,20 @@ $authMiddleware = $container->get(AuthMiddleware::class);
AppFactory::setContainer($container);
$app->post('/login', function ($request, $response) use ($container) {
$data = $request->getParsedBody();
// Detect the content type of the request
$contentType = $request->getHeaderLine('Content-Type');
// Initialize $data to store parsed body
$data = [];
// If Content-Type is application/json, decode the JSON body
if (strstr($contentType, 'application/json')) {
$data = json_decode($request->getBody()->getContents(), true);
} else {
// Otherwise, parse the body as form data
$data = $request->getParsedBody();
}
if (isset($data['username'], $data['password'])) {
$username = $data['username'];
$password = $data['password'];
@@ -58,6 +71,12 @@ $app->post('/login', function ($request, $response) use ($container) {
$response->getBody()->write(json_encode(['error' => 'Invalid credentials']));
return $response->withStatus(401);
}
} else {
// Handle missing fields
$response->getBody()->write(json_encode(['error' => 'Username and password required']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
}
});
$app->post('/addUser', function ($request, $response) use ($container) {