ユーザモデルの定義
モデル
backend/api/online/models.py
from django.db import models
from .utils import encrypt, hash, decrypt # <- 追加
import uuid # <- 追加
# ↓追加
class User(models.Model):
"""ユーザモデル
Attributes
----------
id : UUIDField
ユーザID
email_encrypted : TextField
暗号化emailアドレス
email_hash : CharField
emailアドレスのハッシュ値
"""
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(max_length=64, blank=False, null=False, unique=True) # SHA256は64文字
class Meta:
managed = True
db_table = '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 '{}:{}:{}'.format(self.id, self.email_encrypted, self.email_hash)
# ↑追加
マイグレーション
推薦処理用のデータの準備で生成した【Fernetキー】を下記コマンド中の【Fernetキー】にセットしてください。
(recsys_full) backend$ export ENCRYPTION_KEY=【Fernetキー】
(recsys_full) backend$ python manage.py makemigrations online --settings config.settings.development
Migrations for 'online':
api/online/migrations/0001_initial.py
+ Create model User
(recsys_full) backend$ python manage.py sqlmigrate online 0001 --settings config.settings.development
(recsys_full) backend$ python manage.py migrate --settings config.settings.development
テーブルの確認
recsys_full=# \dt
List of relations
Schema | Name | Type | Owner
--------+----------------------------+-------+-------
public | auth_group | table | rsl
public | auth_group_permissions | table | rsl
public | auth_permission | table | rsl
public | auth_user | table | rsl
public | auth_user_groups | table | rsl
public | auth_user_user_permissions | table | rsl
public | django_admin_log | table | rsl
public | django_content_type | table | rsl
public | django_migrations | table | rsl
public | django_session | table | rsl
public | users | table | rsl
(11 rows)
recsys_full=# \d users
Table "public.users"
Column | Type | Collation | Nullable | Default
-----------------+-----------------------+-----------+----------+---------
id | uuid | | not null |
email_encrypted | text | | not null |
email_hash | character varying(64) | | not null |
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
"users_email_encrypted_ea091e75_like" btree (email_encrypted text_pattern_ops)
"users_email_encrypted_key" UNIQUE CONSTRAINT, btree (email_encrypted)
"users_email_hash_4fb39908_like" btree (email_hash varchar_pattern_ops)
"users_email_hash_key" UNIQUE CONSTRAINT, btree (email_hash)
参考
- 株式会社オープントーン,佐藤大輔,伊東直喜,上野啓二,『実装で学ぶフルスタックWeb開発 エンジニアの視野と知識を広げる「一気通貫」型ハンズオン』,翔泳社,2023.
- 4-3 バックエンド(API)とフロントエンド(画面)の連携
- 6-3 バックエンドでモデルを作成する
- 横瀬明仁,『現場で使える Django の教科書《基礎編》』,2018.
- 第6章 モデル (Model)