BlueGit

blue-star tribegen

Files

tribegen / web / src / api / auth.php

auth.php

various fixes
timfa Tim · pushed by timfa · 9 months ago
49730f61 History
auth.php 2.0 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['token'] = $token;
20
21 echo json_encode([
22 'success' => true,
23 'user' => [
24 'id' => $user->getId(),
25 'email' => $user->getEmail(),
26 'token' => $token
27 ]
28 ]);
29 } catch (\Exception $e) {
30 http_response_code(400);
31 echo json_encode([
32 'success' => false,
33 'error' => $e->getMessage()
34 ]);
35 }
36 } elseif (strpos($apiPath, 'login') !== false) {
37 try {
38 $user = User::login($input['email'], $input['password']);
39
40 $token = bin2hex(random_bytes(32));
41 $_SESSION['user_id'] = $user->getId();
42 $_SESSION['token'] = $token;
43
44 echo json_encode([
45 'success' => true,
46 'user' => [
47 'id' => $user->getId(),
48 'email' => $user->getEmail(),
49 'token' => $token
50 ]
51 ]);
52 } catch (\Exception $e) {
53 http_response_code(401);
54 echo json_encode([
55 'success' => false,
56 'error' => $e->getMessage()
57 ]);
58 }
59 }
60} elseif ($method === 'GET') {
61 $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
62
63 if (strpos($apiPath, 'logout') !== false) {
64 session_destroy();
65 echo json_encode(['success' => true]);
66 }
67}