[Django] Westagram 4-6


Mission 4ログイン機能の実装🐳


🌱 ログインビューの定義

class LoginView(View):
    def post(self, request):
        try:
            data     = json.loads(request.body)
            email    = data['email']
            password = data['password']
            
            if not User.objects.filter(email=email).exists():
                return JsonResponse({'message':'INVALID_USER'}, status=401)
                
            if not password == User.objects.get(email=email).password:
                return JsonResponse({'message':'INVALID_USER'}, status=401)
                
            return JsonResponse({'message':'SUCCESS'}, status=200)
            
        except KeyError:
            return JsonResponse({'message':'KEY_ERROR'], status=400)
1電子メールが存在しない場合は無効user、401を返します2パスワードが一致しない場合は無効user、401を返します3key error発生時にkey error,400を返す

🌱 URLConfの定義

from django.urls import path
from users.views import LoginView

urlpatterns = [
		path('/login', LoginView.as_view()), ]

Missionの5回のコストを適用してパスワードの暗号化を入力します🐳


🌱 ユーザービューの変更


暗号化ストレージ操作を追加し、パスワードの漏洩を回避します.
import bcrypt

data = json.loads(request.body)
password = data['password']

hash_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

User.objects.create(
	    name = data['name'],
            email = data['email'],
            password = hashed_password.decode('utf-8'),
            contact = data['contact']
            )
に注意
  • DBに暗号化パスワード(hashed password)が格納されている場合に復号する.( byte -> str )byteタイプのb'識別子自体もstringとみなされ、ログイン機能が実現した場合に正確な比較ができない.
  • Mission 6を適用してJWTにログイン🐳


    🌱 ログインビューの変更

    import jwt
    from my_settings import SECRET_KEY
    
    data = json.loads(request.body)
    password = data['password']
    user = User.objects.get(email=data['email'])
    
    if not bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')
        return JsonResponse({'message':'INVALID_USER'}, status=401)
    
    token = jwt.encode({'id':user.id}, SECRET_KEY, algorithm = 'HS256')
    
    return JsonResponse({'access_token' : token }, status=200)
    に注意
  • bcrypt.checkpw()の比較対象:ユーザが入力したパスワードを符号化する値-暗号化状態データベースに記録されているパスワードの値(str->byte)
  • tokenにはログインユーザのid値が含まれてフロントエンドに送信される.
  • SECRET_KEYセキュリティに関する非公開値であり、直接入力せずmy_settingsファイルからインポートする.