def join(request): current_user = request.session.get('current_user', None) socialaccount_sociallogin = request.session.get('socialaccount_sociallogin', None) if not current_user and not socialaccount_sociallogin: raise Http404 if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): password = '******'+str(uuid.uuid4()).replace("-", "") # 유저 생성 user = User.objects.create(email=request.POST.get('email'), password=password) mailing_agree = request.POST.get('mailing_agree', None) # 소셜 정보 생성 social_auth = SocialAccount() if current_user: social_user = request.session['current_user']['obj'] social_auth.provider = 'soundcloud' social_auth.uid = social_user['id'] user.username = social_user['username'] user.soundcloud_url = social_user['permalink_url'] user.profile_picture = social_user['avatar_url'] social_auth.user_id = user.id if socialaccount_sociallogin: social_user = request.session['socialaccount_sociallogin']['account'] social_auth.provider = social_user['provider'] social_auth.uid = social_user['uid'] social_auth.user_id = user.id if 'naver' in social_user['provider']: user.username = social_user['extra_data'].get('name', social_user['extra_data']['nickname']) user.profile_picture = social_user['extra_data'].get('profile_image', '') else: user.username = social_user['extra_data'].get('name', '') social_auth.save() if mailing_agree and 'on' in mailing_agree: user.mailing_agree = True user.last_login = datetime.now() user.save() auth_login(request, user, backend='django.contrib.auth.backends.ModelBackend') # 콜백 # msg = settings.SOCIAL_AUTH_LOGIN_REDIRECT_URL+"#status=success&access_token="+get_user_token(user.id) return auth_redirect(request, "#status=success&access_token="+get_user_token(user.id)) # return redirect('//dopehotz.com'+msg) else: form = UserForm() return render(request, 'accounts/join_form.html', {'form': form, 'main_site' : settings.MAIN_URL})
def dispatch(self, request, *args, **kwargs): """ Override allauth's dispatch method to transparently just login if the email already exists. By doing this in dispatch, we can check for existing email, and if a match is found, associate the social account with that user and log them in. Allauth does not provide a mechanism for doing precisely this. """ ret = super().dispatch(request, *args, **kwargs) # By calling super().dispatch first, we set self.sociallogin try: # The email is contained in sociallogin.account.extra_data extra_data = self.sociallogin.account.extra_data except AttributeError: return ret # extract email email = extra_data["email"] if email_address_exists(email): # check that email exists. # If the email does exist, and there is a social account associated # with the user, then we don't have to do anything else if not self.sociallogin.is_existing: # However, if the email exists, and there isn't a social # account associated with that user, we need to associate the # social account # Allauth would perform this as part of the form.save step, but # we are entirely bypassing the form. account_emailaddress = EmailAddress.objects.get(email=email) self.sociallogin.user = account_emailaddress.user # allauth (and us) uses the sociallogin user as a temporary # holding space, and it already is largely filled out by # allauth; we just need to set the user. # This model does not get saved to the database. # We're trusting social provided emails already account_emailaddress.verified = True account_emailaddress.save() if not SocialAccount.objects.filter( uid=self.sociallogin.account.uid, provider=self.sociallogin.account.provider, ).exists(): # just to be on the safe side, double check that the account # does not exist in the database and that the provider is # valid. socialaccount = SocialAccount() socialaccount.uid = self.sociallogin.account.uid socialaccount.provider = self.sociallogin.account.provider socialaccount.extra_data = extra_data socialaccount.user = self.sociallogin.user socialaccount.save() return complete_social_login(request, self.sociallogin) return ret
def register_user(request): try: if request.method == 'POST': req_body = json.loads(request.body.decode()) UserModel = get_user_model() user = UserModel.objects.get( auth0_identifier=req_body['auth0_identifier']) user.first_name = req_body['first_name'] user.last_name = req_body['last_name'] user.username = req_body['username'] user.email = req_body['email'] password = request.user.auth0_identifier.split('.')[1] user.set_password(password) user.save() new_userprofile = UserProfile.objects.create( address=req_body["address"], user=user) new_userprofile.save() # email = req_body['email'] authenticated_user = authenticate( auth0_identifier=req_body['auth0_identifier'], password=password) if authenticated_user is not None: remote_authenticated_user = request.successful_authenticator.authenticate( request) if remote_authenticated_user is not None: management_api_token_endpoint = management_api_oath_endpoint( AUTH0_DOMAIN) management_api_token = json.loads( management_api_token_endpoint) management_api_jwt = management_api_token['access_token'] management_api_user = get_management_api_user( AUTH0_DOMAIN, management_api_jwt, req_body['uid']) token = TokenModel.objects.create( user=remote_authenticated_user[0]) key = token.key extra_data = req_body['extra_data'] extra_data['access_token'] = remote_authenticated_user[1] id_token = json.loads(req_body['id_token']) extra_data['id_token__raw'] = id_token['__raw'] nonce = id_token['nonce'] identities = management_api_user.get('identities')[0] provider = identities.get('provider') # The 'connection' in the auth0 returned result assoc_type = identities.get('connection') exp = id_token['exp'] iat = id_token['iat'] backend_data = backends(request) user_current_backend = authenticated_user.backend #auth0_backend = backend_data['backends']['backends'][1] #openId_backend = backend_data['backends']['backends'][0] #associated_backends = backend_data['backends'].get('associated') # return csrf token for POST form. side effect is have @csrf_protect csrf = req_body[ 'csrf_token'] if 'csrf_token' in req_body and req_body[ 'csrf_token'] else get_token(request) auth0_user_logs = retrieve_user_logs( AUTH0_DOMAIN, management_api_jwt, req_body['uid']) seacft = [ l for l in auth0_user_logs if l['type'] == 'seacft' ] seacft_details = seacft[0].get('details') code = seacft_details.get('code') # ss = [l for l in auth0_user_logs if l['type'] == 'ss'] # ss_details = ss[0].get('details') # transaction = ss_details['body']['transaction'] # associate_user('openid', social_user.uid, authenticated_user, social_user) social_user = remote_authenticated_user[ 0].social_auth.get_or_create( user_id=remote_authenticated_user[0].id, provider=provider, extra_data=extra_data, uid=req_body['auth0_identifier'].replace(".", "|")) # is_association = Association.objects.filter(server_url=AUTH0_OPEN_ID_SERVER_URL, handle=handle).exists() if Association.objects.filter( server_url=AUTH0_OPEN_ID_SERVER_URL, handle=nonce).exists(): user_association = Association.objects.get( server_url=AUTH0_OPEN_ID_SERVER_URL, handle=nonce) else: user_association = Association.objects.create( server_url=AUTH0_OPEN_ID_SERVER_URL, handle=nonce, secret=code, issued=iat, lifetime=exp, assoc_type=assoc_type) social_account = SocialAccount() social_account.user = remote_authenticated_user[0] social_account.uid = req_body['uid'] social_account.provider = provider social_account.extra_data = management_api_user social_account.save() account_email = EmailAddress.objects.get_or_create( user=social_account.user, email=authenticated_user.email, verified=True, primary=True) Nonce.objects.create(server_url=AUTH0_OPEN_ID_SERVER_URL, timestamp=iat, salt=nonce) Code.objects.create(email=account_email[0], code=code, verified=True) social_app = SocialApp.objects.get_or_create( provider=provider, name="Quantum Coasters", secret=SOCIAL_AUTH_AUTH0_SECRET, client_id=AUTH0_CLIENT_ID, key=SOCIAL_AUTH_AUTH0_KEY) time_now = datetime.datetime.now() expires_at = time_now + datetime.timedelta(0, exp) # time = expires_at.time() social_token = SocialToken.objects.create( app_id=social_app[0].id, account_id=social_account.id, token=id_token, token_secret=id_token['__raw'], expires_at=expires_at) # Changed from user to authenticated_user login(request, social_user[0].user, backend='quantumapi.auth0_backend.Auth0') current_user_session = request.session is_session = Session.objects.filter( session_key=current_user_session.session_key).exists() if is_session: session = Session.objects.get( session_key=current_user_session.session_key) else: session = Session.objects.create( user=authenticated_user) # session.save() EmailConfirmation.objects.get_or_create( email_address=account_email[0], key=session.session_key, sent=datetime.datetime.now()) # Turning into Set then back to List to filter out Duplicates (#ToDo-not needed.) social_app_to_list = list(social_app) social_app_data = social_app_to_list[0] auth_user = { "valid": True, "id": user.id, "first_name": user.first_name, "last_name": user.last_name, "email": user.email, "username": user.username, "is_staff": user.is_staff, "auth0_identifier": user.auth0_identifier, "QuantumToken": key, "session": session.session_key, 'csrf': csrf, 'user_social_auth_id': social_user[0].id, 'account_email_id': account_email[0].id, 'management_user': management_api_user, 'social_account_id': social_account.id, 'social_app_id': social_app_data.id, 'social_app_name': social_app_data.name, "social_token_id": social_token.id, 'association_id': user_association.id, 'email_confirmation': True, 'user_profile_id': new_userprofile.id, } data = json.dumps({"DjangoUser": auth_user}) return HttpResponse(data, content_type='application/json') else: error = "Remote authentication failed. Remote Authenticated User was None." data = json.dumps({"Remote Authentication Error": error}) return HttpResponse(data, content_type='application/json') else: error = "Authentication failed. Authenticated User was None." data = json.dumps({"Authentication Error": error}) return HttpResponse(data, content_type='application/json') except Exception as ex: return Response(ex.args, content_type='application/json')