View on GitHub

ユーザモデルの定義

Home

ユーザモデルの定義

モデル

ユーザモデル

src/backend/api/online/models.py

from django.db import models
from .utils import encrypt, hash, decrypt
import uuid


class User(models.Model):
    """
    ユーザモデル

    Attributes
    ----------
    user_id : UUIDField
        ユーザID
    email_encrypted : TextField
        暗号化emailアドレス
    email_hash : CharField
        emailアドレスのハッシュ値
    """
    user_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    email_encrypted = models.TextField(blank=False, null=False, unique=True)
    email_hash = models.CharField(blank=False, null=False, unique=True, max_length=64)  # SHA256は64文字

    class Meta:
        managed = True
        db_table = 't_users'

    def set_email(self, email):
        """emailを暗号化 & ハッシュ化して保存"""
        self.email_encrypted = encrypt(email)
        self.email_hash = hash(email)

    def get_email(self):
        """暗号化されたemailを復号"""
        return decrypt(self.email_encrypted)

    def __str__(self):
        return f'User {self.user_id}: {self.get_email()}'

カスタムユーザモデルとの紐付け

src/backend/api/accounts/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

from api.online.models import User  # <- 追加


# ↓修正
class CustomUser(AbstractUser):
    """
    カスタムユーザモデル

    Attributes
    ----------
    user : OneToOneField
        ユーザ
    """
    user = models.OneToOneField(User, models.DO_NOTHING, blank=True, null=True)
# ↑修正

マイグレーション

推薦処理用のデータの準備で生成した<FERNET_KEY>を下記コマンド中の<FERNET_KEY>にセットしてください。

(recsys_full) backend$
 export ENCRYPTION_KEY=<FERNET_KEY>

(recsys_full) backend$ python manage.py makemigrations
Migrations for 'online':
  api/online/migrations/0001_initial.py
    + Create model User
Migrations for 'accounts':
  api/accounts/migrations/0002_customuser_user.py
    + Add field user to customuser

(recsys_full) backend$ python manage.py migrate
Operations to perform:
  Apply all migrations: accounts, admin, auth, contenttypes, online, sessions
Running migrations:
  Applying online.0001_initial... OK
  Applying accounts.0002_customuser_user... OK

テーブルの確認

recsys_full=# \dt
                       List of relations
 Schema |                 Name                 | Type  | Owner
--------+--------------------------------------+-------+-------
...(略)...
 public | t_users                              | table | rsl
(11 rows)

recsys_full=# \d t_users
                          Table "public.t_users"
     Column      |         Type          | Collation | Nullable | Default
-----------------+-----------------------+-----------+----------+---------
 user_id         | uuid                  |           | not null |
 email_encrypted | text                  |           | not null |
 email_hash      | character varying(64) |           | not null |
Indexes:
    "t_users_pkey" PRIMARY KEY, btree (user_id)
    "t_users_email_encrypted_f1a45f24_like" btree (email_encrypted text_pattern_ops)
    "t_users_email_encrypted_key" UNIQUE CONSTRAINT, btree (email_encrypted)
    "t_users_email_hash_baf41ae7_like" btree (email_hash varchar_pattern_ops)
    "t_users_email_hash_key" UNIQUE CONSTRAINT, btree (email_hash)
Referenced by:
    TABLE "accounts_customuser" CONSTRAINT "accounts_customuser_user_id_d3560d05_fk_t_users_user_id" FOREIGN KEY (user_id) REFERENCES t_users(user_id) DEFERRABLE INITIALLY DEFERRED

recsys_full=# \d accounts_customuser
                                Table "public.accounts_customuser"
    Column    |           Type           | Collation | Nullable |             Default
--------------+--------------------------+-----------+----------+----------------------------------
...(略)...
 user_id      | uuid                     |           |          |
Indexes:
    "accounts_customuser_pkey" PRIMARY KEY, btree (id)
    "accounts_customuser_user_id_key" UNIQUE CONSTRAINT, btree (user_id)
...(略)...
Foreign-key constraints:
    "accounts_customuser_user_id_d3560d05_fk_t_users_user_id" FOREIGN KEY (user_id) REFERENCES t_users(user_id) DEFERRABLE INITIALLY DEFERRED
...(略)...

参考

  1. 株式会社オープントーン,佐藤大輔,伊東直喜,上野啓二,『実装で学ぶフルスタック Web 開発 エンジニアの視野と知識を広げる「一気通貫」型ハンズオン』,翔泳社,2023.
    • 4-3 バックエンド(API)とフロントエンド(画面)の連携
    • 6-3 バックエンドでモデルを作成する
  2. 横瀬明仁,『現場で使える Django の教科書《基礎編》』,2018.
    • 第 6 章 モデル (Model)