# ログイン・サインインシステムのサンプル

{% hint style="info" %}
このコードは少人数(1～10000)程向けのユーザーに対応したログインシステムを想定しています。
{% endhint %}

**PHPとJSDB API** を利用したシンプルな**アカウント登録・ログインシステム**の実装例です。\
ユーザーのアカウント情報をJSDBに保存し、セッションを使ってログイン状態を管理します。

***

### ファイル構成

```
/auth_system
├── index.php        // ホームページ（ログイン後に表示）
├── login.php        // ログインページ
├── register.php     // サインアップ（アカウント登録）ページ
├── logout.php       // ログアウト処理
├── style.css        // 簡易スタイルシート（オプション）
└── functions.php    // APIやセッション管理を行う共通関数
```

***

### `functions.php` (共通関数)

```php
<?php
session_start();

$apiKey = "";  // APIで使用するデータベース名
$apiEndpoint = "https://events-front.mixeder.net/v2/jsdb";

// JSDBからユーザーを取得する関数
function getUsers() {
    global $apiKey, $apiEndpoint;
    $response = file_get_contents("$apiEndpoint?key=$apiKey&action=read");
    return json_decode($response, true) ?? [];
}

// 新しいユーザーをJSDBに保存する関数
function registerUser($username, $password) {
    global $apiKey, $apiEndpoint;
    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);  // パスワードのハッシュ化
    $newUser = json_encode(["username" => $username, "password" => $hashedPassword]);

    $response = file_get_contents("$apiEndpoint?key=$apiKey&action=add&data=" . urlencode($newUser));
    return json_decode($response, true);
}

// ユーザーが存在するかを確認する関数
function findUser($username) {
    $users = getUsers();
    foreach ($users as $user) {
        if ($user['username'] === $username) {
            return $user;
        }
    }
    return null;
}

// ログイン状態を確認する関数
function isLoggedIn() {
    return isset($_SESSION['username']);
}
?>
```

***

### `register.php` (サインアップページ)

```php
<?php
require 'functions.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    if (findUser($username)) {
        $error = "このユーザー名は既に使用されています。";
    } else {
        registerUser($username, $password);
        header('Location: login.php');
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>サインアップ</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>サインアップ</h1>
    <form method="POST">
        <input type="text" name="username" placeholder="ユーザー名" required>
        <input type="password" name="password" placeholder="パスワード" required>
        <button type="submit">登録</button>
    </form>
    <?php if (isset($error)) echo "<p>$error</p>"; ?>
    <a href="login.php">ログインはこちら</a>
</body>
</html>
```

***

### `login.php` (ログインページ)

```php
<?php
require 'functions.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $user = findUser($username);

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['username'] = $username;
        header('Location: index.php');
        exit();
    } else {
        $error = "ユーザー名またはパスワードが間違っています。";
    }
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>ログイン</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>ログイン</h1>
    <form method="POST">
        <input type="text" name="username" placeholder="ユーザー名" required>
        <input type="password" name="password" placeholder="パスワード" required>
        <button type="submit">ログイン</button>
    </form>
    <?php if (isset($error)) echo "<p>$error</p>"; ?>
    <a href="register.php">アカウント登録はこちら</a>
</body>
</html>
```

***

### `index.php` (ホームページ)

```php
<?php
require 'functions.php';

if (!isLoggedIn()) {
    header('Location: login.php');
    exit();
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>ホーム</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>ようこそ、<?= htmlspecialchars($_SESSION['username']) ?>さん！</h1>
    <a href="logout.php">ログアウト</a>
</body>
</html>
```

***

### `logout.php` (ログアウト処理)

```php
<?php
session_start();
session_destroy();
header('Location: login.php');
exit();
?>
```

***

### `style.css` (簡易スタイルシート)

```css
body {
    font-family: 'Arial', sans-serif;
    background-color: #f0f0f0;
    text-align: center;
    margin-top: 50px;
}

input {
    margin: 10px;
    padding: 10px;
    width: 80%;
}

button {
    padding: 10px 20px;
    margin-top: 10px;
}

p {
    color: red;
}

a {
    display: block;
    margin-top: 20px;
}
```

***

### 説明

1. **アカウント登録** (`register.php`): ユーザー名とパスワードを登録し、JSDBに保存します。
2. **ログイン** (`login.php`): 登録済みのユーザー名とパスワードでログインし、セッションを開始します。
3. **ホームページ** (`index.php`): ログイン後、ユーザー名を表示するページです。
4. **ログアウト** (`logout.php`): セッションを破棄してログアウトします。

***

### 注意点

* **パスワードのハッシュ化**: `password_hash()` 関数でパスワードを安全に保存します。
* **JSDBのAPI**: ユーザーデータをJSON形式で管理するため、DBサーバーは不要です。
* **セッション管理**: PHPセッションでログイン状態を管理します。
