Skip to content

Commit

Permalink
Merge pull request #54 from DowaDream/fix/#53-social-login
Browse files Browse the repository at this point in the history
[FIX] 소셜로그인 에러
  • Loading branch information
sanghyunna authored Aug 17, 2023
2 parents f885a0e + a294189 commit 418d44d
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 48 deletions.
3 changes: 2 additions & 1 deletion config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,10 @@
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://127.0.0.1:3000",
"https://dowadream.site"
]

CSRF_TRUSTED_ORIGINS = ['https://api.dowadream.site']
CSRF_TRUSTED_ORIGINS = ['https://api.dowadream.site', 'https://dowadream.site']

ROOT_URLCONF = "config.urls"

Expand Down
2 changes: 1 addition & 1 deletion user/jwt_token.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from rest_framework_simplejwt.serializers import RefreshToken


def make_token(email, accept, user):
def make_token(email, user):
# accept_json = accept.json()
# accept_json.pop('user', None)
token = RefreshToken.for_user(user)
Expand Down
48 changes: 25 additions & 23 deletions user/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,23 @@
GOOGLE_CALLBACK_URI = BASE_URL + 'user/callback/'


### !!! access token 발급 !!! ###

### 구글 로그인 관련 ###
def get_google_access_token(code):
client_id = settings.GOOGLE_CLIENT_ID
client_secret = settings.GOOGLE_PASSWORD
state = "random_state"
# def get_google_access_token(code):
# client_id = settings.GOOGLE_CLIENT_ID
# client_secret = settings.GOOGLE_PASSWORD
# state = "random_state"

token_req = requests.post(f"https://oauth2.googleapis.com/token?client_id={client_id}&client_secret={client_secret}&code={code}&grant_type=authorization_code&redirect_uri={GOOGLE_CALLBACK_URI}&state={state}")
token_req_json = token_req.json()
error = token_req_json.get("error")
# token_req = requests.post(f"https://oauth2.googleapis.com/token?client_id={client_id}&client_secret={client_secret}&code={code}&grant_type=authorization_code&redirect_uri={GOOGLE_CALLBACK_URI}&state={state}")
# token_req_json = token_req.json()
# error = token_req_json.get("error")

if error is not None:
raise JSONDecodeError(error)
# if error is not None:
# raise JSONDecodeError(error)

access_token = token_req_json.get('access_token')
return access_token
# access_token = token_req_json.get('access_token')
# return access_token

def get_google_profile(access_token):
# 가져온 access_token으로 사용자 정보를 구글에 요청
Expand All @@ -42,30 +44,30 @@ def get_google_profile(access_token):


# 로그인
def google_callback_signin(data, user, email) -> ResponseDto:
accept = requests.post(f"{BASE_URL}user/login/finish/", data=data)
accept_status = accept.status_code
def google_callback_signin(user, email) -> ResponseDto:
# accept = requests.post(f"{BASE_URL}user/login/finish/", data=data)
# accept_status = accept.status_code

# 로그인 과정에서 문제가 생기면 에러
if accept_status != 200:
return ResponseDto(status=accept_status, msg=message['SignInFail'])
# if accept_status != 200:
# return ResponseDto(status=accept_status, msg=message['SignInFail'])

data = make_token(email, accept, user)
data = make_token(email, user)
return ResponseDto(status=200, msg=message['SignInSuccess'], data=data)


# 회원가입
def google_callback_signup(data, email, profile_img) -> ResponseDto:
accept = requests.post(f"{BASE_URL}user/login/finish/", data=data)
accept_status = accept.status_code
def google_callback_signup(email, profile_img) -> ResponseDto:
# accept = requests.post(f"{BASE_URL}user/login/finish/", data=data)
# accept_status = accept.status_code

if accept_status != 200:
return ResponseDto(status=accept_status, msg=message['SignUpFail'])
# if accept_status != 200:
# return ResponseDto(status=accept_status, msg=message['SignUpFail'])

