BlueGit

blue-star tribegen

Files

tribegen / web / src / api / auth.php

auth.php

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