BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / User.php

User.php

various fixes
timfa Tim · pushed by timfa · 9 months ago
49730f61 History
User.php 1.8 KiB Download Raw
1<?php
2
3require_once __DIR__ . '/../../src/Database/Database.php';
4require_once __DIR__ . '/../../src/System/SaveManager.php';
5
6class User
7{
8 private $id;
9 private $email;
10
11 public function __construct($id, $email)
12 {
13 $this->id = $id;
14 $this->email = $email;
15 }
16
17 public static function register($email, $password)
18 {
19 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
20 throw new \Exception('Invalid email format');
21 }
22
23 $passwordHash = password_hash($password, PASSWORD_BCRYPT);
24
25 try {
26 $db = Database::getInstance();
27 $pdo = $db->getPDO();
28 $stmt = $pdo->prepare("INSERT INTO users (email, password_hash) VALUES (?, ?)");
29 $stmt->execute([$email, $passwordHash]);
30
31 return new self($pdo->lastInsertId(), $email);
32 } catch (\PDOException $e) {
33 if (strpos($e->getMessage(), 'UNIQUE constraint failed') !== false) {
34 throw new \Exception('Email already registered');
35 }
36 throw $e;
37 }
38 }
39
40 public static function login($email, $password)
41 {
42 $db = Database::getInstance();
43 $pdo = $db->getPDO();
44
45 $stmt = $pdo->prepare("SELECT id, email, password_hash FROM users WHERE email = ?");
46 $stmt->execute([$email]);
47 $row = $stmt->fetch();
48
49 if (!$row || !password_verify($password, $row['password_hash'])) {
50 throw new \Exception('Invalid email or password');
51 }
52
53 return new self($row['id'], $row['email']);
54 }
55
56 public function getId()
57 {
58 return $this->id;
59 }
60
61 public function getEmail()
62 {
63 return $this->email;
64 }
65
66 public function getSaves()
67 {
68 $saveManager = new SaveManager();
69 return $saveManager->listUserSaves($this->id);
70 }
71}