code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,103 @@ +import json +import bcrypt +import jwt + +from django.views import View +from django.http import JsonResponse + +from .models import User, Follow +from my_settings import SECRET_KEY + +class SignupView(View): + def post(self, request): + try: + data = json.loads(request.body) + if User.objects.filter(email=data['email']).exists(): + return JsonResponse({"message": "EMAIL_ERROR"}, status=400) + + if not '@' in data['email'] or not '.' in data['email']: + return JsonResponse({"message":"EMAIL_FAIL"}, status=400) + if len(data['password']) < 8: + return JsonResponse({"message":"PASSWORD_TOO_SHORT"}, status=400) + + byted_password = data['password'].encode('utf-8') + hash_password = bcrypt.hashpw(byted_password, bcrypt.gensalt()).decode() + password = hash_password + user = User.objects.create( + email = data['email'], + password = password + ) + return JsonResponse({"message": "SUCCESS"}, status=200) + except KeyError: + return JsonResponse({"message": "KEY_ERROR"}, status=400) + + +class LoginView(View): + def post(self, request): + try: + data = json.loads(request.body) + try: + user = User.objects.get(email=data['email']) + # user는 객체다 + user_id = user.id + # 객체에 .~하면 바로 내용을 꺼낼 수 있다. + except User.DoesNotExist: + return JsonResponse({"message":"USER_DOES_NOT_EXIST"}, status=400) + + if bcrypt.checkpw(data['password'].encode('utf-8'), user.password.encode('utf-8')): + token = jwt.encode({'user_id' : user_id}, SECRET_KEY, algorithm="HS256") + # 유저 id를 토큰 내용물을 넣는다. 이떄 이미 숫자가 나왔으므로 data로 할 필요 없음 + return JsonResponse({'token' : token, "message":"SUCCESS"}, status=200) + + return JsonResponse({"message":"INVALID_USER"}, status=401) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + +class TokenCheckView(View): + def post(self,request): + data = json.loads(request.body) + + user_token_info = jwt.decode(data['token'], SECRET_KEY, algorithms='HS256') + + if User.objects.filter(email=user_token_info['email']).exists(): + return JsonResponse({"message": "SUCCESS"}, status=200) + return JsonResponse({"message":"INVALID_USER"}, status=401) + +class FollowView(View): + def post(self, request): + data = json.loads(request.body) + following = User.objects.get(email=data['following']) + follower = User.objects.get(email=data['follower']) + if following == follower: + return JsonResponse({"message":"SAME_PERSON!"}) + follow = Follow.objects.create( + following = following, + follower = follower + ) + return JsonResponse({"message": "SUCCESS"}, status=200) + +def TokenCheck(func): + def wrapper(self, request, *args, **kwargs): + # 리퀘스트해서 토큰 까는 애 + # 토큰의 핵심은 공개가 되어도 된다 -> 그래서 예제가 user_id였던 것. + try: + token = request.headers.get('Authorization') + if token: + payload = jwt.decode(token, SECRET_KEY, algorithms="HS256") + user_id = payload['user_id'] + user = User.objects.get(id=user_id) + # user_id 가져온 것을 user라는 변수에 담고 + + request.user = user + # 변수에 담은 것을 뒤에서 부를 request.user에 또 담아준다. + return func(self, request, *args, **kwargs) + # 얘는 return하면서 request를 posting에서 사용할 예정(.user 만 붙이면 이제 자동 완성) + return JsonResponse({"message":"GIVE_ME_TOKEN"}, status=400) + except jwt.InvalidTokenError: + return JsonResponse({"message":"YOUR_TOKEN_ERROR"}, status=400) + + # 지금은 숫자만 확인 상황(id값만 받아서 확인한 상황) + # 추가 : 토큰을 다시 안 갖다준 상황(리퀘스트에 정보를 넣어준다.) ; 리퀘스트의 인스턴스를 만들어준다.(아이디값을 넣어준다.->이걸 꺼내 쓴다.) + + return wrapper \ No newline at end of file
Python
여기서 이렇게 else 로 잡아주시기 보다는 checkpw() 의 값이 Falsy 하다면 401 을 리턴해주시고, 넘어와서 지금 위에 보시는 If 문의 로직을 처리해주신다면 불필요한 else 문이 없어지겠죠?
@@ -0,0 +1,103 @@ +import json +import bcrypt +import jwt + +from django.views import View +from django.http import JsonResponse + +from .models import User, Follow +from my_settings import SECRET_KEY + +class SignupView(View): + def post(self, request): + try: + data = json.loads(request.body) + if User.objects.filter(email=data['email']).exists(): + return JsonResponse({"message": "EMAIL_ERROR"}, status=400) + + if not '@' in data['email'] or not '.' in data['email']: + return JsonResponse({"message":"EMAIL_FAIL"}, status=400) + if len(data['password']) < 8: + return JsonResponse({"message":"PASSWORD_TOO_SHORT"}, status=400) + + byted_password = data['password'].encode('utf-8') + hash_password = bcrypt.hashpw(byted_password, bcrypt.gensalt()).decode() + password = hash_password + user = User.objects.create( + email = data['email'], + password = password + ) + return JsonResponse({"message": "SUCCESS"}, status=200) + except KeyError: + return JsonResponse({"message": "KEY_ERROR"}, status=400) + + +class LoginView(View): + def post(self, request): + try: + data = json.loads(request.body) + try: + user = User.objects.get(email=data['email']) + # user는 객체다 + user_id = user.id + # 객체에 .~하면 바로 내용을 꺼낼 수 있다. + except User.DoesNotExist: + return JsonResponse({"message":"USER_DOES_NOT_EXIST"}, status=400) + + if bcrypt.checkpw(data['password'].encode('utf-8'), user.password.encode('utf-8')): + token = jwt.encode({'user_id' : user_id}, SECRET_KEY, algorithm="HS256") + # 유저 id를 토큰 내용물을 넣는다. 이떄 이미 숫자가 나왔으므로 data로 할 필요 없음 + return JsonResponse({'token' : token, "message":"SUCCESS"}, status=200) + + return JsonResponse({"message":"INVALID_USER"}, status=401) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + +class TokenCheckView(View): + def post(self,request): + data = json.loads(request.body) + + user_token_info = jwt.decode(data['token'], SECRET_KEY, algorithms='HS256') + + if User.objects.filter(email=user_token_info['email']).exists(): + return JsonResponse({"message": "SUCCESS"}, status=200) + return JsonResponse({"message":"INVALID_USER"}, status=401) + +class FollowView(View): + def post(self, request): + data = json.loads(request.body) + following = User.objects.get(email=data['following']) + follower = User.objects.get(email=data['follower']) + if following == follower: + return JsonResponse({"message":"SAME_PERSON!"}) + follow = Follow.objects.create( + following = following, + follower = follower + ) + return JsonResponse({"message": "SUCCESS"}, status=200) + +def TokenCheck(func): + def wrapper(self, request, *args, **kwargs): + # 리퀘스트해서 토큰 까는 애 + # 토큰의 핵심은 공개가 되어도 된다 -> 그래서 예제가 user_id였던 것. + try: + token = request.headers.get('Authorization') + if token: + payload = jwt.decode(token, SECRET_KEY, algorithms="HS256") + user_id = payload['user_id'] + user = User.objects.get(id=user_id) + # user_id 가져온 것을 user라는 변수에 담고 + + request.user = user + # 변수에 담은 것을 뒤에서 부를 request.user에 또 담아준다. + return func(self, request, *args, **kwargs) + # 얘는 return하면서 request를 posting에서 사용할 예정(.user 만 붙이면 이제 자동 완성) + return JsonResponse({"message":"GIVE_ME_TOKEN"}, status=400) + except jwt.InvalidTokenError: + return JsonResponse({"message":"YOUR_TOKEN_ERROR"}, status=400) + + # 지금은 숫자만 확인 상황(id값만 받아서 확인한 상황) + # 추가 : 토큰을 다시 안 갖다준 상황(리퀘스트에 정보를 넣어준다.) ; 리퀘스트의 인스턴스를 만들어준다.(아이디값을 넣어준다.->이걸 꺼내 쓴다.) + + return wrapper \ No newline at end of file
Python
토큰에서 유저정보를 찾아와서 필터하는 기능까지! 👍 👍 👍 다민님 처음에는 이해하는데 어려워하시는 것 같아 걱정을 조금 했었는데, 지금보면 문제 해결능력이 정말 좋으신 것 같아요! 너무 잘하셨습니다ㅎㅎ
@@ -0,0 +1,12 @@ +from django.db import models + +class User(models.Model): + + email = models.EmailField(max_length=50, unique=True) + name = models.CharField(max_length=50, unique=True) + phone = models.CharField(max_length=50, unique=True) + password= models.CharField(max_length=500) + + class Meta: + db_table='users' +
Python
- email 은 가독성을 위해, 그리고 추후 장고 Form 이 제공하는 validator 를 사용할 수도 있을 것을 감안해서 EmailField 로 선언해주세요! - 그리고 email 은 고유값이죠? 이럴때 추가해줄 수 있는 옵션이 있습니다! 찾아서 추가해주세요~
@@ -0,0 +1,12 @@ +from django.db import models + +class User(models.Model): + + email = models.EmailField(max_length=50, unique=True) + name = models.CharField(max_length=50, unique=True) + phone = models.CharField(max_length=50, unique=True) + password= models.CharField(max_length=500) + + class Meta: + db_table='users' +
Python
보통 데이터베이스 컬럼명은 줄여쓰지않고 최대한 명확하게 풀어서 선언해줍니다. 여기는 password 로 풀어주세요~ 그리고 이제 비밀번호 암호화 과정을 진행하는만큼 최대 글자수를 조금 더 넉넉하게 잡아주시는게 좋습니다!
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
- exists 메소드 너무 잘 활용하셨네요!! 👍 - 여기서 exists 의 결과를 따로 변수에 저장해줄것 없이 아래 if 문에 바로 적용해주신다면 불필요한 변수 선언을 없앨 수 있겠죠?!
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
or, not, in 활용 너무 좋습니다 호열님!!! 그런데 email 을 list 로 형변환해주신 이유가 있을까요?
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
위에 리뷰 내용 반영해주시면 이 부분에 수정사항이 생기겠죠!?
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
`or` 과 `is` 중에 어떤게 우선순위일까요? 조건문에서 operator precedence 에 따라 조건이 완전히 바뀔 수 있기 때문에 잘 파악하고 사용하시는게 좋습니다!
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
이 부분들에서는 파이썬의 exception 이 발생할 수 있습니다. Exception handling 에 대해서 repl.it 에서 보신적이 있으신데요! 실제로 view 에서 정말정말 중요한 역할을 하는 만큼 꼭 추가되어야 하는 로직입니다. 이 코드들에서 어떤 exception 이 발생할 수 있을지 확인해보시고 핸들링 로직 추가해주세요!
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
이제 bcrypt 를 활용하여 비밀번호 암호화 로직 추가해서 저장해주세요!
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
CREATED 를 의미하는 201 사용 너무 잘하셨습니다! 😉
@@ -0,0 +1,12 @@ +from django.db import models + +class User(models.Model): + + email = models.EmailField(max_length=50, unique=True) + name = models.CharField(max_length=50, unique=True) + phone = models.CharField(max_length=50, unique=True) + password= models.CharField(max_length=500) + + class Meta: + db_table='users' +
Python
휴대폰 번호도 고유값이니 위처럼 고유값을 뜻하는 옵션을 추가해주셔야 합니다!
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
string / list 에 대한 이해가 부족했습니다. - [x] Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one: - [x] if '.' not in email or '@' not in email:
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
불필요한 주석 제외하고 올려주세요.
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
else 불필요
@@ -0,0 +1,76 @@ +import json,bcrypt,jwt +from json.decoder import JSONDecodeError + +from django.db.models import Q +from django.views import View +from django.http import JsonResponse + +from .models import User +from my_settings import SECRET_KEY, ALGORITHM + + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + name = data['name'] + email = data['email'] + phone = data['phone'] + password= data['password'] + + if '.' not in email or '@' not in email: + return JsonResponse({'message':'error_email_form'}, status=401) + + if len(password)<8: + return JsonResponse({'message':'error_password_form'}, status=401) + + if User.objects.filter(Q(name=name) | Q(email=email) | Q(phone=phone)).exists: + return JsonResponse({'message':'id_exist'}, status = 401) + + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + decoded_password= hashed_password.decode('utf-8') + + User.objects.create(email=email, name=name, phone=phone, password=decoded_password) + return JsonResponse({'message':'success_signup'}, status = 201) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + id = data['id'] + password= data['password'] + user = User.objects.get(Q(name=id) | Q(email=id) | Q(phone=id)) + + if user is not id: + return JsonResponse({'message':'error_id_matching'}, status=401) + + if user is id: + decoded_password = user.password + encoded_password = password.encode('utf-8') + bcrypt.checkpw(encoded_password, decoded_password.encode('utf-8')) + token = jwt.encode({'user':user.id}, SECRET_KEY, ALGORITHM) + return JsonResponse({'message':'success_signin', 'access_token':token}, status=201) + + return JsonResponse({'message':'error_password_matching'}, status = 401) + + except User.MultipleObjectsReturned: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except User.DoesNotExist: + return JsonResponse({'message': 'KEY_ERROR'}, status=401) + + except KeyError: + return JsonResponse({'message': 'KEY_ERROR'}, status=400) + + except JSONDecodeError: + return JsonResponse({'message': 'JSONDecodeError'}, status=400) + + +
Python
성공 케이스에서 쓸 로직이기 때문에 아래로 위치시켜주세요.
@@ -0,0 +1,145 @@ +""" +Django settings for westagram project. + +Generated by 'django-admin startproject' using Django 3.1.7. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.1/ref/settings/ +""" + +from pathlib import Path +from my_settings import SECRET_KEY, DATABASES + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = SECRET_KEY + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['*'] + + +# Application definition + +INSTALLED_APPS = [ +# 'django.contrib.admin', +# 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'corsheaders', + 'user', + 'posting' +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', +# 'django.middleware.csrf.CsrfViewMiddleware', +# 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'corsheaders.middleware.CorsMiddleware', +] + +ROOT_URLCONF = 'westagram.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'westagram.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.1/ref/settings/#databases + +DATABASES = DATABASES + + +# Password validation +# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/3.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.1/howto/static-files/ + +STATIC_URL = '/static/' + +##CORS +CORS_ORIGIN_ALLOW_ALL=True +CORS_ALLOW_CREDENTIALS = True + +CORS_ALLOW_METHODS = ( + 'DELETE', + 'GET', + 'OPTIONS', + 'PATCH', + 'POST', + 'PUT', +) + +CORS_ALLOW_HEADERS = ( + 'accept', + 'accept-encoding', + 'authorization', + 'content-type', + 'dnt', + 'origin', + 'user-agent', + 'x-csrftoken', + 'x-requested-with', +)
Python
완벽합니다 국현님! 💯
@@ -0,0 +1,145 @@ +""" +Django settings for westagram project. + +Generated by 'django-admin startproject' using Django 3.1.7. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.1/ref/settings/ +""" + +from pathlib import Path +from my_settings import SECRET_KEY, DATABASES + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = SECRET_KEY + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['*'] + + +# Application definition + +INSTALLED_APPS = [ +# 'django.contrib.admin', +# 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'corsheaders', + 'user', + 'posting' +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', +# 'django.middleware.csrf.CsrfViewMiddleware', +# 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'corsheaders.middleware.CorsMiddleware', +] + +ROOT_URLCONF = 'westagram.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'westagram.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.1/ref/settings/#databases + +DATABASES = DATABASES + + +# Password validation +# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/3.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.1/howto/static-files/ + +STATIC_URL = '/static/' + +##CORS +CORS_ORIGIN_ALLOW_ALL=True +CORS_ALLOW_CREDENTIALS = True + +CORS_ALLOW_METHODS = ( + 'DELETE', + 'GET', + 'OPTIONS', + 'PATCH', + 'POST', + 'PUT', +) + +CORS_ALLOW_HEADERS = ( + 'accept', + 'accept-encoding', + 'authorization', + 'content-type', + 'dnt', + 'origin', + 'user-agent', + 'x-csrftoken', + 'x-requested-with', +)
Python
넵넵 확인 감사드립니다 승현님 ㅎㅎ 😊😊 미션2 진행하겠습니다~~~!!👨‍💻
@@ -0,0 +1,12 @@ +from django.db import models + +class User(models.Model): + email = models.EmailField(max_length=50, unique=True) + phone = models.CharField(max_length=11, null=True, unique=True) + full_name = models.CharField(max_length=40, null=True) + user_name = models.CharField(max_length=20, null=True, unique=True) + password = models.CharField(max_length=70) + date_of_birth = models.DateField(null=True) + + class Meta: + db_table = 'users'
Python
불필요한 주석 없애주세요!
@@ -0,0 +1,12 @@ +from django.db import models + +class User(models.Model): + email = models.EmailField(max_length=50, unique=True) + phone = models.CharField(max_length=11, null=True, unique=True) + full_name = models.CharField(max_length=40, null=True) + user_name = models.CharField(max_length=20, null=True, unique=True) + password = models.CharField(max_length=70) + date_of_birth = models.DateField(null=True) + + class Meta: + db_table = 'users'
Python
작성하신 여러가지 필드들 중 중복을 허용하면 안되는 필드들이 보이는데 그럴때 사용할 수 있는 옵션이 있습니다! 찾아서 추가해주세요 😉
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
깔끔합니다!! 💯 💯 💯
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
필수필드, `NULL` 허용필드에 따른 접근 방식 다르게 적용 잘하셨습니다!! 👍👍👍 가독성을 위해 조금 위치를 변경할 수 있겠네요! 아래와 같이요ㅎㅎ ```suggestion email = data['email'] password = data['password'] phone = data.get('phone', None) full_name = data.get('full_name', None) user_name = data.get('user_name', None) date_of_birth = data.get('date_of_birth', None) ```
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
입력받은 폰번호에 `-` 가 포함되어 들어올 시 데이터베이스에 넣고싶은 형식에 맞춰주시는 로직 좋습니다! 앞으로 프론트엔드분들과 협업을 하면서 경험하시겠지만, 이런 부분은 꼭 프론트/백 간의 상의가 필요합니다. 이 점 인지해주시고 다음 주 프/백 통신 들어가시면 도움이 되실거에요! ㅎㅎ
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
정규표현식으로 email 과 password validate 해주시는 로직인데 조금 자잘하게 나누어서 비교하시려다보니 조금 복잡해보이네요! 차라리 이메일 형식에 맞는 정규표현식을 통째로 가져와 저장해두고 `re.match()` 를 활용하여 한번에 확인할 수 있습니다. `password` 도 마찬가지구요! 그렇게 변경해주시면 조금 더 깔끔한 조건문을 만들 수 있습니다 😉
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
이미 존재하는 정보인지 확인하는 로직을 작성해주셨는데 작성해주신 로직을 흐름대로 글로 정리해보겠습니다. 1. 입력받은 `email` 값으로 유저 테이블에 filter 쿼리를 날려 반환받은 QuerySet 리스트에 객체가 존재하지 않는다면 `phone_number` 과 `user_name` 으로 filter 쿼리를 날려 추가 확인을 한다. 2. 존재한다면 `400` 을 리턴해준다. 하지만 현재 `SignUp` View 에서는 `email` 을 필수값으로 받아야하기 때문에 사실상 `email` 존재 유무만 확인해도 등록된 유저인지 아닌지는 알 수가 있습니다. `phone_number` 와 `user_name` 은 부가정보들이니까요! 그런데 `email` 로 존재유무는 확인하더라도 `phone_number` 와 `user_name` 의 중복 가능 여부에 따라 추가 로직은 달라질 수 있습니다. 제가 모델쪽에 남겨드린 리뷰를 확인해보신 후 생각하신 구조에 따라 수정해주신 다음 다시한번 이쪽 부분을 확인해보세요!
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
깔끔합니다~ 💯
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
구분을 위해 위아래로 한줄씩 추가해주시면 가독성이 더 좋아지겠네요! 😎
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
이런식으로 exception 을 처리하시게 되면 어떤 exception 이 무엇때문에 `raise` 되었는지 확인하기가 어렵습니다. 그래서 exception 핸들러 추가해주실때는 위에서 `KeyError` 처리해주신것과 같이 명확하게 지정하여 처리해주셔야합니다. 하지만 지금 단계에서 어떤 exception 이 발생할 수 있는지 모르는게 당연하기 때문에 이럴때는 그냥 여러가지 방법으로 호출해보면서 경험하여 추가해주시다보면 나중에는 메소드 하나를 추가할때 관련한 exception 을 처리해주는 로직을 바로 함께 작성할 수 있게 되실거에요! 😁
@@ -0,0 +1,12 @@ +from django.db import models + +class User(models.Model): + email = models.EmailField(max_length=50, unique=True) + phone = models.CharField(max_length=11, null=True, unique=True) + full_name = models.CharField(max_length=40, null=True) + user_name = models.CharField(max_length=20, null=True, unique=True) + password = models.CharField(max_length=70) + date_of_birth = models.DateField(null=True) + + class Meta: + db_table = 'users'
Python
네넵!!
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
아하 네넵!! 궁금한 점 해결 되었습니다 ㅎㅎ!!
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
승현님, 말씀하신대로, 이메일 주소와 비밀번호 정규식 검사에 필요한 값을 REGEX_EMAIL, REGEX_PASSWORD에다가 저장하여 활용하였습니다..! 보다 코드가 간결해져서 아주 좋네요 ㅎㅎㅎ
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
승현님, 아까 해주신 말씀 듣고 User 클래스에 특정 컬럼은 고유한 값을 가지도록 unique 옵션을 설정하였습니다..! 그리고 말씀해주신 q 클래스도 공부하고 다음 소스에도 적용해보도록 하겠습니다!!
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
Truthy, Falsy values 에 대해 알아보시고 해당 조건문들을 어떻게 더 깔끔하게 정리할 수 있을지 고민해보시고 적용해주세요!
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
이제 bcrypt 로 비밀번호를 암호화하여 저장하는 로직을 추가해주세요!
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
여기서도 발생할 수 있는 exception 이 존재합니다! exception handling 로직에 추가해주세요!!
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
`=` 기준 간격 정렬해주세요 국현님!
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
- `|` 사이 간격도 통일해주세요~ - 이 부분 로직이 이해가 잘 안되는데 전부 user_id 를 대입하여 확인하고 싶은게 맞으신가요?!
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
넵넵!! 수정해보겠습니다~~
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
넵 승현님! 저는 사용자가 로그인할 때 이메일, 휴대폰, 유저네임 이 세개중에 하나로 로그인할꺼라고 생각을 해서 사용자가 입력한 값을 아예 user_id로 값을 받으려 했습니다..! 그래서 이 user_id값을 가지고 하나라도 이메일, 휴대폰, 유저네임과 같은게 있으면 유효한 아이디값이라고 생각하였습니다..!
@@ -0,0 +1,87 @@ +import re, json, bcrypt + +from django.views import View +from django.http import JsonResponse, request +from django.db.models.query_utils import Q +from json.decoder import JSONDecodeError + +from user.utils import LoginCheck +from user.models import User + +class SignUpView(View): + def post(self, request): + try: + data = json.loads(request.body) + + email = data['email'] + password = data['password'] + phone = data.get('phone', None) + full_name = data.get('full_name', None) + user_name = data.get('user_name', None) + date_of_birth = data.get('date_of_birth', None) + + if phone: + phone = phone.replace('-','') + + REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + REGEX_PASSWORD = '\S{8,20}' + + if not re.match(REGEX_EMAIL,email): + return JsonResponse({'message':'EMAIL VALIDATION ERROR'}, status=400) + if not re.match(REGEX_PASSWORD,password): + return JsonResponse({'message':'PASSWORD VALIDATION ERROR'}, status=400) + + if not User.objects.filter(email=email): + if phone and User.objects.filter(phone=phone): + return JsonResponse({'message':'PHONE ALREADY EXISTS'}, status=400) + elif user_name and User.objects.filter(user_name=user_name): + return JsonResponse({'message':'USER_NAME ALREADY EXISTS'}, status=400) + else: + return JsonResponse({'message':'EMAIL ALREADY EXISTS'}, status=400) + + hashed_password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode() + + User.objects.create( + email = email, + phone = phone, + full_name = full_name, + user_name = user_name, + password = hashed_password, + date_of_birth = date_of_birth, + ) + + return JsonResponse({'message':'SUCCESS'}, status=200) + + except KeyError: + return JsonResponse({'message':'KEY ERROR'}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) + + +class SignInView(View): + def post(self, request): + try: + data = json.loads(request.body) + + user_id = data['user_id'] + password = data['password'] + + user= User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)) + + if user: + stored_password = User.objects.get(Q(user_name=user_id)|Q(email=user_id)|Q(phone=user_id)).password + if not bcrypt.checkpw(password.encode('UTF-8'), stored_password.encode('UTF-8')): + return JsonResponse({"message":"INVALID_PASSWORD"}, status=401) + else: + return JsonResponse({"message":"INVALID_USER"}, status=401) + + return JsonResponse({"message":"SUCCESS", "Authorization":LoginCheck(user.id)}, status=200) + + except KeyError: + return JsonResponse({"message":"KEY_ERROR"}, status=400) + except JSONDecodeError: + return JsonResponse({'message':'JSON DECODE ERROR'}, status=400) + except Exception as e: + print(e) \ No newline at end of file
Python
승현님 혹시 json 관련 exception 이 JSONDecodeError 인것일까요..?
@@ -1,26 +1,39 @@ package nextstep.app; +import jakarta.servlet.http.HttpServletRequest; +import java.util.ArrayList; import nextstep.app.domain.Member; import nextstep.app.domain.MemberRepository; import nextstep.security.authentication.AuthenticationException; import nextstep.security.authentication.BasicAuthenticationFilter; import nextstep.security.authentication.UsernamePasswordAuthenticationFilter; -import nextstep.security.authorization.CheckAuthenticationFilter; -import nextstep.security.authorization.SecuredAspect; +import nextstep.security.authorization.AuthorizationFilter; +import nextstep.security.authorization.AuthorizationManager; import nextstep.security.authorization.SecuredMethodInterceptor; +import nextstep.security.authorization.method.SecuredAuthorizationManager; +import nextstep.security.authorization.web.AuthenticatedAuthorizationManager; +import nextstep.security.authorization.web.AuthorityAuthorizationManager; +import nextstep.security.authorization.web.DenyAllAuthorizationManager; +import nextstep.security.authorization.web.RequestMatcherDelegatingAuthorizationManager; import nextstep.security.config.DefaultSecurityFilterChain; import nextstep.security.config.DelegatingFilterProxy; import nextstep.security.config.FilterChainProxy; import nextstep.security.config.SecurityFilterChain; import nextstep.security.context.SecurityContextHolderFilter; import nextstep.security.userdetails.UserDetails; import nextstep.security.userdetails.UserDetailsService; +import nextstep.security.util.AnyRequestMatcher; +import nextstep.security.util.MvcRequestMatcher; +import nextstep.security.util.RequestMatcherEntry; +import nextstep.security.authorization.web.PermitAllAuthorizationManager; +import org.aopalliance.intercept.MethodInvocation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import java.util.List; import java.util.Set; +import org.springframework.http.HttpMethod; @EnableAspectJAutoProxy @Configuration @@ -44,12 +57,26 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte @Bean public SecuredMethodInterceptor securedMethodInterceptor() { - return new SecuredMethodInterceptor(); + return new SecuredMethodInterceptor(securedAuthorizationManager()); + } + + @Bean + public AuthorizationManager<MethodInvocation> securedAuthorizationManager() { + return new SecuredAuthorizationManager(); + } + + @Bean + public AuthorizationManager<HttpServletRequest> requestAuthorizationManager() { + List<RequestMatcherEntry<AuthorizationManager>> mappings = new ArrayList<>(); + mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members"), + new AuthorityAuthorizationManager<HttpServletRequest>(Set.of("ADMIN")))); + mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members/me"), + new AuthenticatedAuthorizationManager())); + mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/search"), + new PermitAllAuthorizationManager())); + mappings.add(new RequestMatcherEntry<>(AnyRequestMatcher.INSTANCE, new DenyAllAuthorizationManager())); + return new RequestMatcherDelegatingAuthorizationManager(mappings); } -// @Bean -// public SecuredAspect securedAspect() { -// return new SecuredAspect(); -// } @Bean public SecurityFilterChain securityFilterChain() { @@ -58,7 +85,7 @@ public SecurityFilterChain securityFilterChain() { new SecurityContextHolderFilter(), new UsernamePasswordAuthenticationFilter(userDetailsService()), new BasicAuthenticationFilter(userDetailsService()), - new CheckAuthenticationFilter() + new AuthorizationFilter(requestAuthorizationManager()) ) ); }
Java
잘 추가해주셨네요 👍
@@ -2,7 +2,10 @@ import nextstep.app.domain.Member; import nextstep.app.domain.MemberRepository; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationException; import nextstep.security.authorization.Secured; +import nextstep.security.context.SecurityContextHolder; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -30,4 +33,15 @@ public ResponseEntity<List<Member>> search() { List<Member> members = memberRepository.findAll(); return ResponseEntity.ok(members); } + + @GetMapping("/members/me") + public ResponseEntity<Member> me() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + + String email = authentication.getPrincipal().toString(); + Member member = memberRepository.findByEmail(email) + .orElseThrow(RuntimeException::new); + + return ResponseEntity.ok(member); + } }
Java
이미 Filter에서 처리하고 있는데 불필요한 로직이 아닐까요?
@@ -0,0 +1,20 @@ +package nextstep.security.util; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.http.HttpMethod; + +public class MvcRequestMatcher implements RequestMatcher { + + private final HttpMethod method; + private final String pattern; + + public MvcRequestMatcher(HttpMethod method, String pattern) { + this.method = method; + this.pattern = pattern; + } + + @Override + public boolean matches(HttpServletRequest request) { + return this.method.equals(HttpMethod.valueOf(request.getMethod())) && pattern.equals(request.getRequestURI()); + } +}
Java
```suggestion return this.method.equals(HttpMethod.valueOf(request.getMethod())) && pattern.equals(request.getRequestURI()); ``` null-safe 관점에서는 파라미터로 들어오는 `request.getRequestURI()`는 null일 수 있기 때문에 별도로 null 체크를 하지 않는 이상 위와 같이 표현하는 것이 npe가 발생하지 않는 안전한 코드를 만들 수 있습니다.
@@ -0,0 +1,14 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.web.AuthorizationResult; + +@FunctionalInterface +public interface AuthorizationManager<T> { + @Deprecated + AuthorizationDecision check(Authentication authentication, T object); + + default AuthorizationResult authorize(Authentication authentication, T object) { + return check(authentication, object); + } +}
Java
현재 spring security를 확인해보시면 `check`는 deprecated되었는데요. `AuthorizationDecision`이라는 클래스는 구현해주신 것처럼 구현체로 되어있고, 보통의 프레임워크들은 규모가 커질수록 만들어둔 구현체들을 추상화하는 형태로 개선해나갑니다. `check`가 deprecated됨에 따라 해당 기능이 막힌 것은 아니고 이를 추상화한 `AuthorizationResult`를 반환하는 메소드 사용을 권장하고 있으니 참고해주시면 좋을 것 같아요 :) https://github.com/franticticktick/spring-security/blob/main/core/src/main/java/org/springframework/security/authorization/AuthorizationManager.java https://github.com/spring-projects/spring-security/pull/14712 https://github.com/spring-projects/spring-security/pull/14846
@@ -0,0 +1,14 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.web.AuthorizationResult; + +@FunctionalInterface +public interface AuthorizationManager<T> { + @Deprecated + AuthorizationDecision check(Authentication authentication, T object); + + default AuthorizationResult authorize(Authentication authentication, T object) { + return check(authentication, object); + } +}
Java
준형님이 생각하시기에 선택사항으로 주어진 `verfiy`는 `check`와 비교하여 어떤 상황에서 사용하면 좋을 것 같으신가요?
@@ -0,0 +1,22 @@ +package nextstep.security.authorization; + +import nextstep.security.authorization.web.AuthorizationResult; + +public class AuthorizationDecision implements AuthorizationResult { + public static final AuthorizationDecision ALLOW = new AuthorizationDecision(true); + public static final AuthorizationDecision DENY = new AuthorizationDecision(false); + + private final boolean granted; + + public AuthorizationDecision(boolean granted) { + this.granted = granted; + } + + public boolean isGranted() { + return granted; + } + + public static AuthorizationDecision of(boolean granted) { + return granted ? ALLOW : DENY; + } +}
Java
true 혹은 false만 가지는 `AuthorizationDecision`이 자주 사용되는데 사용될때마다 인스턴스화하기보다는 불변임을 활용하여 미리 만들어준 상수를 사용하도록 유도할 수 있을 것 같네요.
@@ -0,0 +1,38 @@ +package nextstep.security.authorization.web; + +import java.util.Collection; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationException; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.AuthorizationManager; + +public class AuthorityAuthorizationManager<T> implements AuthorizationManager<T> { + + private final Collection<String> authorities; + + public AuthorityAuthorizationManager(Collection<String> authorities) { + this.authorities = authorities; + } + + + @Override + public AuthorizationDecision check(Authentication authentication, T object) { + if (authentication == null) { + throw new AuthenticationException(); + } + + boolean hasAuthority = isAuthorized(authentication, authorities); + + return AuthorizationDecision.of(hasAuthority); + } + + + private boolean isAuthorized(Authentication authentication, Collection<String> authorities) { + for (String authority : authentication.getAuthorities()) { + if (authorities.contains(authority)) { + return true; + } + } + return false; + } +}
Java
실제 spring security에서는 성능의 문제로 인해 stream 사용을 제한하고 있습니다. https://github.com/spring-projects/spring-security/issues/7154
@@ -0,0 +1,28 @@ +package nextstep.security.authorization.web; + +import jakarta.servlet.http.HttpServletRequest; +import java.util.List; +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.AuthorizationManager; +import nextstep.security.util.RequestMatcher; +import nextstep.security.util.RequestMatcherEntry; + +public class RequestMatcherDelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> { + + private final List<RequestMatcherEntry<AuthorizationManager>> mappings; + + public RequestMatcherDelegatingAuthorizationManager(List<RequestMatcherEntry<AuthorizationManager>> mappings) { + this.mappings = mappings; + } + + @Override + public AuthorizationDecision check(Authentication authentication, HttpServletRequest request) { + for (RequestMatcherEntry<AuthorizationManager> mapping : mappings) { + if (mapping.getRequestMatcher().matches(request)) { + return mapping.getEntry().check(authentication, request); + } + } + return AuthorizationDecision.DENY; + } +}
Java
getter로 호출하여 일치 여부를 확인하는 것보다는 `mapping`에서 처리하도록 수정하면 책임이 명확하게 넘어갈 수 있겠네요 :)
@@ -0,0 +1,43 @@ +package nextstep.security.authorization.method; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Collections; +import java.util.Set; +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.AuthorizationManager; +import nextstep.security.authorization.Secured; +import nextstep.security.authorization.web.AuthorityAuthorizationManager; +import org.aopalliance.intercept.MethodInvocation; + +public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { + + private AuthorityAuthorizationManager<Collection<String>> authorityAuthorizationManager; + + public void setAuthorityAuthorizationManager(Collection<String> authorities) { + authorityAuthorizationManager = new AuthorityAuthorizationManager<>(authorities); + } + + @Override + public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) { + Collection<String> authorities = getAuthorities(invocation); + + if (authorities.isEmpty()) { + return null; + } + setAuthorityAuthorizationManager(authorities); + return authorities.isEmpty() ? null : authorityAuthorizationManager.check(authentication, authorities); + } + + private Collection<String> getAuthorities(MethodInvocation invocation) { + Method method = invocation.getMethod(); + + if (!method.isAnnotationPresent(Secured.class)) { + return Collections.emptySet(); + } + + Secured secured = method.getAnnotation(Secured.class); + return Set.of(secured.value()); + } +}
Java
`AuthorityAuthorizationManager`의 로직과 함께보면 ```java boolean hasAuthority = authentication.getAuthorities().stream() .anyMatch(authorities::contains); return new AuthorizationDecision(hasAuthority); ``` 부분이 동일한 것을 확인해볼 수 있어요. 각 `AuthorizatinManager`는 단일에서 각각 본인의 것을 모두 구성하는 것이 아닌 서로 유기적으로 결합되어 사용하기도 하는데요. 즉, `SecuredAuthorizationManager`는 `@Secured`에 있는 정보를 가지고 처리하며, authority에 대한 권한체크는 `AuthorizatinManager`가 온전히 담당하는거죠. https://github.com/spring-projects/spring-security/blob/main/core/src/main/java/org/springframework/security/authorization/method/SecuredAuthorizationManager.java 실제로는 권한체계가 다양하기 때문에 `AuthoritiesAuthorizationManager`를 사용하고 있기는 하지만 관련하여 참고하시면 이해에 도움이 되실 것 같아요.
@@ -0,0 +1,18 @@ +package nextstep.security.fixture; + +import java.util.Base64; +import java.util.Set; +import nextstep.app.domain.Member; + +public class MemberTestFixture { + public static final Member TEST_ADMIN_MEMBER = new Member("a@a.com", "password", "a", "", Set.of("ADMIN")); + public static final Member TEST_USER_MEMBER = new Member("b@b.com", "password", "b", "", Set.of("USER")); + + public static String createAdminToken(){ + return Base64.getEncoder().encodeToString((TEST_ADMIN_MEMBER.getEmail() + ":" + TEST_ADMIN_MEMBER.getPassword()).getBytes()); + } + + public static String createMemberToken(){ + return Base64.getEncoder().encodeToString((TEST_USER_MEMBER.getEmail() + ":" + TEST_USER_MEMBER.getPassword()).getBytes()); + } +}
Java
(반영하지 않으셔도 됩니다.) 개인적으로는 enum에서 지원되는 메소드들을 활용하는 경우도 많아 특정 도메인의 fixture는 enum 으로 생성하는 편입니다 😄
@@ -2,7 +2,10 @@ import nextstep.app.domain.Member; import nextstep.app.domain.MemberRepository; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationException; import nextstep.security.authorization.Secured; +import nextstep.security.context.SecurityContextHolder; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -30,4 +33,15 @@ public ResponseEntity<List<Member>> search() { List<Member> members = memberRepository.findAll(); return ResponseEntity.ok(members); } + + @GetMapping("/members/me") + public ResponseEntity<Member> me() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + + String email = authentication.getPrincipal().toString(); + Member member = memberRepository.findByEmail(email) + .orElseThrow(RuntimeException::new); + + return ResponseEntity.ok(member); + } }
Java
앗 해당 app패키지에 컨트롤러는 강의실에서 실습이후 체리픽 해온것이라 열어볼 생각을 못했네요. 수정해두겠습니다!
@@ -0,0 +1,20 @@ +package nextstep.security.util; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.http.HttpMethod; + +public class MvcRequestMatcher implements RequestMatcher { + + private final HttpMethod method; + private final String pattern; + + public MvcRequestMatcher(HttpMethod method, String pattern) { + this.method = method; + this.pattern = pattern; + } + + @Override + public boolean matches(HttpServletRequest request) { + return this.method.equals(HttpMethod.valueOf(request.getMethod())) && pattern.equals(request.getRequestURI()); + } +}
Java
간과하고 있었네요. 수정해두겠습니다! 👍
@@ -0,0 +1,14 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.web.AuthorizationResult; + +@FunctionalInterface +public interface AuthorizationManager<T> { + @Deprecated + AuthorizationDecision check(Authentication authentication, T object); + + default AuthorizationResult authorize(Authentication authentication, T object) { + return check(authentication, object); + } +}
Java
오.. 불과 4달전에 업데이트된 기능이군요! 피드백 주신 대로 반영해보면서 어떤 식으로 오픈소스가 개선되어 나가는지 체험 해 볼 수 있었네요 감사합니다.
@@ -0,0 +1,22 @@ +package nextstep.security.authorization; + +import nextstep.security.authorization.web.AuthorizationResult; + +public class AuthorizationDecision implements AuthorizationResult { + public static final AuthorizationDecision ALLOW = new AuthorizationDecision(true); + public static final AuthorizationDecision DENY = new AuthorizationDecision(false); + + private final boolean granted; + + public AuthorizationDecision(boolean granted) { + this.granted = granted; + } + + public boolean isGranted() { + return granted; + } + + public static AuthorizationDecision of(boolean granted) { + return granted ? ALLOW : DENY; + } +}
Java
현 상황에서 메모리 효율성을 더 높일 수 있겠네요!
@@ -0,0 +1,38 @@ +package nextstep.security.authorization.web; + +import java.util.Collection; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationException; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.AuthorizationManager; + +public class AuthorityAuthorizationManager<T> implements AuthorizationManager<T> { + + private final Collection<String> authorities; + + public AuthorityAuthorizationManager(Collection<String> authorities) { + this.authorities = authorities; + } + + + @Override + public AuthorizationDecision check(Authentication authentication, T object) { + if (authentication == null) { + throw new AuthenticationException(); + } + + boolean hasAuthority = isAuthorized(authentication, authorities); + + return AuthorizationDecision.of(hasAuthority); + } + + + private boolean isAuthorized(Authentication authentication, Collection<String> authorities) { + for (String authority : authentication.getAuthorities()) { + if (authorities.contains(authority)) { + return true; + } + } + return false; + } +}
Java
가독성 때문에 stream을 선호하는 편인데, spring security같은 라이브러리는 성능이 중요하다보니 그렇게 된거군요.. 구현체 코드 보면서 가독성이 생각만큼은 아닌것 같았는데, 그 위화감이 여기서 기인한 것 같습니다.
@@ -0,0 +1,28 @@ +package nextstep.security.authorization.web; + +import jakarta.servlet.http.HttpServletRequest; +import java.util.List; +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.AuthorizationManager; +import nextstep.security.util.RequestMatcher; +import nextstep.security.util.RequestMatcherEntry; + +public class RequestMatcherDelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> { + + private final List<RequestMatcherEntry<AuthorizationManager>> mappings; + + public RequestMatcherDelegatingAuthorizationManager(List<RequestMatcherEntry<AuthorizationManager>> mappings) { + this.mappings = mappings; + } + + @Override + public AuthorizationDecision check(Authentication authentication, HttpServletRequest request) { + for (RequestMatcherEntry<AuthorizationManager> mapping : mappings) { + if (mapping.getRequestMatcher().matches(request)) { + return mapping.getEntry().check(authentication, request); + } + } + return AuthorizationDecision.DENY; + } +}
Java
음.. 제 생각으로는 `mapping`인 `RequestMatcherEntry`는 `RequestMatcher`랑 `AuthorizationManager`를 단순히 묶어주는 역할을 수행한다고 생각해서, 해당 객체에 `matches()`의 로직까지 있으면 오히려 책임이 과해지고, 원래 RequestMatcher의 역할이 흐려질것 같아 getter로 호출해서 일치 여부를 확인했습니다. 제가 제대로 이해한거라면 진영님 생각이 궁금합니다!
@@ -0,0 +1,18 @@ +package nextstep.security.fixture; + +import java.util.Base64; +import java.util.Set; +import nextstep.app.domain.Member; + +public class MemberTestFixture { + public static final Member TEST_ADMIN_MEMBER = new Member("a@a.com", "password", "a", "", Set.of("ADMIN")); + public static final Member TEST_USER_MEMBER = new Member("b@b.com", "password", "b", "", Set.of("USER")); + + public static String createAdminToken(){ + return Base64.getEncoder().encodeToString((TEST_ADMIN_MEMBER.getEmail() + ":" + TEST_ADMIN_MEMBER.getPassword()).getBytes()); + } + + public static String createMemberToken(){ + return Base64.getEncoder().encodeToString((TEST_USER_MEMBER.getEmail() + ":" + TEST_USER_MEMBER.getPassword()).getBytes()); + } +}
Java
3단계 수행하면서 변경해 보겠습니다! 😄
@@ -0,0 +1,43 @@ +package nextstep.security.authorization.method; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Collections; +import java.util.Set; +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.AuthorizationManager; +import nextstep.security.authorization.Secured; +import nextstep.security.authorization.web.AuthorityAuthorizationManager; +import org.aopalliance.intercept.MethodInvocation; + +public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { + + private AuthorityAuthorizationManager<Collection<String>> authorityAuthorizationManager; + + public void setAuthorityAuthorizationManager(Collection<String> authorities) { + authorityAuthorizationManager = new AuthorityAuthorizationManager<>(authorities); + } + + @Override + public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) { + Collection<String> authorities = getAuthorities(invocation); + + if (authorities.isEmpty()) { + return null; + } + setAuthorityAuthorizationManager(authorities); + return authorities.isEmpty() ? null : authorityAuthorizationManager.check(authentication, authorities); + } + + private Collection<String> getAuthorities(MethodInvocation invocation) { + Method method = invocation.getMethod(); + + if (!method.isAnnotationPresent(Secured.class)) { + return Collections.emptySet(); + } + + Secured secured = method.getAnnotation(Secured.class); + return Set.of(secured.value()); + } +}
Java
[83a4efd](https://github.com/next-step/spring-security-authorization/pull/15/commits/83a4efd95662b7e9d2590f72ee5a56173a16477d) 으로 반영해보았습니다! 각자의 Manager가 단일 책임이 아닌 결합해서 사용하기도 하는군요! 저도 작업하면서 같은 로직이 들어간다고 생각이 들었는데, 이런식으로도 역할과 책임 분배를 가져갈 수 있겠네요! 현재 말씀해주신 `AuthoritiesAuthorizationManager` 처럼 다양한 권한 체계는 없기 떄문에 기존 `SecuredAuthorizationManager`에서 `AuthorityAuthorizationManager`를 사용해보는 방향으로 변경해보았습니다.
@@ -0,0 +1,14 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.web.AuthorizationResult; + +@FunctionalInterface +public interface AuthorizationManager<T> { + @Deprecated + AuthorizationDecision check(Authentication authentication, T object); + + default AuthorizationResult authorize(Authentication authentication, T object) { + return check(authentication, object); + } +}
Java
음.. 결국엔 **인가실패시 예외를 발생시킨다.** 가 핵심이라고 생각해요. check로는 null이 올 수도 있고, 권한이 없다 할 지어도 에러코드 등에서 개발자 마음대로 핸들링 할 수 있는 반면에, verify는 인가에 실패한 경우 동일한 에러가 발생된다. 라는 점에서 추적에 용이할 것 같고, 인적오류를 최소화 할 수 있을 것 같다고 생각이 드네요! 따라서 관리자 전용 API등 권한이 없으면 추가적인 로직 없이 바로 예외를 던질때 사용하면 좋을 것 같습니다~
@@ -0,0 +1,14 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.web.AuthorizationResult; + +@FunctionalInterface +public interface AuthorizationManager<T> { + @Deprecated + AuthorizationDecision check(Authentication authentication, T object); + + default AuthorizationResult authorize(Authentication authentication, T object) { + return check(authentication, object); + } +}
Java
네 사실 `verify`를 단일로 쓰면 저희가 흔히 알고 있듯 예외를 발생시킬 수 있는 곳에서 예외를 발생시키는 것이 맞기는 합니다. 다만 `AuthorizationManager`의 원래 책임은 인가가 된 유저인지를 확인하는 것이고 이건 인가가 실패되었다는 것이 에러 상황이 아닌 정상적인 비즈니스의 흐름이라고 볼 수 있어요. 인가가 실패한 것에 대한 결과가 예외가 나는 것은 `AuthorizationFilter`가 인가 실패의 결과가 예외이다라는 것을 실행하는 것일뿐인 것이구요. 실제 `AuthorizationManager`들의 구현체를 보시면 이런 이유들도 겹쳐서 `check`안에서 거의 예외가 발생하지 않고 있는 것을 확인할 수 있어요.
@@ -0,0 +1,28 @@ +package nextstep.security.authorization.web; + +import jakarta.servlet.http.HttpServletRequest; +import java.util.List; +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.AuthorizationManager; +import nextstep.security.util.RequestMatcher; +import nextstep.security.util.RequestMatcherEntry; + +public class RequestMatcherDelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> { + + private final List<RequestMatcherEntry<AuthorizationManager>> mappings; + + public RequestMatcherDelegatingAuthorizationManager(List<RequestMatcherEntry<AuthorizationManager>> mappings) { + this.mappings = mappings; + } + + @Override + public AuthorizationDecision check(Authentication authentication, HttpServletRequest request) { + for (RequestMatcherEntry<AuthorizationManager> mapping : mappings) { + if (mapping.getRequestMatcher().matches(request)) { + return mapping.getEntry().check(authentication, request); + } + } + return AuthorizationDecision.DENY; + } +}
Java
```suggestion if (mapping.matches(request)) { ``` 제가 의도 드렸던 내용은 getter를 꺼내와서 다시 호출하는 것이 아닌 해당 객체 내에서 처리할 수 있게 메시지를 던지는 형태를 말씀드린 것이었어요. getter를 호출해서 메소드 체이닝이 되는 것은 객체의 역할이 있다기보단 단순히 래핑클래스가 되어버려 책임과 역할이 불분명해질 수 있습니다. ```java public boolean matches(HttpServletRequest request) { return requestMatcher.matches(request); } ```
@@ -0,0 +1,13 @@ +package nextstep.security.authorization.web; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.AuthorizationManager; + +public class DenyAllAuthorizationManager implements AuthorizationManager<HttpServletRequest> { + @Override + public AuthorizationDecision check(Authentication authentication, HttpServletRequest object) { + return AuthorizationDecision.DENY; + } +}
Java
```suggestion public AuthorizationResult check(Authentication authentication, HttpServletRequest object) { ``` 반환 타입들도 잘 추상화해주신 클래스로 만들어주면 좋겠네요 :)
@@ -0,0 +1,22 @@ +package nextstep.security.authorization; + +import nextstep.security.authorization.web.AuthorizationResult; + +public class AuthorizationDecision implements AuthorizationResult { + public static final AuthorizationDecision ALLOW = new AuthorizationDecision(true); + public static final AuthorizationDecision DENY = new AuthorizationDecision(false); + + private final boolean granted; + + public AuthorizationDecision(boolean granted) { + this.granted = granted; + } + + public boolean isGranted() { + return granted; + } + + public static AuthorizationDecision of(boolean granted) { + return granted ? ALLOW : DENY; + } +}
Java
```suggestion public static AuthorizationDecision from(boolean granted) { ``` 관습적으로 정적 팩토리 메소드는 파라미터가 하나일때 from, 여러개일때 of를 활용합니다.
@@ -0,0 +1,37 @@ +[ + { + "id": 1, + "img": "images/yoonhee/imgg.jpg", + "text": "한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한" + }, + { + "id": 2, + "img": "images/yoonhee/imgg.jpg", + "text": "한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한" + }, + { + "id": 3, + "img": "images/yoonhee/imgg.jpg", + "text": "한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한" + }, + { + "id": 4, + "img": "images/yoonhee/imgg.jpg", + "text": "한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한" + }, + { + "id": 5, + "img": "images/yoonhee/imgg.jpg", + "text": "한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한" + }, + { + "id": 6, + "img": "images/yoonhee/imgg.jpg", + "text": "한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한" + }, + { + "id": 7, + "img": "images/yoonhee/imgg.jpg", + "text": "한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한국어한" + } +]
Unknown
애국자 윤희님의 뜻 잘 알겠습니다.
@@ -1,9 +1,23 @@ import React from 'react'; +import './Login.scss'; +import LoginForm from './LoginForm'; -class Login extends React.Component { +class LoginYoonHee extends React.Component { render() { - return null; + return ( + <article className="login-art"> + <div className="log-in__main"> + <h1 className="main-name">westagram</h1> + <div className="log-in"> + <LoginForm /> + </div> + <a className="find-ps" href="#!"> + 비밀번호를 잊으셨나요? + </a> + </div> + </article> + ); } } -export default Login; +export default LoginYoonHee;
JavaScript
props의 개념에 대해 잘 이해하셨네요! 하지만 이렇게 할 필요 없이, `<LoginForm>` 컴포넌트에서 withRouter import해서 감싸주시는 방식으로 하시는 게 좋을 것 같네요!
@@ -0,0 +1,75 @@ +.login-art { + display: flex; + justify-content: center; + align-items: center; + height: 100vh; + background-color: var(--color-boxgray); + + .log-in__main { + display: flex; + flex-direction: column; + justify-content: space-evenly; + align-items: center; + width: 300px; + height: 350px; + background-color: white; + border: 1px solid var(--color-boxborder); + } + + .main-name { + font-size: 40px; + font-weight: lighter; + font-family: 'Lobster', cursive; + } + + .log-in { + display: flex; + flex-direction: column; + align-items: center; + } + + .log-in__id, + .log-in__ps { + width: 230px; + height: 35px; + margin: 3px 0; + padding: 3px 10px; + border-radius: 5px; + border: 1px solid var(--color-boxborder); + color: var(--color-textgray); + background-color: var(--color-boxgray); + } + + .find-ps { + text-decoration: none; + font-size: 13px; + } + + .log-in__btn { + width: 230px; + height: 30px; + margin-top: 10px; + margin-bottom: 80px; + border-radius: 5px; + background-color: var(--color--btn-text); + border: none; + color: white; + font-weight: bold; + } + .disabled { + width: 230px; + height: 30px; + margin-top: 10px; + margin-bottom: 80px; + border-radius: 5px; + background-color: var(--color--btn-text-yet); + border: none; + color: white; + font-weight: bold; + } + + .log-in > form { + display: flex; + flex-direction: column; + } +}
Unknown
- 하나의 요소에 여러가지 속성을 부여하는 경우 중요도, 관련도에 따라서 나름의 convention을 지켜서 작성하는 것이 좋습니다. - 일반적인 convention 은 아래와 같습니다. 아래와 같이 순서 적용해주세요. [CSS property 순서] - Layout Properties (position, float, clear, display) - Box Model Properties (width, height, margin, padding) - Visual Properties (color, background, border, box-shadow) - Typography Properties (font-size, font-family, text-align, text-transform) - Misc Properties (cursor, overflow, z-index) - 리뷰하지 않은 부분도 참고해서 수정해주세요-!
@@ -0,0 +1,51 @@ +import React from 'react'; +import { withRouter } from 'react-router-dom'; + +class LoginForm extends React.Component { + constructor() { + super(); + this.state = { id: '', ps: '' }; + } + + goToMain = e => { + this.props.history.push('/main-yoonhee'); + }; + + handleInput = e => { + this.setState({ [e.target.name]: e.target.value }); + }; + + render() { + const { id, ps } = this.state; + const isAble = id.includes('@') && ps.length >= 5; + return ( + <form> + <input + name="id" + className="log-in__id" + type="text" + placeholder="전화번호, 사용자 이름 또는 이메일" + onChange={this.handleInput} + /> + + <input + name="ps" + className="log-in__ps" + type="password" + placeholder="비밀번호" + onChange={this.handleInput} + /> + <button + type="button" + className={`log-in__btn ${isAble ? '' : 'disabled'}`} + onClick={this.goToMain} + disabled={!isAble} + > + 로그인 + </button> + </form> + ); + } +} + +export default withRouter(LoginForm);
JavaScript
계산된 속성명 잘 활용해주셨네요! :)
@@ -0,0 +1,10 @@ +import React from 'react'; + +class Comment extends React.Component { + render() { + const { innerText } = this.props; + return <li>{innerText}</li>; + } +} + +export default Comment;
JavaScript
map 메서드를 사용하시는 부분에서 key prop 부여해주시면 됩니다!
@@ -0,0 +1,59 @@ +import React from 'react'; +import Comment from './Comment'; + +class CommentBox extends React.Component { + constructor(props) { + super(props); + this.state = { feedComment: '', commentList: [] }; + } + + handleInput = e => { + this.setState({ [e.target.name]: e.target.value }); + }; + + addCommentByEnter = e => { + if (e.key === 'Enter') { + this.addComment(); + } + }; + + addComment = () => { + const { feedComment, commentList } = this.state; + this.setState({ + commentList: [...commentList, feedComment], + feedComment: '', + }); + }; + + render() { + return ( + <> + <div className="feed__comment-box"> + <input + name="feedComment" + className="comment__input" + placeholder="댓글 달기..." + onChange={this.handleInput} + onKeyDown={this.addCommentByEnter} + value={this.state.feedComment} + /> + <button + className="btn btn--hover comment__btn" + onClick={this.addComment} + > + 게시 + </button> + </div> + <div className="feed__comment"> + <ul className="feed__comment-list"> + {this.state.commentList.map((comment, index) => { + return <Comment key={index} innerText={comment} />; + })} + </ul> + </div> + </> + ); + } +} + +export default CommentBox;
JavaScript
isKeyEnter라는 함수명은 key가 enter인지 아닌지를 판별하는 boolean 변수명으로 적합한 것 같네요. 함수의 동작에 대한 내용을 직관적으로 알 수 있는 동사형으로 작성해주세요! ex) addCommentByEnter
@@ -0,0 +1,59 @@ +import React from 'react'; +import Comment from './Comment'; + +class CommentBox extends React.Component { + constructor(props) { + super(props); + this.state = { feedComment: '', commentList: [] }; + } + + handleInput = e => { + this.setState({ [e.target.name]: e.target.value }); + }; + + addCommentByEnter = e => { + if (e.key === 'Enter') { + this.addComment(); + } + }; + + addComment = () => { + const { feedComment, commentList } = this.state; + this.setState({ + commentList: [...commentList, feedComment], + feedComment: '', + }); + }; + + render() { + return ( + <> + <div className="feed__comment-box"> + <input + name="feedComment" + className="comment__input" + placeholder="댓글 달기..." + onChange={this.handleInput} + onKeyDown={this.addCommentByEnter} + value={this.state.feedComment} + /> + <button + className="btn btn--hover comment__btn" + onClick={this.addComment} + > + 게시 + </button> + </div> + <div className="feed__comment"> + <ul className="feed__comment-list"> + {this.state.commentList.map((comment, index) => { + return <Comment key={index} innerText={comment} />; + })} + </ul> + </div> + </> + ); + } +} + +export default CommentBox;
JavaScript
리뷰하지 않은 부분도 수정해주세요!
@@ -0,0 +1,59 @@ +import React from 'react'; +import Comment from './Comment'; + +class CommentBox extends React.Component { + constructor(props) { + super(props); + this.state = { feedComment: '', commentList: [] }; + } + + handleInput = e => { + this.setState({ [e.target.name]: e.target.value }); + }; + + addCommentByEnter = e => { + if (e.key === 'Enter') { + this.addComment(); + } + }; + + addComment = () => { + const { feedComment, commentList } = this.state; + this.setState({ + commentList: [...commentList, feedComment], + feedComment: '', + }); + }; + + render() { + return ( + <> + <div className="feed__comment-box"> + <input + name="feedComment" + className="comment__input" + placeholder="댓글 달기..." + onChange={this.handleInput} + onKeyDown={this.addCommentByEnter} + value={this.state.feedComment} + /> + <button + className="btn btn--hover comment__btn" + onClick={this.addComment} + > + 게시 + </button> + </div> + <div className="feed__comment"> + <ul className="feed__comment-list"> + {this.state.commentList.map((comment, index) => { + return <Comment key={index} innerText={comment} />; + })} + </ul> + </div> + </> + ); + } +} + +export default CommentBox;
JavaScript
- `newfeedComment`라고 새로 선언하고 할당할 필요 없이, concat 메서드에 feedComment라는 state를 직접 넣어주셔도 될 것 같네요. - concat 잘 사용해주셨는데, concat 대신에 spread operator를 사용해서 동일하게 구현해보실 수 있습니다. 연습한다고 생각하시고 찾아서 구현해보세요! ```suggestion const { feedComment, commentList } = this.state; this.setState({ commentList: commentList.concat(feedComment), feedComment: '', }); ```
@@ -0,0 +1,59 @@ +import React from 'react'; +import Comment from './Comment'; + +class CommentBox extends React.Component { + constructor(props) { + super(props); + this.state = { feedComment: '', commentList: [] }; + } + + handleInput = e => { + this.setState({ [e.target.name]: e.target.value }); + }; + + addCommentByEnter = e => { + if (e.key === 'Enter') { + this.addComment(); + } + }; + + addComment = () => { + const { feedComment, commentList } = this.state; + this.setState({ + commentList: [...commentList, feedComment], + feedComment: '', + }); + }; + + render() { + return ( + <> + <div className="feed__comment-box"> + <input + name="feedComment" + className="comment__input" + placeholder="댓글 달기..." + onChange={this.handleInput} + onKeyDown={this.addCommentByEnter} + value={this.state.feedComment} + /> + <button + className="btn btn--hover comment__btn" + onClick={this.addComment} + > + 게시 + </button> + </div> + <div className="feed__comment"> + <ul className="feed__comment-list"> + {this.state.commentList.map((comment, index) => { + return <Comment key={index} innerText={comment} />; + })} + </ul> + </div> + </> + ); + } +} + +export default CommentBox;
JavaScript
이 컴포넌트의 tag들에서 id와 className을 같이 부여하신 이유가 있을까요??
@@ -0,0 +1,59 @@ +import React from 'react'; +import Comment from './Comment'; + +class CommentBox extends React.Component { + constructor(props) { + super(props); + this.state = { feedComment: '', commentList: [] }; + } + + handleInput = e => { + this.setState({ [e.target.name]: e.target.value }); + }; + + addCommentByEnter = e => { + if (e.key === 'Enter') { + this.addComment(); + } + }; + + addComment = () => { + const { feedComment, commentList } = this.state; + this.setState({ + commentList: [...commentList, feedComment], + feedComment: '', + }); + }; + + render() { + return ( + <> + <div className="feed__comment-box"> + <input + name="feedComment" + className="comment__input" + placeholder="댓글 달기..." + onChange={this.handleInput} + onKeyDown={this.addCommentByEnter} + value={this.state.feedComment} + /> + <button + className="btn btn--hover comment__btn" + onClick={this.addComment} + > + 게시 + </button> + </div> + <div className="feed__comment"> + <ul className="feed__comment-list"> + {this.state.commentList.map((comment, index) => { + return <Comment key={index} innerText={comment} />; + })} + </ul> + </div> + </> + ); + } +} + +export default CommentBox;
JavaScript
위에 리뷰드린 내용이네요! index를 props로 넘겨주는 게 아니라, 이 부분에서 key={index}로 부여해주시면 될 것 같습니다!
@@ -0,0 +1,59 @@ +import React from 'react'; +import Comment from './Comment'; + +class CommentBox extends React.Component { + constructor(props) { + super(props); + this.state = { feedComment: '', commentList: [] }; + } + + handleInput = e => { + this.setState({ [e.target.name]: e.target.value }); + }; + + addCommentByEnter = e => { + if (e.key === 'Enter') { + this.addComment(); + } + }; + + addComment = () => { + const { feedComment, commentList } = this.state; + this.setState({ + commentList: [...commentList, feedComment], + feedComment: '', + }); + }; + + render() { + return ( + <> + <div className="feed__comment-box"> + <input + name="feedComment" + className="comment__input" + placeholder="댓글 달기..." + onChange={this.handleInput} + onKeyDown={this.addCommentByEnter} + value={this.state.feedComment} + /> + <button + className="btn btn--hover comment__btn" + onClick={this.addComment} + > + 게시 + </button> + </div> + <div className="feed__comment"> + <ul className="feed__comment-list"> + {this.state.commentList.map((comment, index) => { + return <Comment key={index} innerText={comment} />; + })} + </ul> + </div> + </> + ); + } +} + +export default CommentBox;
JavaScript
그리고 cur이라는 변수명은 어떤 데이터를 가지고 있는지 명확하지 않은데, 해당 변수가 담고 있는 데이터에 대한 내용이 좀 더 직관적으로 드러날 수 있도록 수정해주세요! ex) comment
@@ -0,0 +1,32 @@ +import React from 'react'; +import Feed from './Feed'; + +class Feeds extends React.Component { + constructor(props) { + super(props); + this.state = { + feeds: [], + }; + } + + componentDidMount() { + fetch('/data/feed.json') + .then(res => res.json()) + .then(data => { + this.setState({ feeds: data }); + }); + } + + render() { + const { feeds } = this.state; + return ( + <div className="feeds"> + {feeds.map(feed => ( + <Feed key={feed.id} img={feed.img} text={feed.text} /> + ))} + </div> + ); + } +} + +export default Feeds;
JavaScript
- method 잘 생략해주셨네요! 👍 - 추가적으로, `http://localhost:3000` 부분도 생략할 수 있습니다. 포트 번호가 바뀔 때마다 에러가 발생하고 그때그때 수정해줘야 하는 번거로움이 있기 때문에, 다음과 같이 생략해서 사용해주세요! ```suggestion fetch('/data/feed.json') ```
@@ -0,0 +1,32 @@ +import React from 'react'; +import Feed from './Feed'; + +class Feeds extends React.Component { + constructor(props) { + super(props); + this.state = { + feeds: [], + }; + } + + componentDidMount() { + fetch('/data/feed.json') + .then(res => res.json()) + .then(data => { + this.setState({ feeds: data }); + }); + } + + render() { + const { feeds } = this.state; + return ( + <div className="feeds"> + {feeds.map(feed => ( + <Feed key={feed.id} img={feed.img} text={feed.text} /> + ))} + </div> + ); + } +} + +export default Feeds;
JavaScript
오잉 여기에는 key prop 잘 부여해주셨네요! 살짝 흠을 잡자면,, 매개변수의 데이터는 각 피드에 대한 데이터이기 때문에 feeds -> feed가 더 적절한 것 같습니다.
@@ -1,9 +1,22 @@ +// eslint-disable-next-line import React from 'react'; +import Nav from './Nav'; +import Feeds from './Feeds'; +import MainR from './MainR'; +import './Main.scss'; -class Main extends React.Component { +class MainYoonHee extends React.Component { render() { - return null; + return ( + <div className="main-body"> + <Nav /> + <main> + <Feeds /> + <MainR /> + </main> + </div> + ); } } -export default Main; +export default MainYoonHee;
JavaScript
import 순서 수정해주세요! 일반적인 convention을 따라 순서만 잘 지켜주셔도 가독성이 좋아집니다. 아래 순서 참고해주세요. - React → Library(Package) → Component → 변수 / 이미지 → css 파일(scss 파일)
@@ -0,0 +1,25 @@ +import React from 'react'; + +class Recommend extends React.Component { + render() { + const { nickname, img } = this.props; + return ( + <li className="user main-right__user2"> + <div className="user-and-botton"> + <img + className="user__img user__img--brder-red" + alt={nickname} + src={img} + /> + <div className="user-id2"> + <div className="user__id">{nickname}</div> + <div className="text--gray">한국어한국어한국어</div> + </div> + </div> + <button className="btn btn--hover nnn">팔로우</button> + </li> + ); + } +} + +export default Recommend;
JavaScript
`<li>`태그, `<div>`태그 둘 중 하나로만 감싸주셔도 될 것 같습니다!
@@ -0,0 +1,22 @@ +import React from 'react'; + +class Story extends React.Component { + render() { + const { nickname, img } = this.props; + return ( + <li className="user main-right__user"> + <img + className="user__img user__img--brder-red" + alt={nickname} + src={img} + /> + <div className="user-id2"> + <div className="user__id">{nickname}</div> + <div className="text--gray">2시간 전</div> + </div> + </li> + ); + } +} + +export default Story;
JavaScript
여기도 마찬가지-!
@@ -0,0 +1,281 @@ +/*------공통-----*/ +/*------공통-----*/ + +.main-body { + background-color: var(--color-boxgray); +} + +main { + display: flex; + margin-left: 100px; +} + +ul > li { + margin: 10px 0; +} + +a { + text-decoration: none; + color: inherit; +} + +.box { + background-color: white; + border: 1px solid var(--color-boxborder); +} +.box-padding { + padding: 10px; +} + +.text { + font-size: 12px; +} + +.text--gray { + margin-top: 3px; + font-size: 13px; + color: var(--color-textgray); +} + +.icon { + border: no; +} + +.btn { + padding: 5px 0px; + border: none; + border-radius: 5px; + background-color: transparent; + color: var(--color--btn-text); + font-weight: bold; +} +.btn--hover:hover { + color: white; + background-color: var(--color--btn-text); +} + +.westagram { + font-family: 'Lobster', cursive; + font-size: 25px; +} +.user { + display: flex; + align-items: center; + justify-content: flex-start; +} + +.user__img { + width: 30px; + height: 30px; + margin-right: 7px; + border-radius: 50%; + border: 1px solid var(--color-textgray); +} + +.user__img--brder-red { + border: 1px solid red; + border-spacing: 3px; +} + +.user__img--small { + width: 20px; + height: 18px; + margin-right: 5px; +} + +.user__img--big { + width: 40px; + height: 40px; +} + +.user__id { + font-size: 14px; + font-weight: bolder; +} + +.user-text2 { + display: flex; + flex-direction: column; +} + +.footer { + margin-top: 15px; +} + +/*--------nav--------*/ +/*--------nav--------*/ +/*--------nav--------*/ + +.nav { + display: flex; + justify-content: space-around; + align-items: center; + padding: 20px 0; + border-bottom: 1px solid var(--color-boxborder); + background-color: white; + + .nav__border { + height: 30px; + border-left: 2px solid black; + } + + .nav-left { + display: flex; + align-items: center; + justify-content: space-between; + width: 18%; + } + + .nav-center { + width: 20%; + } + + .nav-center > .search-bar { + height: 25px; + width: 100%; + border: 1px solid var(--color-boxborder); + background-color: var(--color-boxgray); + text-align: center; + } + .search-bar[value] { + color: var(--color-textgray); + } + + .nav-right { + display: flex; + justify-content: space-between; + width: 12%; + } +} + +/*----------feed----------*/ +/*----------feed----------*/ +/*----------feed----------*/ + +.feeds { + display: flex; + flex-direction: column; + width: 50%; + padding-top: 65px; + + .feed { + display: flex; + align-items: center; + flex-direction: column; + width: 100%; + margin-bottom: 50px; + border: 1px solid var(--color-boxborder); + background-color: white; + } + + .feed__head { + display: flex; + align-items: center; + justify-content: space-between; + width: 95%; + margin: 15px 20px; + } + + .feed__head > .user { + width: 22%; + } + + .feed__img { + width: 100%; + } + + .feed__icons { + display: flex; + justify-content: space-between; + width: 95%; + margin: 12px 0px; + } + + .feed__icons__left { + display: flex; + justify-content: space-between; + width: 18%; + } + + .feed__likes { + display: flex; + align-items: center; + width: 95%; + } + + .feed__text { + width: 95%; + margin-top: 15px; + } + + .feed__comment-box { + width: 100%; + height: 35px; + margin-top: 5px; + border-top: 1px solid var(--color-boxborder); + border-bottom: 1px solid var(--color-boxborder); + } + + .comment__input { + width: 90%; + height: 100%; + padding-left: 14px; + border: none; + } + + .comment__input[placehilder] { + color: var(--color-textgray); + } + + .comment__btn { + width: 8%; + height: 80; + } + + .feed__comment { + width: 100%; + } + .feed__comment-list { + width: 95%; + margin: 10px 0; + padding: 5px 14px; + } + + .feed__comment-list > li { + font-size: 13px; + } +} + +/*-------------main-right------------*/ +/*-------------main-right------------*/ +/*-------------main-right------------*/ + +.main-right { + position: fixed; + right: 40px; + width: 25%; + margin-top: 65px; + + .main-right__header { + display: flex; + align-items: flex-end; + justify-content: space-between; + margin-bottom: 15px; + padding: 0 5px; + } + + .user-and-botton { + width: 70%; + display: flex; + } + + .main-right__story > .box { + margin-top: 15px; + } + + .main-right__user2 { + display: flex; + justify-content: space-between; + margin: 2px; + } +}
Unknown
공통으로 사용하는 속성은 팀원들과 상의하여 common.scss 파일로 옮겨주세요!
@@ -0,0 +1,59 @@ +import React from 'react'; +import Comment from './Comment'; + +class CommentBox extends React.Component { + constructor(props) { + super(props); + this.state = { feedComment: '', commentList: [] }; + } + + handleInput = e => { + this.setState({ [e.target.name]: e.target.value }); + }; + + addCommentByEnter = e => { + if (e.key === 'Enter') { + this.addComment(); + } + }; + + addComment = () => { + const { feedComment, commentList } = this.state; + this.setState({ + commentList: [...commentList, feedComment], + feedComment: '', + }); + }; + + render() { + return ( + <> + <div className="feed__comment-box"> + <input + name="feedComment" + className="comment__input" + placeholder="댓글 달기..." + onChange={this.handleInput} + onKeyDown={this.addCommentByEnter} + value={this.state.feedComment} + /> + <button + className="btn btn--hover comment__btn" + onClick={this.addComment} + > + 게시 + </button> + </div> + <div className="feed__comment"> + <ul className="feed__comment-list"> + {this.state.commentList.map((comment, index) => { + return <Comment key={index} innerText={comment} />; + })} + </ul> + </div> + </> + ); + } +} + +export default CommentBox;
JavaScript
리액트로 파일 옮겨오기전 js파일로만 작업할 때 돔으로 접근하는 용도로 쓰고 지우는걸 깜빡했네요 …;;;ㅠㅠ지웠습니다!
@@ -1,9 +1,23 @@ import React from 'react'; +import './Login.scss'; +import LoginForm from './LoginForm'; -class Login extends React.Component { +class LoginYoonHee extends React.Component { render() { - return null; + return ( + <article className="login-art"> + <div className="log-in__main"> + <h1 className="main-name">westagram</h1> + <div className="log-in"> + <LoginForm /> + </div> + <a className="find-ps" href="#!"> + 비밀번호를 잊으셨나요? + </a> + </div> + </article> + ); } } -export default Login; +export default LoginYoonHee;
JavaScript
수정했습니당! 덕분에 라우터에 대해서 좀 더 알게됐네용 ㅎㅎ
@@ -0,0 +1,10 @@ +import React from 'react'; + +class Comment extends React.Component { + render() { + const { innerText } = this.props; + return <li>{innerText}</li>; + } +} + +export default Comment;
JavaScript
수정했습니다-! key값 넣는곳을 정확히 모르고있었는데 이제 정확하게 알거같아요!
@@ -0,0 +1,32 @@ +import React from 'react'; +import Feed from './Feed'; + +class Feeds extends React.Component { + constructor(props) { + super(props); + this.state = { + feeds: [], + }; + } + + componentDidMount() { + fetch('/data/feed.json') + .then(res => res.json()) + .then(data => { + this.setState({ feeds: data }); + }); + } + + render() { + const { feeds } = this.state; + return ( + <div className="feeds"> + {feeds.map(feed => ( + <Feed key={feed.id} img={feed.img} text={feed.text} /> + ))} + </div> + ); + } +} + +export default Feeds;
JavaScript
수정했습니다-! 포트번호는 생략으루! 팁 감사합니당!
@@ -0,0 +1,32 @@ +import React from 'react'; +import Feed from './Feed'; + +class Feeds extends React.Component { + constructor(props) { + super(props); + this.state = { + feeds: [], + }; + } + + componentDidMount() { + fetch('/data/feed.json') + .then(res => res.json()) + .then(data => { + this.setState({ feeds: data }); + }); + } + + render() { + const { feeds } = this.state; + return ( + <div className="feeds"> + {feeds.map(feed => ( + <Feed key={feed.id} img={feed.img} text={feed.text} /> + ))} + </div> + ); + } +} + +export default Feeds;
JavaScript
feed로 수정완료 했습니당 😊
@@ -1,9 +1,22 @@ +// eslint-disable-next-line import React from 'react'; +import Nav from './Nav'; +import Feeds from './Feeds'; +import MainR from './MainR'; +import './Main.scss'; -class Main extends React.Component { +class MainYoonHee extends React.Component { render() { - return null; + return ( + <div className="main-body"> + <Nav /> + <main> + <Feeds /> + <MainR /> + </main> + </div> + ); } } -export default Main; +export default MainYoonHee;
JavaScript
scss파일 아래로 위치수정 했습니당 !
@@ -1,9 +1,22 @@ +// eslint-disable-next-line import React from 'react'; +import Nav from './Nav'; +import Feeds from './Feeds'; +import MainR from './MainR'; +import './Main.scss'; -class Main extends React.Component { +class MainYoonHee extends React.Component { render() { - return null; + return ( + <div className="main-body"> + <Nav /> + <main> + <Feeds /> + <MainR /> + </main> + </div> + ); } } -export default Main; +export default MainYoonHee;
JavaScript
그 때 말씀해주셨던 부분이네용 ㅎㅎ.. <div>로 변경했습니당.. 콘솔창에 뜨던 알수없는 빨간색 글씨 오류가 이것떄문이였군용 ㅠㅠ index.html에있는 body부분과 충돌해서요; 기본적인 구조를 생각하면 당연한건데 제가 너무 안일했네요..
@@ -0,0 +1,25 @@ +import React from 'react'; + +class Recommend extends React.Component { + render() { + const { nickname, img } = this.props; + return ( + <li className="user main-right__user2"> + <div className="user-and-botton"> + <img + className="user__img user__img--brder-red" + alt={nickname} + src={img} + /> + <div className="user-id2"> + <div className="user__id">{nickname}</div> + <div className="text--gray">한국어한국어한국어</div> + </div> + </div> + <button className="btn btn--hover nnn">팔로우</button> + </li> + ); + } +} + +export default Recommend;
JavaScript
수정했숨미당~!😇
@@ -0,0 +1,22 @@ +import React from 'react'; + +class Story extends React.Component { + render() { + const { nickname, img } = this.props; + return ( + <li className="user main-right__user"> + <img + className="user__img user__img--brder-red" + alt={nickname} + src={img} + /> + <div className="user-id2"> + <div className="user__id">{nickname}</div> + <div className="text--gray">2시간 전</div> + </div> + </li> + ); + } +} + +export default Story;
JavaScript
여기두용~
@@ -0,0 +1,281 @@ +/*------공통-----*/ +/*------공통-----*/ + +.main-body { + background-color: var(--color-boxgray); +} + +main { + display: flex; + margin-left: 100px; +} + +ul > li { + margin: 10px 0; +} + +a { + text-decoration: none; + color: inherit; +} + +.box { + background-color: white; + border: 1px solid var(--color-boxborder); +} +.box-padding { + padding: 10px; +} + +.text { + font-size: 12px; +} + +.text--gray { + margin-top: 3px; + font-size: 13px; + color: var(--color-textgray); +} + +.icon { + border: no; +} + +.btn { + padding: 5px 0px; + border: none; + border-radius: 5px; + background-color: transparent; + color: var(--color--btn-text); + font-weight: bold; +} +.btn--hover:hover { + color: white; + background-color: var(--color--btn-text); +} + +.westagram { + font-family: 'Lobster', cursive; + font-size: 25px; +} +.user { + display: flex; + align-items: center; + justify-content: flex-start; +} + +.user__img { + width: 30px; + height: 30px; + margin-right: 7px; + border-radius: 50%; + border: 1px solid var(--color-textgray); +} + +.user__img--brder-red { + border: 1px solid red; + border-spacing: 3px; +} + +.user__img--small { + width: 20px; + height: 18px; + margin-right: 5px; +} + +.user__img--big { + width: 40px; + height: 40px; +} + +.user__id { + font-size: 14px; + font-weight: bolder; +} + +.user-text2 { + display: flex; + flex-direction: column; +} + +.footer { + margin-top: 15px; +} + +/*--------nav--------*/ +/*--------nav--------*/ +/*--------nav--------*/ + +.nav { + display: flex; + justify-content: space-around; + align-items: center; + padding: 20px 0; + border-bottom: 1px solid var(--color-boxborder); + background-color: white; + + .nav__border { + height: 30px; + border-left: 2px solid black; + } + + .nav-left { + display: flex; + align-items: center; + justify-content: space-between; + width: 18%; + } + + .nav-center { + width: 20%; + } + + .nav-center > .search-bar { + height: 25px; + width: 100%; + border: 1px solid var(--color-boxborder); + background-color: var(--color-boxgray); + text-align: center; + } + .search-bar[value] { + color: var(--color-textgray); + } + + .nav-right { + display: flex; + justify-content: space-between; + width: 12%; + } +} + +/*----------feed----------*/ +/*----------feed----------*/ +/*----------feed----------*/ + +.feeds { + display: flex; + flex-direction: column; + width: 50%; + padding-top: 65px; + + .feed { + display: flex; + align-items: center; + flex-direction: column; + width: 100%; + margin-bottom: 50px; + border: 1px solid var(--color-boxborder); + background-color: white; + } + + .feed__head { + display: flex; + align-items: center; + justify-content: space-between; + width: 95%; + margin: 15px 20px; + } + + .feed__head > .user { + width: 22%; + } + + .feed__img { + width: 100%; + } + + .feed__icons { + display: flex; + justify-content: space-between; + width: 95%; + margin: 12px 0px; + } + + .feed__icons__left { + display: flex; + justify-content: space-between; + width: 18%; + } + + .feed__likes { + display: flex; + align-items: center; + width: 95%; + } + + .feed__text { + width: 95%; + margin-top: 15px; + } + + .feed__comment-box { + width: 100%; + height: 35px; + margin-top: 5px; + border-top: 1px solid var(--color-boxborder); + border-bottom: 1px solid var(--color-boxborder); + } + + .comment__input { + width: 90%; + height: 100%; + padding-left: 14px; + border: none; + } + + .comment__input[placehilder] { + color: var(--color-textgray); + } + + .comment__btn { + width: 8%; + height: 80; + } + + .feed__comment { + width: 100%; + } + .feed__comment-list { + width: 95%; + margin: 10px 0; + padding: 5px 14px; + } + + .feed__comment-list > li { + font-size: 13px; + } +} + +/*-------------main-right------------*/ +/*-------------main-right------------*/ +/*-------------main-right------------*/ + +.main-right { + position: fixed; + right: 40px; + width: 25%; + margin-top: 65px; + + .main-right__header { + display: flex; + align-items: flex-end; + justify-content: space-between; + margin-bottom: 15px; + padding: 0 5px; + } + + .user-and-botton { + width: 70%; + display: flex; + } + + .main-right__story > .box { + margin-top: 15px; + } + + .main-right__user2 { + display: flex; + justify-content: space-between; + margin: 2px; + } +}
Unknown
common.scss 파일에 이미 있어서 해당 부분 삭제했어용 ㅎ...😱
@@ -0,0 +1,51 @@ +import React from 'react'; +import { withRouter } from 'react-router-dom'; + +class LoginForm extends React.Component { + constructor() { + super(); + this.state = { id: '', ps: '' }; + } + + goToMain = e => { + this.props.history.push('/main-yoonhee'); + }; + + handleInput = e => { + this.setState({ [e.target.name]: e.target.value }); + }; + + render() { + const { id, ps } = this.state; + const isAble = id.includes('@') && ps.length >= 5; + return ( + <form> + <input + name="id" + className="log-in__id" + type="text" + placeholder="전화번호, 사용자 이름 또는 이메일" + onChange={this.handleInput} + /> + + <input + name="ps" + className="log-in__ps" + type="password" + placeholder="비밀번호" + onChange={this.handleInput} + /> + <button + type="button" + className={`log-in__btn ${isAble ? '' : 'disabled'}`} + onClick={this.goToMain} + disabled={!isAble} + > + 로그인 + </button> + </form> + ); + } +} + +export default withRouter(LoginForm);
JavaScript
래영님 강의 덕분입니당 ㅋ.ㅋ
@@ -0,0 +1,59 @@ +import React from 'react'; +import Comment from './Comment'; + +class CommentBox extends React.Component { + constructor(props) { + super(props); + this.state = { feedComment: '', commentList: [] }; + } + + handleInput = e => { + this.setState({ [e.target.name]: e.target.value }); + }; + + addCommentByEnter = e => { + if (e.key === 'Enter') { + this.addComment(); + } + }; + + addComment = () => { + const { feedComment, commentList } = this.state; + this.setState({ + commentList: [...commentList, feedComment], + feedComment: '', + }); + }; + + render() { + return ( + <> + <div className="feed__comment-box"> + <input + name="feedComment" + className="comment__input" + placeholder="댓글 달기..." + onChange={this.handleInput} + onKeyDown={this.addCommentByEnter} + value={this.state.feedComment} + /> + <button + className="btn btn--hover comment__btn" + onClick={this.addComment} + > + 게시 + </button> + </div> + <div className="feed__comment"> + <ul className="feed__comment-list"> + {this.state.commentList.map((comment, index) => { + return <Comment key={index} innerText={comment} />; + })} + </ul> + </div> + </> + ); + } +} + +export default CommentBox;
JavaScript
데이터 내용의 뜻을 알 수 있게 comment로 변경했습니다!
@@ -0,0 +1,29 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationException; +import org.aopalliance.intercept.MethodInvocation; + +import java.lang.reflect.Method; +import java.util.List; + +public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { + private final AuthoritiesAuthorizationManager authoritiesAuthorizationManager = new AuthoritiesAuthorizationManager(); + + @Override + public AuthorizationDecision check(final Authentication authentication, final MethodInvocation invocation) { + Method method = invocation.getMethod(); + + if (method.isAnnotationPresent(Secured.class)) { + Secured secured = method.getAnnotation(Secured.class); + + if (authentication == null) { + throw new AuthenticationException(); + } + + return authoritiesAuthorizationManager.check(authentication, List.of(secured.value())); + } + + return new AuthorizationDecision(true); + } +}
Java
method.getAnnotation(Secured.class)를 사용하여 `@Secured` 어노테이션을 조회하고 있네요. Spring AOP 환경에서는 메서드가 프록시 객체로 감싸질 수 있기 때문에, 프록시된 메서드를 조회할 경우 실제 구현체의 메서드에서 선언된 `@Secured` 어노테이션을 찾지 못할 가능성이 있습니다. method.getAnnotation 와 AopUtils.getMostSpecificMethod() 어떤 차이가 있을까요? 😄
@@ -23,7 +23,7 @@ @AutoConfigureMockMvc class BasicAuthTest { private final Member TEST_ADMIN_MEMBER = new Member("a@a.com", "password", "a", "", Set.of("ADMIN")); - private final Member TEST_USER_MEMBER = new Member("b@b.com", "password", "b", "", Set.of()); + private final Member TEST_USER_MEMBER = new Member("b@b.com", "password", "b", "", Set.of("")); @Autowired private MockMvc mockMvc; @@ -37,6 +37,33 @@ void setUp() { memberRepository.save(TEST_USER_MEMBER); } + @DisplayName("인증된 사용자는 자신의 정보를 조회할 수 있다.") + @Test + void request_success_members_me() throws Exception { + String token = Base64.getEncoder().encodeToString((TEST_USER_MEMBER.getEmail() + ":" + TEST_USER_MEMBER.getPassword()).getBytes()); + + ResultActions response = mockMvc.perform(get("/members/me") + .header("Authorization", "Basic " + token) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + ); + + response.andExpect(status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.email").value(TEST_USER_MEMBER.getEmail())); + } + + @DisplayName("인증되지 않은 사용자는 자신의 정보를 조회할 수 없다.") + @Test + void request_fail_members_me() throws Exception { + String token = Base64.getEncoder().encodeToString(("none" + ":" + "none").getBytes()); + + ResultActions response = mockMvc.perform(get("/members/me") + .header("Authorization", "Basic " + token) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + ); + + response.andExpect(status().isUnauthorized()); + } + @DisplayName("ADMIN 권한을 가진 사용자가 요청할 경우 모든 회원 정보를 조회할 수 있다.") @Test void request_success_with_admin_user() throws Exception { @@ -64,6 +91,20 @@ void request_fail_with_general_user() throws Exception { response.andExpect(status().isForbidden()); } + @DisplayName("허용된 URI이 아닌경우 요청이 실패 한다.") + @Test + void request_fail_invalid_uri() throws Exception { + String token = Base64.getEncoder().encodeToString((TEST_USER_MEMBER.getEmail() + ":" + TEST_USER_MEMBER.getPassword()).getBytes()); + + ResultActions response = mockMvc.perform(get("/invalid-uri") + .header("Authorization", "Basic " + token) + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + ); + + response.andExpect(status().isForbidden()); + } + + @DisplayName("사용자 정보가 없는 경우 요청이 실패해야 한다.") @Test void request_fail_with_no_user() throws Exception {
Java
테스트 코드 👍
@@ -0,0 +1,29 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationException; +import org.aopalliance.intercept.MethodInvocation; + +import java.lang.reflect.Method; +import java.util.List; + +public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { + private final AuthoritiesAuthorizationManager authoritiesAuthorizationManager = new AuthoritiesAuthorizationManager(); + + @Override + public AuthorizationDecision check(final Authentication authentication, final MethodInvocation invocation) { + Method method = invocation.getMethod(); + + if (method.isAnnotationPresent(Secured.class)) { + Secured secured = method.getAnnotation(Secured.class); + + if (authentication == null) { + throw new AuthenticationException(); + } + + return authoritiesAuthorizationManager.check(authentication, List.of(secured.value())); + } + + return new AuthorizationDecision(true); + } +}
Java
AopUtils.getMostSpecificMethod()를 사용하면 프록시 객체든 아니든 실제 객체의 메서드를 조회하여 @Secured 어노테이션을 못찾는 경우가 발생하지 않겠네요! 감사합니다 :)
@@ -0,0 +1,83 @@ +@import '../../../../../Styles/common.scss'; + +.navYeseul { + position: fixed; + top: 0; + left: 50%; + right: 0; + transform: translateX(-50%); + padding: 8px 0; + border-bottom: 1px solid $main-border; + background-color: #fff; + z-index: 9999; + + .inner-nav { + display: flex; + justify-content: space-between; + align-items: center; + margin: 0 auto; + padding: 0 20px; + width: 100%; + max-width: 975px; + box-sizing: border-box; + + h1 { + display: flex; + align-items: center; + margin: 0; + font-size: 28px; + color: $main-font; + + button { + margin-right: 15px; + padding: 0 14px 0 0; + width: 22px; + height: 22px; + box-sizing: content-box; + border-right: 2px solid $main-font; + + img { + margin: 0; + } + } + } + + .nav__search { + display: flex; + align-items: center; + padding: 3px 10px 3px 26px; + width: 215px; + min-width: 125px; + height: 28px; + box-sizing: border-box; + border: 1px solid $main-border; + border-radius: 3px; + background-color: $bg-light-grey; + + input { + height: 100%; + background-color: transparent; + + &::placeholder { + text-align: center; + } + } + } + + .nav__menu { + display: flex; + + li { + margin-left: 22px; + width: 22px; + height: 22px; + + .like-button { + padding: 0; + width: 22px; + height: 22px; + } + } + } + } +}
Unknown
css 속성 순서에 따르면 z-index가 가장 아래에 와야 할 것 같아요 😀
@@ -0,0 +1,83 @@ +@import '../../../../../Styles/common.scss'; + +.navYeseul { + position: fixed; + top: 0; + left: 50%; + right: 0; + transform: translateX(-50%); + padding: 8px 0; + border-bottom: 1px solid $main-border; + background-color: #fff; + z-index: 9999; + + .inner-nav { + display: flex; + justify-content: space-between; + align-items: center; + margin: 0 auto; + padding: 0 20px; + width: 100%; + max-width: 975px; + box-sizing: border-box; + + h1 { + display: flex; + align-items: center; + margin: 0; + font-size: 28px; + color: $main-font; + + button { + margin-right: 15px; + padding: 0 14px 0 0; + width: 22px; + height: 22px; + box-sizing: content-box; + border-right: 2px solid $main-font; + + img { + margin: 0; + } + } + } + + .nav__search { + display: flex; + align-items: center; + padding: 3px 10px 3px 26px; + width: 215px; + min-width: 125px; + height: 28px; + box-sizing: border-box; + border: 1px solid $main-border; + border-radius: 3px; + background-color: $bg-light-grey; + + input { + height: 100%; + background-color: transparent; + + &::placeholder { + text-align: center; + } + } + } + + .nav__menu { + display: flex; + + li { + margin-left: 22px; + width: 22px; + height: 22px; + + .like-button { + padding: 0; + width: 22px; + height: 22px; + } + } + } + } +}
Unknown
common css에 있어서 빼셔도 될 것 같아요!
@@ -0,0 +1,125 @@ +import React, { Component } from 'react'; +import { withRouter } from 'react-router-dom'; +import { API } from '../../../config'; +import './Login.scss'; + +class LoginYeseul extends Component { + constructor(props) { + super(props); + this.state = { + inputId: '', + inputPw: '', + loginMode: true, + }; + } + + handleInput = e => { + const { name, value } = e.target; + this.setState({ [name]: value }); + }; + + convertMode = () => { + this.setState({ + loginMode: !this.state.loginMode, + }); + }; + + signIn = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_IN, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + localStorage.setItem('token', users.ACCESS_TOKEN); + this.props.history.push('/main-yeseul'); + } else if (users.MESSAGE === 'INVALID_USER') { + const wantToSignUp = window.confirm( + '잘못된 정보입니다. 회원가입하시겠습니까?' + ); + wantToSignUp && this.convertMode(); + } + }); + }; + + signUp = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_UP, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + alert(`회원가입되었습니다!🎉 로그인해주세요`); + this.convertMode(); + } else { + alert(users.MESSAGE); + } + }); + }; + + render() { + const { inputId, inputPw, loginMode } = this.state; + const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/; + + return ( + <main className="loginYeseul give-border"> + <h1 className="logo">westagram</h1> + <form + className="login-form" + onSubmit={loginMode ? this.signIn : this.signUp} + > + <div className="login-form__input-box"> + <input + type="text" + name="inputId" + placeholder="전화번호, 사용자 이름 또는 이메일" + value={inputId} + onChange={this.handleInput} + /> + <input + type="password" + name="inputPw" + placeholder="비밀번호" + value={inputPw} + onChange={this.handleInput} + /> + </div> + <button + type="submit" + disabled={!(checkId.test(inputId) && inputPw.length > 8)} + > + {loginMode ? '로그인' : '회원가입'} + </button> + </form> + <a + href="https://www.instagram.com/accounts/password/reset/" + className="find-pw" + > + 비밀번호를 잊으셨나요? + </a> + </main> + ); + } +} + +export default withRouter(LoginYeseul);
JavaScript
디테일....👍👍
@@ -0,0 +1,140 @@ +import React, { Component } from 'react'; +import { Link } from 'react-router-dom'; +import User from '../User/User'; +import Comment from '../Comment/Comment'; +import IconButton from '../Button/IconButton'; +import { API } from '../../../../../config'; +import './Feed.scss'; + +class Feed extends Component { + constructor(props) { + super(props); + this.state = { + inputComment: '', + commentId: 0, + comments: [], + }; + } + + componentDidMount() { + const { feedId } = this.props; + fetch(API.COMMENT) + .then(comments => comments.json()) + .then(comments => { + this.setState({ + commentId: comments.length + 1, + comments: comments.filter(comment => comment.feedId === feedId), + }); + }); + } + + handleInput = e => { + this.setState({ inputComment: e.target.value }); + }; + + addComment = e => { + const { inputComment, commentId, comments } = this.state; + + e.preventDefault(); + this.setState({ + inputComment: '', + commentId: commentId + 1, + comments: [ + ...comments, + { + id: commentId.toString(), + writer: this.props.userName, + content: inputComment, + tagId: '', + }, + ], + }); + }; + + deleteComment = clickedId => { + const { comments } = this.state; + this.setState({ + comments: comments.filter(comment => comment.id !== clickedId), + }); + }; + + render() { + const { inputComment, comments } = this.state; + const { writer, contents } = this.props; + + return ( + <article className="feed give-border"> + <header className="feed__header"> + <User size="small" user={writer}> + <IconButton + className="feed__header__more-icon align-right" + info={{ name: '더보기', fileName: 'more.svg' }} + /> + </User> + </header> + <div className="feed__image"> + <img + alt={`by ${writer.name} on ${contents.date}`} + src={contents.postedImage} + /> + </div> + <div className="feed__btns"> + <button type="button"> + <img + alt="좋아요" + src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/bearu/heart.png" + /> + </button> + <IconButton info={{ name: '댓글', fileName: 'comment.svg' }} /> + <IconButton info={{ name: '공유하기', fileName: 'send.svg' }} /> + <IconButton + className="align-right" + info={{ name: '북마크', fileName: 'bookmark.svg' }} + /> + </div> + <p className="feed__likes-number"> + <Link to="/main-yeseul">{`좋아요 ${contents.likesNum}개`}</Link> + </p> + <div className="feed__description"> + <p> + <span className="user-name">{writer.name}</span> + <span>{contents.description}</span> + </p> + </div> + <div className="feed__comments"> + {comments.map(comment => ( + <Comment + key={comment.id} + info={comment} + handleClick={this.deleteComment} + /> + ))} + </div> + <form + className="feed__form align-item-center space-between" + name="commentForm" + > + <IconButton info={{ name: '이모티콘', fileName: 'emoticon.svg' }} /> + <input + type="text" + placeholder="댓글 달기..." + value={inputComment} + className="feed__input-comment" + name="inputComment" + onChange={this.handleInput} + /> + <input + type="submit" + className="feed__submit-comment" + name="submitComment" + value="게시" + disabled={!(inputComment.length > 0)} + onClick={this.addComment} + /> + </form> + </article> + ); + } +} + +export default Feed;
JavaScript
오홍 예슬님은 filter로 구현하셨네여! :)
@@ -0,0 +1,140 @@ +import React, { Component } from 'react'; +import { Link } from 'react-router-dom'; +import User from '../User/User'; +import Comment from '../Comment/Comment'; +import IconButton from '../Button/IconButton'; +import { API } from '../../../../../config'; +import './Feed.scss'; + +class Feed extends Component { + constructor(props) { + super(props); + this.state = { + inputComment: '', + commentId: 0, + comments: [], + }; + } + + componentDidMount() { + const { feedId } = this.props; + fetch(API.COMMENT) + .then(comments => comments.json()) + .then(comments => { + this.setState({ + commentId: comments.length + 1, + comments: comments.filter(comment => comment.feedId === feedId), + }); + }); + } + + handleInput = e => { + this.setState({ inputComment: e.target.value }); + }; + + addComment = e => { + const { inputComment, commentId, comments } = this.state; + + e.preventDefault(); + this.setState({ + inputComment: '', + commentId: commentId + 1, + comments: [ + ...comments, + { + id: commentId.toString(), + writer: this.props.userName, + content: inputComment, + tagId: '', + }, + ], + }); + }; + + deleteComment = clickedId => { + const { comments } = this.state; + this.setState({ + comments: comments.filter(comment => comment.id !== clickedId), + }); + }; + + render() { + const { inputComment, comments } = this.state; + const { writer, contents } = this.props; + + return ( + <article className="feed give-border"> + <header className="feed__header"> + <User size="small" user={writer}> + <IconButton + className="feed__header__more-icon align-right" + info={{ name: '더보기', fileName: 'more.svg' }} + /> + </User> + </header> + <div className="feed__image"> + <img + alt={`by ${writer.name} on ${contents.date}`} + src={contents.postedImage} + /> + </div> + <div className="feed__btns"> + <button type="button"> + <img + alt="좋아요" + src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/bearu/heart.png" + /> + </button> + <IconButton info={{ name: '댓글', fileName: 'comment.svg' }} /> + <IconButton info={{ name: '공유하기', fileName: 'send.svg' }} /> + <IconButton + className="align-right" + info={{ name: '북마크', fileName: 'bookmark.svg' }} + /> + </div> + <p className="feed__likes-number"> + <Link to="/main-yeseul">{`좋아요 ${contents.likesNum}개`}</Link> + </p> + <div className="feed__description"> + <p> + <span className="user-name">{writer.name}</span> + <span>{contents.description}</span> + </p> + </div> + <div className="feed__comments"> + {comments.map(comment => ( + <Comment + key={comment.id} + info={comment} + handleClick={this.deleteComment} + /> + ))} + </div> + <form + className="feed__form align-item-center space-between" + name="commentForm" + > + <IconButton info={{ name: '이모티콘', fileName: 'emoticon.svg' }} /> + <input + type="text" + placeholder="댓글 달기..." + value={inputComment} + className="feed__input-comment" + name="inputComment" + onChange={this.handleInput} + /> + <input + type="submit" + className="feed__submit-comment" + name="submitComment" + value="게시" + disabled={!(inputComment.length > 0)} + onClick={this.addComment} + /> + </form> + </article> + ); + } +} + +export default Feed;
JavaScript
id값으로 key props 할당 👍 💯 🥇