def _get_sociallogin(user, provider): """ Returns an ready sociallogin object for the given auth provider. """ socialaccount = SocialAccount(user=user, uid='1234', provider=provider) socialaccount.extra_data = {'email': user.email} sociallogin = SocialLogin() sociallogin.account = socialaccount return sociallogin
def get_or_create_user(payload, oidc=False): user_id = payload.get('sub') if not user_id: msg = _('Invalid payload. sub missing') raise ValueError(msg) # django-helusers uses UUID as the primary key for the user # If the incoming token does not have UUID in the sub field, # we must synthesize one if not is_valid_uuid(user_id): # Maybe we have an Azure pairwise ID? Check for Azure tenant ID # in token and use that as UUID namespace if available namespace = payload.get('tid') user_id = convert_to_uuid(user_id, namespace) try_again = False try: user = _try_create_or_update(user_id, payload, oidc) except IntegrityError: # If we get an integrity error, it probably meant a race # condition with another process. Another attempt should # succeed. try_again = True if try_again: # We try again without catching exceptions this time. user = _try_create_or_update(user_id, payload, oidc) # If allauth.socialaccount is installed, create the SocialAcount # that corresponds to this user. Otherwise logins through # allauth will not work for the user later on. if 'allauth.socialaccount' in settings.INSTALLED_APPS: from allauth.socialaccount.models import SocialAccount, EmailAddress if oidc: provider_name = 'helsinki_oidc' else: provider_name = 'helsinki' args = {'provider': provider_name, 'uid': user_id} try: account = SocialAccount.objects.get(**args) assert account.user_id == user.id except SocialAccount.DoesNotExist: account = SocialAccount(**args) account.extra_data = payload account.user = user account.save() try: email = EmailAddress.objects.get(email__iexact=user.email) assert email.user == user except EmailAddress.DoesNotExist: email = EmailAddress(email=user.email.lower(), primary=True, user=user, verified=True) email.save() return user
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 _get_sociallogin(user, provider): """ Returns an ready sociallogin object for the given auth provider. """ socialaccount = SocialAccount( user=user, uid='1234', provider=provider, ) socialaccount.extra_data = {'email': user.email} sociallogin = SocialLogin() sociallogin.account = socialaccount return sociallogin
def get_or_create_user(payload, oidc=False): user_id = payload.get('sub') if not user_id: msg = _('Invalid payload.') raise exceptions.AuthenticationFailed(msg) try_again = False try: user = _try_create_or_update(user_id, payload, oidc) except IntegrityError: # If we get an integrity error, it probably meant a race # condition with another process. Another attempt should # succeed. try_again = True if try_again: # We try again without catching exceptions this time. user = _try_create_or_update(user_id, payload, oidc) # If allauth.socialaccount is installed, create the SocialAcount # that corresponds to this user. Otherwise logins through # allauth will not work for the user later on. if 'allauth.socialaccount' in settings.INSTALLED_APPS: from allauth.socialaccount.models import SocialAccount, EmailAddress if oidc: provider_name = 'helsinki_oidc' else: provider_name = 'helsinki' args = {'provider': provider_name, 'uid': user_id} try: account = SocialAccount.objects.get(**args) assert account.user_id == user.id except SocialAccount.DoesNotExist: account = SocialAccount(**args) account.extra_data = payload account.user = user account.save() try: email = EmailAddress.objects.get(email__iexact=user.email) assert email.user == user except EmailAddress.DoesNotExist: email = EmailAddress(email=user.email.lower(), primary=True, user=user, verified=True) email.save() return user
def dispatch(self, request): app = self.adapter.get_app(request) provider_id = self.adapter.provider_id try: uid, data, extra_data = self.adapter.get_user_info(request, app) except OAuthError: return render_authentication_error(request) try: account = SocialAccount.objects.get(provider=provider_id, uid=uid) except SocialAccount.DoesNotExist: account = SocialAccount(provider=provider_id, uid=uid) account.extra_data = extra_data if account.pk: account.save() return complete_social_login(request, data, account)
def dispatch(self, request): app = self.adapter.get_app(request) provider_id = self.adapter.provider_id try: uid, data, extra_data = self.adapter.get_user_info(request, app) except OAuthError: return render_authentication_error(request) try: account = SocialAccount.objects.get(provider=provider_id, uid=uid) except SocialAccount.DoesNotExist: account = SocialAccount(provider=provider_id, uid=uid) account.extra_data = extra_data if account.pk: account.save() return complete_social_login(request, data, account)
def get_or_create_user(payload, oidc=False): user_id = payload.get('sub') if not user_id: msg = _('Invalid payload.') raise exceptions.AuthenticationFailed(msg) try_again = False try: user = _try_create_or_update(user_id, payload, oidc) except IntegrityError: # If we get an integrity error, it probably meant a race # condition with another process. Another attempt should # succeed. try_again = True if try_again: # We try again without catching exceptions this time. user = _try_create_or_update(user_id, payload, oidc) # If allauth.socialaccount is installed, create the SocialAcount # that corresponds to this user. Otherwise logins through # allauth will not work for the user later on. if 'allauth.socialaccount' in settings.INSTALLED_APPS: from allauth.socialaccount.models import SocialAccount, EmailAddress if oidc: provider_name = 'helsinki_oidc' else: provider_name = 'helsinki' args = {'provider': provider_name, 'uid': user_id} try: account = SocialAccount.objects.get(**args) assert account.user_id == user.id except SocialAccount.DoesNotExist: account = SocialAccount(**args) account.extra_data = payload account.user = user account.save() try: email = EmailAddress.objects.get(email__iexact=user.email) assert email.user == user except EmailAddress.DoesNotExist: email = EmailAddress(email=user.email.lower(), primary=True, user=user, verified=True) email.save() return user
def get_or_create_user(payload, oidc=False): user_id = payload.get('sub') if not user_id: msg = _('Invalid payload.') raise exceptions.AuthenticationFailed(msg) user_model = get_user_model() with transaction.atomic(): try: user = user_model.objects.select_for_update().get(uuid=user_id) except user_model.DoesNotExist: user = user_model(uuid=user_id) user.set_unusable_password() update_user(user, payload, oidc) # If allauth.socialaccount is installed, create the SocialAcount # that corresponds to this user. Otherwise logins through # allauth will not work for the user later on. if 'allauth.socialaccount' in settings.INSTALLED_APPS: from allauth.socialaccount.models import SocialAccount, EmailAddress if oidc: provider_name = 'helsinki_oidc' else: provider_name = 'helsinki' args = {'provider': provider_name, 'uid': user_id} try: account = SocialAccount.objects.get(**args) assert account.user_id == user.id except SocialAccount.DoesNotExist: account = SocialAccount(**args) account.extra_data = payload account.user = user account.save() try: email = EmailAddress.objects.get(email__iexact=user.email) assert email.user == user except EmailAddress.DoesNotExist: email = EmailAddress(email=user.email.lower(), primary=True, user=user, verified=True) email.save() return user
def dispatch(self, request): if 'error' in request.GET or not 'code' in request.GET: # TODO: Distinguish cancel from error return render_authentication_error(request) app = self.adapter.get_app(self.request) client = self.get_client(request, app) provider_id = self.adapter.provider_id try: access_token = client.get_access_token(request.GET['code']) uid, data, extra_data = self.adapter.get_user_info( request, app, access_token) except OAuth2Error: return render_authentication_error(request) # TODO: DRY, duplicates OAuth logic try: account = SocialAccount.objects.get(provider=provider_id, uid=uid) except SocialAccount.DoesNotExist: account = SocialAccount(provider=provider_id, uid=uid) account.extra_data = extra_data if account.pk: account.save() return complete_social_login(request, data, account)
def dispatch(self, request): if 'error' in request.GET or not 'code' in request.GET: # TODO: Distinguish cancel from error return render_authentication_error(request) app = self.adapter.get_app(self.request) client = self.get_client(request, app) provider_id = self.adapter.provider_id try: access_token = client.get_access_token(request.GET['code']) uid, data, extra_data = self.adapter.get_user_info(request, app, access_token) except OAuth2Error: return render_authentication_error(request) # TODO: DRY, duplicates OAuth logic try: account = SocialAccount.objects.get(provider=provider_id, uid=uid) except SocialAccount.DoesNotExist: account = SocialAccount(provider=provider_id, uid=uid) account.extra_data = extra_data if account.pk: account.save() return complete_social_login(request, data, account)
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')