Assignment #1 | Westagram [Mission 5] 회원가입 비밀번호 암호화 적용

Jayson Hwang·2022년 5월 21일
0

Westagram Project

목록 보기
5/11
post-thumbnail

::: 현재까지 진행 상황 :::

  • 초기 세팅 완료
  • Users 앱 생성 완료
  • models.py의 User 클래스 작성 완료
  • DB에 migrate까지 진행
  • 회원가입 기능 구현 (정규표현식, 예외처리 사용)
  • 로그인 기능 구현 (계정, 패스워드 필터링 적용)

1.. Must Do..

2.. install bcrypt

$ pip install bcrypt

3.. views.py

📌 암호화된 SignUp View 코드

import bcrypt
# bcrypt 불러오기

class SignUpView(View):
    def post(self, request):
        try:
            data = json.loads(request.body)
            
            name     = data['name']
            email    = data['email']
            password = data['password']
            contact  = data['contact']

            email_regex    = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
            password_regex = '^(?=.*[A-Za-z])(?=.*\d)(?=.*[@!%*#?&])[A-Za-z\d@!%*#?&]{8,}$'
            
            if not re.match(email_regex, email):
                return JsonResponse({"message": "INVALID_EMAIL"}, status=400)

            if not re.match(password_regex, password):
                return JsonResponse({"message": "INVALID_PASSWORD"}, status=400)
            
            if User.objects.filter(email = email).exists():
                return JsonResponse({"message": "EMAIL_IS_ALREADY_REGISTERED"}, status=400)

            User.objects.create(
                name     = name,
                email    = email,
                password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8'),
                contact  = contact
            )
            return JsonResponse({"message": "SUCCESS"}, status=201)

        except KeyError: 
            return JsonResponse({"message": "KEY_ERROR"}, status=400)

📌 코드 설명

3-1.. 암호화 적용::

User.objects.create
	name     = name
	email    = email
	password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8'),

"""
# 비밀번호에 salting 후 encode하여 btye타입으로 변경,
# hased_pw = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())

# 최종적으로 DB에는 str형태로 들어가야하기 때문에 decode 해줌
# .decode('utf-8')
"""
profile
"Your goals, Minus your doubts, Equal your reality"

0개의 댓글