스타일쉐어 클론 프로젝트- user

cs982607·2020년 11월 25일
0
import json, jwt, requests, re, bcrypt

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

from stylecode.my_settings import JWT_SECRET_KEY, JWT_ALGORITHM
from .models               import User
from .utils                import Login_decorator

class SignUpView(View): #회원가입 뷰
    def post(self, request):
        try:
            data      = json.loads(request.body)
            login_id  = data['login_id']
            password  = data['password']
            email     = data['email']
            gender    = data['gender']
            profile_image_url = data.get('profile_image_url', "")

            id_pattern = '[a-z0-9]'
            email_pattern = '[a-zA-Z0-9_-]+@[a-z]+.[a-z]+'
            password_pattern = '[A-Za-z0-9]'
            				# 정규화패턴 

            if not re.search(id_pattern, login_id) or len(login_id) > 30 or len(login_id)< 3:
                return JsonResponse ({'message':'INVALID_ID'}, status=400)
                							# 아이디 체크 영문소문자,숫자만 가능, 글자수 3자 이상 30자 미만
            if not re.match(email_pattern, email):
                return JsonResponse ({'message:':'INVALID_EMAIL'}, status=400)
                							# 이메일 체크 영문 대,소문자 _- 가능, @ 영문소문자 . 영문소문자 가능
            if not re.search(password_pattern, password) or len(password) > 16 or len(password) < 8:
                return JsonResponse ({'message:':'INVALID_PASSWORD'}, status=400)
									# 패스워드 체크, 영문 대,소문자, 숫자만 가능, 8자 이상 16자 미만
            if User.objects.filter(email=email).exists():
                return JsonResponse ({'message:':'ALREADY_EMAIL'}, status=400)
                							# 이메일 중복 체크
            if User.objects.filter(nickname=data['nickname']).exists():
                return JsonResponse ({'message':'ALREADY_NICKNAME'}, status=400)
									# 닉네임 중복 체크
            hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')			
									# 비밀번호 암호화
            User.objects.create(
                login_id          = login_id,
                password          = hashed_password,
                nickname          = data['nickname'],
                email             = email,
                gender_id         = 1 if data['gender']=='남자' else 2,
                birth_date        = data['birth_date'],
                profile_image_url = profile_image_url
            )
            								# 유저 생성
                        
            return JsonResponse ({'message:':'CREATE_USER'}, status=200)
        except KeyError:
            return JsonResponse({'message:':'KEY_ERROR'}, status=400)

class LogInView(View): # 로그인 뷰
    def post(self, request):
        try:
            data     = json.loads(request.body)
            login_id = data['login_id']
            password = data['password']
            user     = User.objects.get(login_id=login_id)

            if bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')):
                token = jwt.encode({'login_id':login_id}, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM).decode('utf-8')
                							# 로그인 비밀번호 확인 후 로그인 시 토큰 발행

                return JsonResponse({'token':token}, status=200)
                							# 토큰 발행
            return JsonResponse({'message:':'INVALID_PASSWORD'}, status=400)
        except KeyError:
            return JsonResponse({'message:':'INVALID_ID'}, status=400)
        except User.DoesNotExist:
            return JsonResponse({'message:':'USER_DOES_NOT_EXIST'}, status=400)

class ProfileView(View): # 프로필 뷰
    @Login_decorator
    def get(self, request):
        try :
            user = User.objects.get(id = request.user_id)

            user_info = {
                'nickname'          : user.nickname,
                'gender_id'         : user.gender_id,
                'birth_date'        : user.birth_date,
                'country'           : user.country,
                'website_url'       : user.website_url,
                'description'       : user.description,
                'profile_image_url' : user.profile_image_url,
            }
            								# 유저 정보 불러오기
            return JsonResponse ({'user_info:': user_info}, status=400)
        except KeyError:
            return JsonResponse({'message:':'KEY_ERROR'}, status=400)

    @Login_decorator
    def put(self, request):
        try:
            data = json.loads(request.body)
            user = User.objects.get(id = request.user_id)

            if 'country' in data:
                user.country = data['country']
            if 'gender_id' in data:
                user.gender = data['gender_id']
            if 'birth_date' in data:
                user.birth_date = data['birth_date']
            if 'website_url' in data:
                user.website_url = data['website_url']
            if 'description' in data:
                user.description =data['description']
            if 'profile_image_url' in data:
                user.profile_image_url = data['profile_image_url']
            user.save()
									# 유저 정보 수정 시 저장
            return JsonResponse({'message:':'SUCCESS'}, status=200)
        except KeyError:
            return JsonResponse({'message:':'KEY_ERROR'}, status=400)

profile
기록하는 벨로그

0개의 댓글