BlueGit

blue-star tribegen

Files

tribegen / web / src / api / auth.php

auth.php

savefiks
timfa Tim · pushed by timfa · 9 months ago
143b3fa4 History
auth.php 2.1 KiB Download Raw
1<?php
2
3require_once __DIR__ . '/../../src/Classes/User.php';
4
5$method = $_SERVER['REQUEST_METHOD'];
6
7if ($method === 'POST') {
8 $input = json_decode(file_get_contents('php://input'), true);
9
10 $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
11
12 if (strpos($apiPath, 'register') !== false) {
13 try {
14 $user = User::register($input['email'], $input['password']);
15
16 // Generate a simple token (in production use JWT)
17 $token = bin2hex(random_bytes(32));
18 $_SESSION['user_id'] = $user->getId();
19 $_SESSION['user_email'] = $user->getEmail();
20 $_SESSION['token'] = $token;
21
22 echo json_encode([
23 'success' => true,
24 'user' => [
25 'id' => $user->getId(),
26 'email' => $user->getEmail(),
27 'token' => $token
28 ]
29 ]);
30 } catch (\Exception $e) {
31 http_response_code(400);
32 echo json_encode([
33 'success' => false,
34 'error' => $e->getMessage()
35 ]);
36 }
37 } elseif (strpos($apiPath, 'login') !== false) {
38 try {
39 $user = User::login($input['email'], $input['password']);
40
41 $token = bin2hex(random_bytes(32));
42 $_SESSION['user_id'] = $user->getId();
43 $_SESSION['user_email'] = $user->getEmail();
44
45 echo json_encode([
46 'success' => true,
47 'user' => [
48 'id' => $user->getId(),
49 'email' => $user->getEmail(),
50 'token' => $token
51 ]
52 ]);
53 } catch (\Exception $e) {
54 http_response_code(401);
55 echo json_encode([
56 'success' => false,
57 'error' => $e->getMessage()
58 ]);
59 }
60 }
61} elseif ($method === 'GET') {
62 $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
63
64 if (strpos($apiPath, 'logout') !== false) {
65 session_destroy();
66 echo json_encode(['success' => true]);
67 }
68}