user = User.objects.get(email=email)
user.profile_img = profile_img # profile_img 저장
user.save() # 변경 내용을 저장
data = make_token(email, accept, user)
data = make_token(email, user)
return ResponseDto(status=201, msg=message['SignUpSuccess'], data=data)


Expand Down
5 changes: 3 additions & 2 deletions user/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@

urlpatterns = [
# path('login/', google_login, name='google_login'),
path('callback/', google_callback, name='google_callback'),
path('login/finish/', GoogleLogin.as_view(), name='google_login_todjango'),
# path('callback/', google_callback, name='google_callback'),
# path('login/finish/', GoogleLogin.as_view(), name='google_login_todjango'),
path('get-token/', AccessTokenView.as_view()),

path('info/', UserInfoView.as_view()),
path('resol/', ResolMsgView.as_view()),
Expand Down
72 changes: 51 additions & 21 deletions user/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,35 +39,65 @@ def responseFactory(res: ResponseDto):

# 구글 로그인
# def google_login(request):
# scope = "https://www.googleapis.com/auth/userinfo.email "
# client_id = settings.GOOGLE_CLIENT_ID
# return redirect(f"https://accounts.google.com/o/oauth2/v2/auth?client_id={client_id}&response_type=code&redirect_uri={GOOGLE_CALLBACK_URI}&scope={scope}")
# scope = "https://www.googleapis.com/auth/userinfo.email "
# client_id = settings.GOOGLE_CLIENT_ID
# return redirect(f"https://accounts.google.com/o/oauth2/v2/auth?client_id={client_id}&response_type=code&redirect_uri={GOOGLE_CALLBACK_URI}&scope={scope}")


# Callback 함수
def google_callback(request):
code = request.GET.get('code')
access_token = get_google_access_token(code)
email, profile_img = get_google_profile(access_token)
# def google_callback(request):
# code = request.GET.get('code')
# access_token = get_google_access_token(code)
# print(access_token)
# return access_token
# email, profile_img = get_google_profile(access_token)

try:
user = User.objects.get(email=email)
# try:
# user = User.objects.get(email=email)

# 이미 Google로 제대로 가입된 유저 => 로그인
data = {'access_token': access_token, 'code': code}
res = google_callback_signin(data, user, email)
return responseFactory(res)
# # 이미 Google로 제대로 가입된 유저 => 로그인
# data = {'access_token': access_token, 'code': code}
# res = google_callback_signin(data, user, email)
# return responseFactory(res)

except User.DoesNotExist: # 회원가입
data = {'access_token': access_token, 'code': code}
res = google_callback_signup(data, email, profile_img)
return responseFactory(res)
# except User.DoesNotExist: # 회원가입
# data = {'access_token': access_token, 'code': code}
# res = google_callback_signup(data, email, profile_img)
# return responseFactory(res)


class GoogleLogin(SocialLoginView):
adapter_class = google_view.GoogleOAuth2Adapter
callback_url = GOOGLE_CALLBACK_URI
client_class = OAuth2Client
import json
class AccessTokenView(GenericAPIView):
def post(self, request):
try:
raw_data = request.body
decoded_data = raw_data.decode('utf-8')
json_data = json.loads(decoded_data)

google_access_token = json_data.get('access_token')
if google_access_token:
email, profile_img = get_google_profile(google_access_token)
try:
user = User.objects.get(email=email)

# 이미 Google로 제대로 가입된 유저 => 로그인
res = google_callback_signin(user, email)
return responseFactory(res)

except User.DoesNotExist: # 회원가입
res = google_callback_signup(email, profile_img)
return responseFactory(res)
else:
return Response({"error": "Access token not found in request body."}, status=status.HTTP_400_BAD_REQUEST)

except json.JSONDecodeError:
return Response({"error": "Invalid JSON format in request body."}, status=status.HTTP_400_BAD_REQUEST)


# class GoogleLogin(SocialLoginView):
# adapter_class = google_view.GoogleOAuth2Adapter
# callback_url = GOOGLE_CALLBACK_URI
# client_class = OAuth2Client


### 유저 관련
Expand Down

0 comments on commit 418d44d

Please sign in to comment.