SignUp, SignIn

김혜지·2021년 6월 6일

import json
import re
import jwt
import bcrypt

from django.http import JsonResponse
from django.views import View

from .models import User
from my_settings import SECRET_KEY, ALGORITHM

class SignUpView(View):
def post(self, request):

    try:
        data            = json.loads(request.body)
        email_regax     = re.compile("^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$") 
        hashed_password = bcrypt.hashpw(data['password'].encode('utf-8'),bcrypt.gensalt())

        if not re.match(email_regax, data['email']):
            return JsonResponse({"message":"이메일형식이잘못되었습니다."}, status = 400)

        if User.objects.filter(email=data['email']).exists():
            return JsonResponse({'message':'중복되었습니다.'}, status = 400)

        if 'name' in data:
            if User.objects.filter(name=data['name']).exists():
                return JsonResponse({'message':'중복되었습니다.'}, status = 400)

        if len(data['password']) < 8 :
            return JsonResponse({"message":"8자리이상입력하세요."}, status = 400)

        User.objects.create(
        email        = data['email'],
        password     = hashed_password.decode('utf-8'), 
        name         = data.get('name')
        )
        return JsonResponse({'message':'SUCCESS'}, status = 201)

    except KeyError:
        return JsonResponse({'message':'KEY_ERROR'}, status = 400)
    except User.DoesNotExist:
        return JsonResponse({'message':'INVALID_USER'}, status = 400)

class SignInView(View):
def post(self, request):

    try:
        data = json.loads(request.body)
        users = User.objects.get(email = data['email'])

        if bcrypt.checkpw(data['password'].encode('utf-8'),users.password.encode('utf-8')):
            acess_token = jwt.encode({'id':users.id}, SECRET_KEY, ALGORITHM)
            # acess_token = acess_token.decode('utf-8')
            print(users.id)
            print(type(users.id))
            print(acess_token)
            print(type(acess_token))
            return JsonResponse({'token':acess_token}, status = 200)
        else:
            return JsonResponse({'message':'INVALID_PASSWORD'}, status = 401)

    except KeyError:
        return JsonResponse({'message':'KEY_ERROR'}, status = 400)
    except User.DoesNotExist:
        return JsonResponse({'message':'INVALID_USER'}, status = 400)

0개의 댓글