def create_logged_in_user(test, name, email, password="******", is_moderator=False, is_active=False): test.name = name # create use instance User = EmailUser user = User.objects.create_user(name=name, email=email, password=password) user.save() if is_active: user.profile.is_active = True user.profile.save() # make sure this user is in the staff group, too if is_staff_address(email): assign_group_policy(user, "staff") add_user_to_main_site(user) if is_moderator: assign_group_policy(user, "moderator") # log this user in for further testing purposes test.user = user test.client = JSONDefaultClient() test.client.force_login(user)
def populate_user(self, request, sociallogin, data): user = super().populate_user(request, sociallogin, data) name = data.get('name') user.name = ' '.join([ data.get('first_name', ''), data.get('last_name', '') ]).strip() if not name else name if sociallogin.account.provider == google_provider_id and is_staff_address(user_email(user)): user.is_staff = True return user
def post(self, request, *args, **kwargs): validation_result = post_validate(request) if validation_result is True: # invalidate the nonce, so this form cannot be # resubmitted with the current id request.session['nonce'] = False ''' If there is a thumbnail, and it was sent as part of an application/json payload, then we need to unpack a thumbnail object payload and convert it to a Python ContentFile payload instead. We use a try/catch because the optional nature means we need to check using "if hasattr(request.data,'thumbnail'):" as we as "if request.data['thumnail']" and these are pretty much mutually exclusive patterns. A try/pass make far more sense. ''' try: thumbnail = request.data['thumbnail'] # do we actually need to repack as ContentFile? if thumbnail['name'] and thumbnail['base64']: name = thumbnail['name'] encdata = thumbnail['base64'] proxy = ContentFile(base64.b64decode(encdata), name=name) request.data['thumbnail'] = proxy except: pass serializer = EntrySerializer(data=request.data) if serializer.is_valid(): user = request.user # ensure that the published_by is always the user doing # the posting, and set 'featured' to false. # # see https://github.com/mozilla/network-pulse-api/issues/83 moderation_state = ModerationState.objects.get(name='Pending') if (is_staff_address(request.user.email)): moderation_state = ModerationState.objects.get( name='Approved') savedEntry = serializer.save(published_by=user, featured=False, moderation_state=moderation_state) return Response({'status': 'submitted', 'id': savedEntry.id}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response("post validation failed", status=status.HTTP_400_BAD_REQUEST)
def populate_user(self, request, sociallogin, data): user = super().populate_user(request, sociallogin, data) name = data.get('name') if not name: first_name = data.get('first_name') or '' last_name = data.get('last_name') or '' name = f"{first_name} {last_name}".strip() user.name = name if name else 'Unnamed Pulse user' if sociallogin.account.provider == google_provider_id and is_staff_address(user_email(user)): user.is_staff = True return user
def create_logged_in_user(test, name, email, password="******"): test.name = name # create use instance User = EmailUser user = User.objects.create_user(name=name, email=email, password=password) user.save() # make sure this user is in the staff group, too if is_staff_address(email): assign_group_policy(user, "staff") add_user_to_main_site(user) # log this user in for further testing purposes test.user = user test.client = Client() test.client.force_login(user)
def callback(request, **kwargs): """ The callback route that Google will send the user to when authentication finishes (with successfully, or erroneously). """ if 'state' not in request.session: msg = '\n'.join([ 'ERROR: No state key found in request.session!', 'Are you making doubly sure your initial domain and callback domain are the same domain?' ]) print(msg) return HttpResponseNotFound(msg) error = request.GET.get('error', False) auth_code = request.GET.get('code', False) if error is not False: return HttpResponse("login failed: " + str(error)) if auth_code is not False: state = request.GET.get('state', False) if state is False: return HttpResponse( "Questionable login: missing state value in callback.") if state != request.session['state']: return HttpResponse( "Questionable login: incorrect state value in callback.") # get the authenticating user's name and email address from the Google API credentials = FlowHandler.get_flow().step2_exchange(auth_code) http_auth = credentials.authorize(Http()) # get a user's full name service = build('oauth2', 'v2', http=http_auth) userinfo = service.userinfo().get().execute() name = userinfo['name'] email = userinfo['email'] if settings.ALLOW_UNIVERSAL_LOGIN is None: # Any user outside of the cleared mozilla domains is redirected to the main page. if not is_staff_address(email): return do_final_redirect(state, False, "Domain not in whitelist") try: # Get the db record for this user and make sure their # name matches what google says it should be. user = EmailUser.objects.get(email=email) # Just to be safe, we rebind the user's name, as this may have # changed since last time we saw this user. user.name = name user.save() except EmailUser.DoesNotExist: # Create a new database entry for this user. user = EmailUser.objects.create_user(name=name, email=email) # As this user just authenticated, we mark this user as logged in # for the duration of this session. login(request, user) return do_final_redirect(state, True, "User logged in") return HttpResponseNotFound( "callback happened without an error or code query argument: this should not be possible." )
def post(self, request, *args, **kwargs): request_data = request.data user = request.user if hasattr(request, 'user') else None validation_result = post_validate(request) if validation_result: # invalidate the nonce, so this form cannot be # resubmitted with the current id request.session['nonce'] = False ''' If there is a thumbnail, and it was sent as part of an application/json payload, then we need to unpack a thumbnail object payload and convert it to a Python ContentFile payload instead. We use a try/catch because the optional nature means we need to check using "if hasattr(request.data,'thumbnail'):" as we as "if request.data['thumnail']" and these are pretty much mutually exclusive patterns. A try/pass make far more sense. ''' try: thumbnail = request_data['thumbnail'] # do we actually need to repack as ContentFile? if thumbnail['name'] and thumbnail['base64']: name = thumbnail['name'] encdata = thumbnail['base64'] proxy = ContentFile(base64.b64decode(encdata), name=name) request_data['thumbnail'] = proxy except KeyError: pass # we also want to make sure that tags are properly split # on commas, in case we get e.g. ['a', 'b' 'c,d'] if 'tags' in request_data: tags = request_data['tags'] filtered_tags = [] for tag in tags: if ',' in tag: filtered_tags = filtered_tags + tag.split(',') else: filtered_tags.append(tag) request_data['tags'] = filtered_tags serializer = self.get_serializer_class()( data=request_data, context={ 'user': user }, ) if serializer.is_valid(): # ensure that the published_by is always the user doing # the posting, and set 'featured' to false. # # see https://github.com/mozilla/network-pulse-api/issues/83 moderation_state = ModerationState.objects.get(name='Pending') if is_staff_address(user.email): moderation_state = ModerationState.objects.get( name='Approved') # save the entry saved_entry = serializer.save( published_by=user, featured=False, moderation_state=moderation_state) return Response({'status': 'submitted', 'id': saved_entry.id}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response( "post validation failed - {}".format(validation_result), status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): request_data = request.data validation_result = post_validate(request) if validation_result is True: # invalidate the nonce, so this form cannot be # resubmitted with the current id request.session['nonce'] = False ''' If there is a thumbnail, and it was sent as part of an application/json payload, then we need to unpack a thumbnail object payload and convert it to a Python ContentFile payload instead. We use a try/catch because the optional nature means we need to check using "if hasattr(request.data,'thumbnail'):" as we as "if request.data['thumnail']" and these are pretty much mutually exclusive patterns. A try/pass make far more sense. ''' try: thumbnail = request_data['thumbnail'] # do we actually need to repack as ContentFile? if thumbnail['name'] and thumbnail['base64']: name = thumbnail['name'] encdata = thumbnail['base64'] proxy = ContentFile(base64.b64decode(encdata), name=name) request_data['thumbnail'] = proxy except: pass # we need to split out creators, because it's a many-to-many # relation with a Through class, so that needs manual labour: creator_data = request_data.pop('creators', []) # we also want to make sure that tags are properly split # on commas, in case we get e.g. ['a', 'b' 'c,d'] if 'tags' in request_data: tags = request_data['tags'] filtered_tags = [] for tag in tags: if ',' in tag: filtered_tags = filtered_tags + tag.split(',') else: filtered_tags.append(tag) request_data['tags'] = filtered_tags serializer = EntrySerializer( data=request_data, context={'request': request}, ) if serializer.is_valid(): user = request.user # ensure that the published_by is always the user doing # the posting, and set 'featured' to false. # # see https://github.com/mozilla/network-pulse-api/issues/83 moderation_state = ModerationState.objects.get(name='Pending') if (is_staff_address(request.user.email)): moderation_state = ModerationState.objects.get( name='Approved') # save the entry saved_entry = serializer.save( published_by=user, featured=False, moderation_state=moderation_state) # QUEUED FOR DEPRECATION: Use the `related_creators` property instead. # See https://github.com/mozilla/network-pulse-api/issues/241 if len(creator_data) > 0: for creator_name in creator_data: (creator, _) = Creator.objects.get_or_create(name=creator_name) OrderedCreatorRecord.objects.create(entry=saved_entry, creator=creator) return Response({'status': 'submitted', 'id': saved_entry.id}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response( "post validation failed - {}".format(validation_result), status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): request_data = request.data validation_result = post_validate(request) if validation_result is True: # invalidate the nonce, so this form cannot be # resubmitted with the current id request.session['nonce'] = False ''' If there is a thumbnail, and it was sent as part of an application/json payload, then we need to unpack a thumbnail object payload and convert it to a Python ContentFile payload instead. We use a try/catch because the optional nature means we need to check using "if hasattr(request.data,'thumbnail'):" as we as "if request.data['thumnail']" and these are pretty much mutually exclusive patterns. A try/pass make far more sense. ''' try: thumbnail = request_data['thumbnail'] # do we actually need to repack as ContentFile? if thumbnail['name'] and thumbnail['base64']: name = thumbnail['name'] encdata = thumbnail['base64'] proxy = ContentFile(base64.b64decode(encdata), name=name) request_data['thumbnail'] = proxy except: pass # we need to split out creators, because it's a many-to-many # relation with a Through class, so that needs manual labour: creator_data = request_data.pop('creators', None) serializer = EntrySerializer(data=request_data) if serializer.is_valid(): user = request.user # ensure that the published_by is always the user doing # the posting, and set 'featured' to false. # # see https://github.com/mozilla/network-pulse-api/issues/83 moderation_state = ModerationState.objects.get( name='Pending' ) if (is_staff_address(request.user.email)): moderation_state = ModerationState.objects.get( name='Approved' ) # save the entry saved_entry = serializer.save( published_by=user, featured=False, moderation_state=moderation_state ) # create entry/creator intermediaries if creator_data is not None: for creator_name in creator_data: # TODO: update Creator model so that it can fall through # to a profile is the correct format to achieve this # is specified. (creator, _) = Creator.objects.get_or_create(name=creator_name) OrderedCreatorRecord.objects.create( entry=saved_entry, creator=creator ) return Response({'status': 'submitted', 'id': saved_entry.id}) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) else: return Response( "post validation failed", status=status.HTTP_400_BAD_REQUEST )