def vote(request, id): option = Options.objects.get(id=id) poll = Polls.objects.get(id=option.poll_id) option_vote = OptionsVotes.objects.filter(poll_id=poll.id, user_ip=get_client_ip(request)) if option_vote.count() > 0: c = Context({ 'error': u'Вы уже голосовали в этом опросе', 'user': request.user, 'backlink': '/poll/%i/' % poll.id }) print poll.id return render_to_response('error.html', c) else: option.count += 1 option.save() ov = OptionsVotes() ov.poll_id = poll.id ov.vote_id = option.id ov.user_ip = get_client_ip(request) ov.save() cache.delete('polls_objects_get_id_%s' % poll.id) return HttpResponseRedirect('/poll/%i' % poll.id)
def post(self, request, pk): ''' Send authentication emails to the whole census ''' permission_required(request.user, 'AuthEvent', ['edit', 'send-auth'], pk) data = {'msg': 'Sent successful'} # first, validate input e = get_object_or_404(AuthEvent, pk=pk) try: req = parse_json_request(request) except: return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) userids = req.get("user-ids", None) if userids is None: permission_required(request.user, 'AuthEvent', ['edit', 'send-auth-all'], pk) extra_req = req.get('extra', {}) auth_method = req.get("auth-method", None) # force extra_req type to be a dict if not isinstance(extra_req, dict): return json_response( status=400, error_codename=ErrorCodes.BAD_REQUEST) if req.get('msg', '') or req.get('subject', ''): config = {} if req.get('msg', ''): config['msg'] = req.get('msg', '') if req.get('subject', ''): config['subject'] = req.get('subject', '') else: send_error = census_send_auth_task( pk, get_client_ip(request), None, userids, auth_method, request.user.id, **extra_req) if send_error: return json_response(**send_error) return json_response(data) if config.get('msg', None) is not None: if type(config.get('msg', '')) != str or len(config.get('msg', '')) > settings.MAX_AUTH_MSG_SIZE[e.auth_method]: return json_response( status=400, error_codename=ErrorCodes.BAD_REQUEST) send_error = census_send_auth_task( pk, get_client_ip(request), config, userids, auth_method, request.user.id, **extra_req) if send_error: return json_response(**send_error) return json_response(data)
def init_db(): if app.config["DB_CREATED"]: app.logger.warning("Someone (%s) tried to access init_db" % get_client_ip()) return redirect(url_for("show_index")) else: db.create_all() app.logger.info("%s created database tables with /init_db" % get_client_ip()) flash("Database created, please update config.py") return redirect(url_for("show_index"))
def init_db(): if app.config['DB_CREATED']: app.logger.warning('Someone (%s) tried to access init_db' % get_client_ip()) return redirect( url_for('show_index') ) else: db.create_all() app.logger.info('%s created database tables with /init_db' % get_client_ip()) flash('Database created, please update config.py') return redirect( url_for('show_index') )
def get(self, request, username=None, format=None): ip = utils.get_client_ip(request) utils.start_method_log('ProfileViewSet: get', username=request.user.username, ip=ip) if username is None: user = request.user serializer = ProfileSerializer( user, context={'request_user': request.user}) data = serializer.data return self._response(data, request) else: user = User.objects.filter(username=username).first() if user is None: response_content = {"detail": "User not Found"} return Response(response_content, status.HTTP_404_NOT_FOUND) serializer = ProfileSerializer( user, context={'request_user': request.user}) data = serializer.data data.pop('email', None) return self._response(data, request)
def post(self, request, format=None): ip = utils.get_client_ip(request) utils.start_method_log('SetProfilePicViewSet: post', username=request.user.username, ip=ip) if request.FILES.get('profile_picture'): try: utils.validate_image(request.FILES.get('profile_picture')) except ValidationError as e: data = {"error": e} logger.info( "SetProfilePicViewSet: post " "(Profile picture is not valid) username:{}, ip: {}". format(request.user.username, ip)) return Response(data=data, status=status.HTTP_400_BAD_REQUEST) user = request.user user.profile_picture = request.FILES.get('profile_picture') user.save() logger.info( "SetProfilePicViewSet: post " "(Profile picture successfully changed.) username:{}, ip: {}". format(request.user.username, ip)) return Response(data={}, status=status.HTTP_200_OK) else: data = {"error": ["Profile picture is required."]} logger.info( "SetProfilePicViewSet: post " "(Profile picture is required.) username:{}, ip: {}".format( request.user.username, ip)) return Response(data=data, status=status.HTTP_400_BAD_REQUEST)
def on_answer(self, request, dnsr=None, dnsq=None): headers = CIMultiDict() if dnsr is None: ttl = 300 dnsr = dns.message.make_response(dnsq) dnsr.answer.append( dns.rrset.from_text(str(dnsq.question[0].name), ttl, 'IN', 'A', '0.0.0.0')) headers["cache-control"] = "max-age={}".format(ttl) #dnsr.set_rcode(dns.rcode.SERVFAIL) elif len(dnsr.answer): ttl = min(r.ttl for r in dnsr.answer) headers["cache-control"] = "max-age={}".format(ttl) clientip = utils.get_client_ip(request.transport) interval = int((time.time() - self.time_stamp) * 1000) self.logger.info("[HTTPS] {} (Original IP: {}) {} {}ms".format( clientip, request.headers.getall('X-Forwaded-For'), utils.dnsans2log(dnsr), interval)) if request.method == "HEAD": body = b"" else: body = dnsr.to_wire() return aiohttp.web.Response( status=200, body=body, content_type=constants.DOH_MEDIA_TYPE, headers=headers, )
def post(self, request, format=None): ip = utils.get_client_ip(request) utils.start_method_log('likeAPI: get', username=request.user.username, ip=ip) data = request.data errors = {} try: CommentAPIView._validate_data(request, data) except ValidationError as e: errors['details'] = list(e.messages) return Response(errors, status=status.HTTP_400_BAD_REQUEST) post_id = data.get('post_id') content = data.get('content') post = Posts.objects.get(id=post_id) try: comment = Comment.objects.create(user=request.user, post=post, content=content) except: return Response({"details": 'comment already exists.'}, status=status.HTTP_400_BAD_REQUEST) if request.user != post.owner: comment_notification(request.user.id, post.owner.id, post.id, content) return Response({'details': 'created'}, status=status.HTTP_201_CREATED)
def create_image(filename, data, request): '''create an image from data and request''' from mimetypes import guess_type from StringIO import StringIO try: if not utils.is_image(data): print 'data is not image' return None try: name, dot, ext = filename.partition('.') if len(ext) > 4: ext = "jpg" except: ext = "jpg" img = Image() img.ext = ext img.mime = guess_type(filename)[0] img.ip = utils.get_client_ip(request) #create thumbs and reduce size if necessary data = create_thumb_and_reduce_size(img, data) img.image.put(data, filename=img.uid + "." + img.ext, content_type=img.mime) if request.user.is_authenticated(): img.user = request.user img.edited = datetime.now() img.save() except Exception, what: print repr(what) return None
def post(self, request): ip = utils.get_client_ip(request) utils.start_method_log("CreateNewBoardApiView: post", username=request.user.username, ip=ip) data = request.data.copy() data['owner'] = request.user.id serializer = CreateNeqBoardSerializer(data=data) if serializer.is_valid(): try: board = Board.objects.create( owner=request.user, name=serializer.data.get('name') ) except IntegrityError: return Response( data={"details": "This object already exist."}, status=status.HTTP_400_BAD_REQUEST ) logger.info('CreateNewBoardApiView: post ' '(created successfully) username:{}, ip: {}'.format( request.user.username, ip)) return Response( data={ "id": board.id }, status=status.HTTP_201_CREATED ) else: logger.info('CreateNewBoardApiView: post ' '(Request is not good.) username:{}, ip: {}'.format( request.user.username, ip)) return Response(status=status.HTTP_400_BAD_REQUEST)
def post(self, request): ip = utils.get_client_ip(request) utils.start_method_log('ForgotPasswordVerfication: post', ip=ip) token = request.data.get('token') if token is None: logger.info('ForgotPasswordVerfication: ' 'post (Token is required. ip: {})'.format(ip)) return Response(data={"details": "Token is required."}, status=status.HTTP_400_BAD_REQUEST) try: token_query_set = Token.objects.get(key=token) except ObjectDoesNotExist: logger.info('ForgotPasswordVerfication: ' 'post (Token not found. ip: {})'.format(ip)) return Response(data={"details": "Token not found."}, status=status.HTTP_404_NOT_FOUND) token_time = int(token_query_set.created_time.strftime("%Y%m%d%H%M")) now_time = int(datetime.datetime.now().strftime("%Y%m%d%H%M")) ok_time = now_time - token_time # One day = 10,000 if ok_time <= 10000: logger.info('ForgotPasswordVerfication: ' 'post (Token is valid. ip: {})'.format(ip)) return Response(data={"details": "Token is valid"}, status=status.HTTP_200_OK) else: token_query_set.delete() logger.info('ForgotPasswordVerfication: post ' '(Token is invalid. ip: {})'.format(ip)) return Response(data={"details": "Token is invalid"}, status=status.HTTP_401_UNAUTHORIZED)
def check_pipeline(request, ae, step='register', default_pipeline=None): req = json.loads(request.body.decode('utf-8')) if req.get('tlf'): req['tlf'] = get_cannonical_tlf(req['tlf']) data = { 'ip_addr': get_client_ip(request), 'tlf': req.get('tlf', None), 'code': req.get('code', None), 'auth_event': ae } pipeline = ae.auth_method_config.get('pipeline').get('%s-pipeline' % step) if pipeline is None: if default_pipeline is None: return error(message="no pipeline", status=400, error_codename="no-pipeline") pipeline = default_pipeline for pipe in pipeline: check = getattr(eval(pipe[0]), '__call__')(data, **pipe[1]) if check: data.update(json.loads(check.content.decode('utf-8'))) data['status'] = check.status_code if data.get('auth_event'): data.pop('auth_event') if data.get('code'): data.pop('code') return data return RET_PIPE_CONTINUE
def put(self, request, *args, **kwargs): ip = utils.get_client_ip(request) utils.start_method_log('ChangePassword: put', username=request.user.username, ip=ip) object = self.get_object() serializer = UserChangePasswordSerializer(data=request.data) if serializer.is_valid(): old_password = serializer.data.get("old_password") new_password = serializer.data.get("new_password") if not object.check_password(old_password): logger.info( 'ChangePassword: put (username: {} old password is wrong ip: {})' .format(request.user.username, ip)) return Response({"details": ["The old password was wrong!"]}, status=status.HTTP_400_BAD_REQUEST) object.set_password(new_password) object.save() logger.info( 'ChangePassword: put (username: {} password changed! ip: {})'. format(request.user.username, ip)) res = {'details': 'The password changed.'} return Response(res, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): try: slug = self.kwargs['slug'] rsvp_form = RSVPForm(request.POST) event = get_object_or_404(Event, slug=slug ) if not rsvp_form.is_valid(): # THis is so that we maintain state # The previous filled form is not lost variables = {'form': rsvp_form, 'event': event } return render(request, self.template_name, variables ) # Validate the CAPTCHA try: captcha_resp = request.REQUEST['g-recaptcha-response'] except: variables = {'form': rsvp_form, 'event': event } return render(request, self.template_name, variables ) remote_ip = utils.get_client_ip(request) captcha_validity = utils.validateCaptcha(captcha_resp, remote_ip) if not captcha_validity: rsvp_form.add_error('captcha_field_hidden',"reCAPTCHA is not complete or incorrect. Complete the CAPTCHA to proceed") variables = {'form': rsvp_form, 'event': event } return render(request, self.template_name, variables ) # Pulling out values from the request guest_email = request.REQUEST['your_email'] guest_name = request.REQUEST['name'] guest_associated_organization = request.REQUEST['associated_organization'] guest_attending_status = request.REQUEST['will_you_be_attending'] guest_is_student = request.REQUEST['are_you_a_student'] guest_wants_updates = False # We have to do this since the field is a Boolean check box. # Not clicking true is going to not return anything if request.REQUEST.has_key('receive_email_updates_for_this_event'): guest_wants_updates = request.REQUEST['receive_email_updates_for_this_event'] # Getting current RSVP count so that we are not above limit rsvp_count = Guest.objects.filter(Q(attending_status='yes') & Q(event_id=event.id)).count() if rsvp_count >= event.maximum_attendees: return HttpResponseRedirect('/rsvp/event/%s/full/' % slug ) # Checking if this email ID has been used to RSVP before is_guest_present = Guest.objects.filter(Q(email=guest_email) & Q(event_id=event.id)) if is_guest_present: return HttpResponseRedirect('/rsvp/event/%s/duplicate/' % slug ) Guest.objects.create(event=event, email=guest_email, name=guest_name, attending_status=guest_attending_status,associated_organization=guest_associated_organization, is_student=guest_is_student, wants_updates= guest_wants_updates) # If denied RSVP if guest_attending_status.lower() == 'no': return HttpResponseRedirect('/rsvp/event/%s/deniedrsvp/' % slug ) # Accept RSVP. if guest_wants_updates: venue_info = [event.hosted_by, event.street_address, event.city, event.state ] utils.sendConfirmationEmail(guest_email, guest_name, event.title, event.description, localtime(event.date_of_event), venue_info, event.speaker) return HttpResponseRedirect('/rsvp/event/%s/thanks/' % slug ) except Exception, exp: print "Exception: ",exp return HttpResponseRedirect('/rsvp/event/%s/failed/' % slug )
def post(self, request): ip = utils.get_client_ip(request) utils.start_method_log('DeleteBoard: post', username=request.user.username, ip=ip) data = request.data errors = {} try: DeleteBoard._validate_data(request, data) except ValidationError as e: errors['details'] = list(e.messages) return Response(errors, status=status.HTTP_400_BAD_REQUEST) board_id = request.data.get('board_id') Board.objects.filter(id=board_id).delete() logger.info('DeleteBoard: delete!' 'board: {board},' 'username: {username},' 'ip:{ip}'.format(board=board_id, username=request.user.username, ip=ip)) r_data = {'details': 'Board deleted'} return Response(r_data, status.HTTP_200_OK)
def create(self, request): activity_id = request.POST.get("activity_id", 0) text = request.POST.get("text", "") service = request.POST.get("service", "dev") try: #TODO 检查用户是否有权限发布消息 activity = Activity.objects.get(pk=activity_id) except Activity.DoesNotExist: activity = None if not activity: return rc.NOT_FOUND if "" == text: empty = rc.BAD_REQUEST empty.write("Text can not empty.") return empty ip_address = utils.get_client_ip(request) chat = Chat(user=request.user, activity=activity, text=text, \ ip=ip_address) chat.save() notification = push_models.Notification(message=text) notification.extra = {\ 'activity_id': activity_id, 'chat_id': chat.id, 'user_id': request.user.id, 'chat_text': text, 'type': 'chat', } devices = activity.devices(service, exclude=[request.user]) send_notification(devices, service, notification) return chat
def post_comment(request): if not request.user.is_authenticated(): if (request.POST['security'] != request.session['expected'] or not request.POST['name'] or not request.POST['password']): return HttpResponseForbidden() if not request.POST['body'] or not request.POST['post']: return HttpResponseForbidden() post = get_object_or_404(Post, pk=int(request.POST['post'])) comment = Comment(post=post) if request.user.is_authenticated(): comment.author = request.user comment.name = request.user.username else: comment.name = request.POST['name'] password = request.POST['password'].encode('utf-8') comment.password = bcrypt.hashpw(password, bcrypt.gensalt()) if request.POST['parent']: parent = get_object_or_404(Comment, pk=int(request.POST['parent'])) comment.parent = parent comment.comment = request.POST['body'] comment.ip_address = get_client_ip(request) comment.save() return redirect(reverse('post-read', kwargs={'slug': post.slug}))
def get(self, request, format=None): ip = utils.get_client_ip(request) utils.start_method_log('FeedAPI: get', username=request.user.username, ip=ip) user = request.user page = request.GET.get('page') url = str(request.scheme) + '://' + request.get_host() + MEDIA_URL posts_of_followers = Posts.objects.filter(owner__following__user=user) posts_of_user = Posts.objects.filter(owner=user) posts = (posts_of_followers | posts_of_user).distinct().order_by("-time") serializer = GetPostsSerializer(user, context={ 'page': page, 'url': url, 'posts': posts, 'user': user }) return Response(serializer.data)
def get(self, request, username=None, format=None): ip = utils.get_client_ip(request) utils.start_method_log('BoardApiView: get', username=request.user.username, ip=ip) user = request.user if username is not None: user = User.objects.filter(username=username).first() if user is None: response_content = {"detail": "User not found."} return Response(response_content, status.HTTP_400_BAD_REQUEST) if user != request.user and user.is_private == True: Flw = Followers.objects.filter(user=request.user, following=user) if len(Flw) == 0: return Response({'details': 'you cant see him/her boards'}, status=status.HTTP_400_BAD_REQUEST) page = request.GET.get('page') if page is None: page = 1 url = str(request.scheme) + '://' + request.get_host() + MEDIA_URL data = Board.objects.filter(owner=user).order_by('-id') serializer = UserBoardsSerializer(user, context={ 'page': page, 'url': url, 'data': data }) return Response(serializer.data)
def _validate_data(request, data): ip = utils.get_client_ip(request) utils.start_method_log('LikeApi: _validate_data', username=request.user.username, ip=ip) post_id = data.get('post_id') user_id = request.user.id if post_id is None: raise ValidationError('post_id must be set.') try: post = Posts.objects.get(id=post_id) except: raise ValidationError('post is not exists') if not post.owner.is_private: return True if post.owner == request.user: return True flw = Followers.objects.filter(user=user_id, following=post.owner).all() if len(flw) != 0: return True raise ValidationError('Permission denied')
def post(self, request): ip = utils.get_client_ip(request) utils.start_method_log('AddNewPostToBoard: post', username=request.user.username, ip=ip) data = request.data errors = {} try: AddNewPostToBoard._validate_data(request, data) except ValidationError as e: errors['details'] = list(e.messages) return Response(errors, status=status.HTTP_400_BAD_REQUEST) board_id = data.get('board_id') post_id = data.get('post_id') post = Posts.objects.get(id=post_id) board = Board.objects.get(id=board_id) BoardContains.objects.create(post=post, board=board) logger.info('AddNewPostToBoard: post!' 'post: {post} added to' 'board: {board},' 'username: {username},' 'ip:{ip}'.format(post=post_id, board=board_id, username=request.user.username, ip=ip)) r_data = {'details': 'Post added to board'} return Response(r_data, status.HTTP_200_OK)
def resend_auth_code(self, ae, request): req = json.loads(request.body.decode('utf-8')) msg = '' if req.get('tlf'): req['tlf'] = get_cannonical_tlf(req.get('tlf')) tlf = req.get('tlf') if isinstance(tlf, str): tlf = tlf.strip() msg += check_field_type(self.tlf_definition, tlf, 'authenticate') msg += check_field_value(self.tlf_definition, tlf, 'authenticate') if msg: return self.error("Incorrect data", error_codename="invalid_credentials") try: u = User.objects.get(userdata__tlf=tlf, userdata__event=ae, is_active=True) except: return self.error("Incorrect data", error_codename="invalid_credentials") msg = check_pipeline( request, ae, 'resend-auth-pipeline', Sms.PIPELINES['resend-auth-pipeline']) if msg: return self.error("Incorrect data", error_codename="invalid_credentials") result = plugins.call("extend_send_sms", ae, 1) if result: return self.error("Incorrect data", error_codename="invalid_credentials") send_codes.apply_async(args=[[u.id,], get_client_ip(request)]) return {'status': 'ok'}
def post(self, request): ip = utils.get_client_ip(request) utils.start_method_log('CheckEmailApiView: post', ip=ip) serializer = EmailSerializer(data=request.data) if serializer.is_valid(): email = request.data['email'] try: User.objects.get(email=email) except ObjectDoesNotExist: logger.info( 'CheckEmailApiView: post (Email does not exist. ip: {})'. format(ip)) return Response({"message": "Email does not exist."}, status=status.HTTP_200_OK) logger.info( 'CheckEmailApiView: post (Email exists. ip: {})'.format(ip)) return Response({"message": "Email exists"}, status=status.HTTP_400_BAD_REQUEST) else: logger.info( 'CheckEmailApiView: post (Email address is not valid. ip: {})'. format(ip)) return Response({"message": "Email address is not valid"}, status=status.HTTP_400_BAD_REQUEST)
def _validate_data(request, data): ip = utils.get_client_ip(request) utils.start_method_log('DeletePostFromBoard: _validate_data', username=request.user.username, ip=ip) post_id = data.get('post_id') board_id = data.get('board_id') if post_id is None: raise ValidationError('post_id must be set.') if board_id is None: raise ValidationError('board_id must be set.') try: board = Board.objects.get(id=board_id) except: raise ValidationError('board does not exist') try: post = Posts.objects.get(id=post_id) except: raise ValidationError('post does not exist') if board.owner != request.user: raise ValidationError("it's not your board!") is_existed = BoardContains.objects.filter(board=board_id, post=post_id) if len(is_existed) == 0: raise ValidationError("This board doesnt have this post") return True
def create_image(filename,data,request): '''create an image from data and request''' from mimetypes import guess_type from StringIO import StringIO try: if not utils.is_image(data): print 'data is not image' return None try: name,dot,ext = filename.partition('.') if len(ext)>4: ext = "jpg" except: ext = "jpg" img = Image() img.ext = ext img.mime = guess_type(filename)[0] img.ip = utils.get_client_ip(request) #create thumbs and reduce size if necessary data = create_thumb_and_reduce_size(img,data) img.image.put(data, filename=img.uid+"."+img.ext, content_type=img.mime) if request.user.is_authenticated(): img.user = request.user img.edited = datetime.now() img.save() except Exception,what: print repr(what) return None
async def doh1handler(request): path, params = utils.extract_path_params(request.rel_url.path_qs) if request.method in ["GET", "HEAD"]: try: ct, body = utils.extract_ct_body(params) except DOHParamsException as e: return aiohttp.web.Response(status=400, body=e.body()) elif request.method == "POST": body = await request.content.read() ct = request.headers.get("content-type") else: return aiohttp.web.Response(status=501, body=b"Not Implemented") if ct != constants.DOH_MEDIA_TYPE: return aiohttp.web.Response(status=415, body=b"Unsupported content type") # Do actual DNS Query try: dnsq = utils.dns_query_from_body(body, debug=request.app.debug) except DOHDNSException as e: return aiohttp.web.Response(status=400, body=e.body()) clientip = utils.get_client_ip(request.transport) request.app.logger.info("[HTTPS] {} (Original IP: {}) {}".format( clientip, request.headers.getall('X-Forwaded-For'), utils.dnsquery2log(dnsq))) return await request.app.resolve(request, dnsq)
def post(self, request, format=None): ip = utils.get_client_ip(request) utils.start_method_log('likeAPI: get', username=request.user.username, ip=ip) data = request.data errors = {} try: LikeAPI._validate_data(request, data) except ValidationError as e: errors['details'] = list(e.messages) return Response(errors, status=status.HTTP_400_BAD_REQUEST) post_id = data.get('post_id') post = Posts.objects.get(id=post_id) like, created = Like.objects.get_or_create(user=request.user, post=post) if not created: like.delete() if request.user != post.owner: unlike_notification(request.user.id, post.owner.id, post.id) else: if request.user != post.owner: like_notification(request.user.id, post.owner.id, post.id) return Response({'liked': created}, status=status.HTTP_200_OK)
def post(self, request, pk): ''' Send authentication emails to the whole census ''' permission_required(request.user, 'AuthEvent', 'edit', pk) data = {'msg': 'Sent successful'} # first, validate input e = get_object_or_404(AuthEvent, pk=pk) if e.status != 'started': return json_response(status=400, error_codename="AUTH_EVENT_NOT_STARTED") try: req = parse_json_request(request) except: return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) userids = req.get("user-ids", None) extra_req = req.get('extra', {}) # force extra_req type to be a dict if not isinstance(extra_req, dict): return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) if req.get('msg', '') or req.get('subject', ''): config = {} if req.get('msg', ''): config['msg'] = req.get('msg', '') if req.get('subject', ''): config['subject'] = req.get('subject', '') else: send_error = census_send_auth_task(pk, get_client_ip(request), None, userids, **extra_req) if send_error: return json_response(**send_error) return json_response(data) if config.get('msg', None) is not None: if type(config.get('msg', '')) != str or len(config.get( 'msg', '')) > settings.MAX_AUTH_MSG_SIZE[e.auth_method]: return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) send_error = census_send_auth_task(pk, get_client_ip(request), config, userids, **extra_req) if send_error: return json_response(**send_error) return json_response(data)
def post(self, request, pk): ''' Send authentication emails to the whole census ''' permission_required(request.user, 'AuthEvent', 'edit', pk) data = {'msg': 'Sent successful'} # first, validate input e = get_object_or_404(AuthEvent, pk=pk) if e.status != 'started': return json_response( status=400, message='AuthEvent with id = %s has not started' % pk, error_codename=ErrorCodes.BAD_REQUEST) invalid_json = json.dumps({'error': "Invalid json"}) try: req = json.loads(request.body.decode('utf-8')) except: return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) userids = req.get("user-ids", None) if req.get('msg') or req.get('subject'): config = {} if req.get('msg'): config['msg'] = req.get('msg') if req.get('subject'): config['subject'] = req.get('subject') else: msg = census_send_auth_task(pk, get_client_ip(request), None, userids) if msg: data['msg'] = msg return json_response(data) if config.get('msg', None) is not None: if type(config.get('msg')) != str or len(config.get( 'msg')) > settings.MAX_AUTH_MSG_SIZE[e.auth_method]: return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) msg = census_send_auth_task(pk, get_client_ip(request), config, userids) if msg: data['msg'] = msg return json_response(data)
def create_visitor(self, short_addr=None): if not self.queryset: self.queryset = URL.objects.filter(short_addr=short_addr) device = Visitor.MOBILE if self.request.user_agent.is_mobile else Visitor.DESKTOP Visitor.objects.create(url=self.queryset.first(), date=datetime.now(), browser=self.request.user_agent.browser.family.lower(), device=device, ip=get_client_ip(self.request)) self.queryset = None
def verify_user_email(self, request): self.verified_at = now() self.verif_ua = get_user_agent(request) self.verif_ip = get_client_ip(request) self.save() auth_user = self.auth_user auth_user.email_verified = True auth_user.save()
def send_message(subject, message, from_email, to_email): dt = datetime.datetime msg = Message(subject, sender=from_email, recipients=[to_email]) msg.body = message + '\n\nSent at ' + str(dt.now()) + ' from ' + str(get_client_ip()) + '\n' send_async_email(msg) app.logger.debug('E-mail sent to %s ' % to_email) return True
def get(self, request, username=None, *args, **kwargs): ip = utils.get_client_ip(request) utils.start_method_log('PaginationApiView: get', authorized_user=request.user.username, request_user=username) if username is None: username = request.user.username try: profile = User.objects.get(username=username) except ObjectDoesNotExist: data = {"error": "Username not found"} logger.info('PaginationApiView: get ' '(Username not found) username:{}, ip: {}'.format( request.user.username, ip)) return Response(data=data, status=status.HTTP_404_NOT_FOUND) profile_private = profile.is_private target_profile = profile user_profile = request.user if target_profile != user_profile and profile_private: try: follow_status = Followers.objects.get(user=user_profile, following=target_profile) except ObjectDoesNotExist: return Response(status=status.HTTP_403_FORBIDDEN) queryset = Posts.objects.filter(owner=profile).order_by('-time') page = request.GET.get('page') pages = utils.paginator(queryset, page=page) results = pages.get('result') count = pages.get('count') total_page = pages.get('total_page') results_list = [] for post in results: item = { "id": post.id, "post_picture": str(request.scheme) + "://" + request.get_host() + MEDIA_URL + str(post.picture) } results_list.append(item) data = { "count": count, "total_pages": total_page, "results": results_list } logger.info('PaginationApiView: get ' '(get posts of {}) username:{}, ip: {}'.format( username, request.user.username, ip)) return Response(data=data, status=status.HTTP_200_OK)
def register(self, ae, request): req = json.loads(request.body.decode('utf-8')) msg = check_pipeline(request, ae) if msg: return self.error("Incorrect data", error_codename="invalid_credentials") # create the user as active? Usually yes, but the execute_pipeline call inside # check_fields_in_request might modify this req['active'] = True msg = '' if req.get('tlf'): req['tlf'] = get_cannonical_tlf(req.get('tlf')) tlf = req.get('tlf') if isinstance(tlf, str): tlf = tlf.strip() msg += check_field_type(self.tlf_definition, tlf) msg += check_field_value(self.tlf_definition, tlf) msg += check_fields_in_request(req, ae) if msg: return self.error("Incorrect data", error_codename="invalid_credentials") # get active from req, this value might have changed in check_fields_in_requests active = req.pop('active') msg_exist = exist_user(req, ae, get_repeated=True) if msg_exist: u = msg_exist.get('user') if u.is_active: return self.error("Incorrect data", error_codename="invalid_credentials") else: u = create_user(req, ae, active) msg += give_perms(u, ae) if msg: return self.error("Incorrect data", error_codename="invalid_credentials") elif not active: # Note, we are not calling to extend_send_sms because we are not # sending the code in here return {'status': 'ok'} result = plugins.call("extend_send_sms", ae, 1) if result: return self.error("Incorrect data", error_codename="invalid_credentials") send_codes.apply_async(args=[[ u.id, ], get_client_ip(request)]) return {'status': 'ok'}
def get(self, request, username=None, format=None): ip = utils.get_client_ip(request) if username is None: username = request.user.username utils.start_method_log('FollowerSearchApiView: get', username=request.user.username, ip=ip) page = request.GET.get('page') search_value = request.GET.get('search') user = User.objects.filter(username=username).first() if user is None: response_content = {"detail": "User not found."} return Response(response_content, status.HTTP_400_BAD_REQUEST) if search_value is None: search_value = '' if user != request.user and user.is_private == True: if Followers.objects.filter(user=request.user, following=user).count() == 0: return Response( {'details': 'You cannot see him/her followers.'}, status=status.HTTP_400_BAD_REQUEST) search_array = search_value.split(' ') followers_query_set = Followers.objects.filter( following=user).order_by('-id') followers = [' '] for f in followers_query_set: followers.append(f.user.username) Users = User.objects.filter( reduce(or_, [Q(username=q) for q in followers])).order_by('-id') data = Users.filter( Q(username__icontains=search_value) | Q(reduce(or_, [Q(fullname__icontains=q) for q in search_array]))).order_by('-id') url = str(request.scheme) + '://' + request.get_host() + MEDIA_URL serializer = UserSearchSerializer(self.request.user, context={ 'page': page, 'url': url, 'data': data, 'request_user': self.request.user }) return Response(serializer.data)
def post(self, request, pk): permission_required(request.user, 'AuthEvent', 'edit', pk) ae = get_object_or_404(AuthEvent, pk=pk) req = json.loads(request.body.decode('utf-8')) for uid in req.get('user-ids'): u = get_object_or_404(User, pk=uid, userdata__event=ae) u.is_active = self.activate u.save() if self.activate: send_codes.apply_async(args=[[u for u in req.get('user-ids')], get_client_ip(request)]) return json_response()
def post(self, request, pk): ''' Send authentication emails to the whole census ''' permission_required(request.user, 'AuthEvent', 'edit', pk) data = {'msg': 'Sent successful'} # first, validate input e = get_object_or_404(AuthEvent, pk=pk) if e.status != 'started': return json_response(status=400, message='AuthEvent with id = %s has not started' % pk, error_codename=ErrorCodes.BAD_REQUEST) invalid_json = json.dumps({'error': "Invalid json"}) try: req = json.loads(request.body.decode('utf-8')) except: return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) userids = req.get("user-ids", None) if req.get('msg') or req.get('subject'): config = {} if req.get('msg'): config['msg'] = req.get('msg') if req.get('subject'): config['subject'] = req.get('subject') else: msg = census_send_auth_task(pk, get_client_ip(request), None, userids) if msg: data['msg'] = msg return json_response(data) if config.get('msg', None) is not None: if type(config.get('msg')) != str or len(config.get('msg')) > settings.MAX_AUTH_MSG_SIZE[e.auth_method]: return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) msg = census_send_auth_task(pk, get_client_ip(request), config, userids) if msg: data['msg'] = msg return json_response(data)
def signup(request): user = request.user if user.is_authenticated: return HttpResponseRedirect(reverse_lazy('dashboard')) form = RegistrationForm() if request.method == 'POST': form = RegistrationForm(data=request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] existing_user = get_object_or_None(AuthUser, email=email) if existing_user: msg = _('That email already belongs to someone, please login:'******'Login Successful') messages.success(request, msg) return HttpResponseRedirect(reverse_lazy('dashboard')) elif request.method == 'GET': # Preseed name and/or email if passed through GET string email = request.GET.get('e') full_name = request.GET.get('name') if email or full_name: form = RegistrationForm(initial={ 'email': email, 'full_name': full_name, }) return { 'form': form, 'is_input_page': True, }
def signup(request): user = request.user if user.is_authenticated(): return HttpResponseRedirect(reverse_lazy('dashboard')) form = RegistrationForm() if request.method == 'POST': form = RegistrationForm(data=request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] existing_user = get_object_or_None(AuthUser, email=email) if existing_user: msg = _('That email already belongs to someone, please login:'******'Login Successful') messages.success(request, msg) return HttpResponseRedirect(reverse_lazy('dashboard')) elif request.method == 'GET': # Preseed name and/or email if passed through GET string email = request.GET.get('e') full_name = request.GET.get('name') if email or full_name: form = RegistrationForm(initial={ 'email': email, 'full_name': full_name, }) return { 'form': form, 'is_input_page': True, }
def post(self, request): ip = utils.get_client_ip(request) utils.start_method_log('ForgotPasswordApiView: post', ip=ip) email = request.data.get('email') if email is None: logger.info('ForgotPasswordApiView: ' 'post (Email is required. ip: {})'.format(ip)) return Response(data={"details": "email is required."}, status=status.HTTP_400_BAD_REQUEST) try: user_query_set = User.objects.get(email=email) except ObjectDoesNotExist: logger.info('ForgotPasswordApiView: ' 'post (User not found. ip: {})'.format(ip)) return Response(data={"details": "User not found"}, status=status.HTTP_404_NOT_FOUND) try: token = Token.objects.get(user=user_query_set) token_time = token.created_time now_time = datetime.datetime.now(datetime.timezone.utc) ok_time = now_time - token_time if ok_time.seconds > 300: token.delete() token = Token.objects.create(user=user_query_set) else: logger.info( 'ForgotPasswordApiView: ' 'post (Try again later for create token. ip: {})'.format( ip)) return Response( data={"details": "Please try again a few minutes later"}, status=status.HTTP_403_FORBIDDEN) except ObjectDoesNotExist: token = Token.objects.create(user=user_query_set) email = utils.send_email(to=email, subject="Token for forgot password", body="Your Token: {}".format(token.key)) if email.status_code == 200: logger.info('ForgotPasswordApiView: post (Ok , Token send to this ' 'email:{email} ip: {ip})'.format(ip=ip, email=email)) return Response(data={}, status=status.HTTP_201_CREATED) else: logger.info('ForgotPasswordApiView: post ' '(Email API fail. ip: {})'.format(ip)) return Response(data={"details": "email api fail"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def _validate_data(request, data): ip = utils.get_client_ip(request) utils.start_method_log('DeleteBoard: _validate_data', username=request.user.username, ip=ip) board_id = data.get('board_id') if board_id is None: raise ValidationError('board_id must be set.') try: board = Board.objects.get(id=board_id) except: raise ValidationError('board is not exists') if board.owner != request.user: raise ValidationError("it's not your board!")
def create(self, request): subject = request.POST.get("subject", "") invitations = request.POST.get("invitation", "").split(",") ip_address = utils.get_client_ip(request) kw_activity = { "subject": subject, "owner": request.user, "ip": ip_address } activity = Activity\ .objects\ .create(**kw_activity) activity.user.add(request.user) return activity
def add(cls, request): ip = get_client_ip(request) instance = cls( username = request.POST.get('forum_nickname') or '__no_username', question_id = request.POST.get('question'), answer = request.POST.get('answer') or '__empty_answer', ip_address = ip ) type_of_visitor, potential_spammer = lookup_http_blacklist(ip) if type_of_visitor is not None and potential_spammer is not None: instance.potential_spammer = potential_spammer instance.type_of_visitor = type_of_visitor instance.save() return instance
def log_webhook(cls, request, api_name): try: data_from_post = json.loads(request.body.decode()) except Exception: client.captureException() data_from_post = None return cls.objects.create( ip_address=get_client_ip(request), user_agent=get_user_agent(request), api_name=api_name, hostname=request.get_host(), request_path=request.path, uses_https=request.is_secure(), data_from_get=request.GET, data_from_post=data_from_post, )
def register(self, ae, request): req = json.loads(request.body.decode('utf-8')) msg = check_pipeline(request, ae) if msg: return self.error("Incorrect data", error_codename="invalid_credentials") # create the user as active? Usually yes, but the execute_pipeline call inside # check_fields_in_request might modify this req['active'] = True msg = '' if req.get('tlf'): req['tlf'] = get_cannonical_tlf(req.get('tlf')) tlf = req.get('tlf') if isinstance(tlf, str): tlf = tlf.strip() msg += check_field_type(self.tlf_definition, tlf) msg += check_field_value(self.tlf_definition, tlf) msg += check_fields_in_request(req, ae) if msg: return self.error("Incorrect data", error_codename="invalid_credentials") # get active from req, this value might have changed in check_fields_in_requests active = req.pop('active') msg_exist = exist_user(req, ae, get_repeated=True) if msg_exist: u = msg_exist.get('user') if u.is_active: return self.error("Incorrect data", error_codename="invalid_credentials") else: u = create_user(req, ae, active) msg += give_perms(u, ae) if msg: return self.error("Incorrect data", error_codename="invalid_credentials") elif not active: # Note, we are not calling to extend_send_sms because we are not # sending the code in here return {'status': 'ok'} result = plugins.call("extend_send_sms", ae, 1) if result: return self.error("Incorrect data", error_codename="invalid_credentials") send_codes.apply_async(args=[[u.id,], get_client_ip(request)]) return {'status': 'ok'}
def post(self, request, pk): permission_required(request.user, 'AuthEvent', ['edit', 'census-activation'], pk) ae = get_object_or_404(AuthEvent, pk=pk) req = parse_json_request(request) user_ids = req.get('user-ids', []) check_contract(CONTRACTS['list_of_ints'], user_ids) for uid in user_ids: u = get_object_or_404(User, pk=uid, userdata__event=ae) u.is_active = self.activate u.save() if self.activate: send_codes.apply_async( args=[ [u for u in user_ids], get_client_ip(request), ae.auth_method ]) return json_response()
def create(self, request): attrs = self.flatten_dict(request.POST) ip_address = utils.get_client_ip(request) message_body = attrs.get("body", None) activity_id = attrs.get("activity_id", 0) service = attrs.get("service", "dev") stash = bool(attrs.get("stash", False)) try: activity = Activity.objects.get(pk=activity_id) except Activity.DoesNotExist: return rc.NOT_FOUND msg = Message(user=request.user, activity=activity, body=attrs['body'],\ ip=ip_address, message_type="T", stash=stash) msg.save() if not stash: self._send_notification(msg) return msg
def setup_address_forwarding(request, coin_symbol): # kind of tricky because we have to deal with both logged in and new users already_authenticated = request.user.is_authenticated() initial = {'coin_symbol': coin_symbol} if already_authenticated: form = KnownUserAddressForwardingForm(initial=initial) else: form = NewUserAddressForwardingForm(initial=initial) if request.method == 'POST': if already_authenticated: form = KnownUserAddressForwardingForm(data=request.POST) else: form = NewUserAddressForwardingForm(data=request.POST) if form.is_valid(): coin_symbol = form.cleaned_data['coin_symbol'] destination_address = form.cleaned_data['coin_address'] user_email = form.cleaned_data.get('email') # optional. null in case of KnownUserAddressForwardingForm if already_authenticated: auth_user = request.user else: auth_user = None if user_email: # Check for existing user with that email existing_user = get_object_or_None(AuthUser, email=user_email) if existing_user: msg = _('Please first login to this account to create a notification') messages.info(request, msg) return HttpResponseRedirect(existing_user.get_login_uri()) else: # Create user with unknown (random) password auth_user = AuthUser.objects.create_user( email=user_email, password=None, # it will create a random pw creation_ip=get_client_ip(request), creation_user_agent=get_user_agent(request), ) # Login the user # http://stackoverflow.com/a/3807891/1754586 auth_user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, auth_user) # Log the login LoggedLogin.record_login(request) else: # No user email given, proceed anonymously # FIXME: confirm this pass # Setup Payment Forwarding forwarding_address_details = get_forwarding_address_details( destination_address=destination_address, api_key=BLOCKCYPHER_API_KEY, callback_url=None, # notifications happen separately (and not always) coin_symbol=coin_symbol, ) if 'error' in forwarding_address_details: # Display error message back to user messages.warning(request, forwarding_address_details['error'], extra_tags='safe') else: initial_address = forwarding_address_details['input_address'] # create forwarding object address_forwarding_obj = AddressForwarding.objects.create( coin_symbol=coin_symbol, initial_address=initial_address, destination_address=destination_address, auth_user=auth_user, blockcypher_id=forwarding_address_details['id'], ) subscribe_uri = reverse('subscribe_address', kwargs={'coin_symbol': coin_symbol}) uri_qs = {'a': initial_address} if user_email: uri_qs['e'] = user_email if already_authenticated: uri_qs['e'] = auth_user.email subscribe_uri = '%s?%s' % (subscribe_uri, urlencode(uri_qs)) initial_addr_uri = reverse('address_overview', kwargs={ 'coin_symbol': coin_symbol, 'address': initial_address, }) destination_addr_uri = reverse('address_overview', kwargs={ 'coin_symbol': coin_symbol, 'address': destination_address, }) msg_merge_dict = { 'initial_address': initial_address, 'initial_addr_uri': initial_addr_uri, 'destination_address': destination_address, 'destination_addr_uri': destination_addr_uri, 'subscribe_uri': subscribe_uri, 'small_payments_msg': SMALL_PAYMENTS_MSG, } if auth_user: msg_merge_dict['user_email'] = auth_user.email if user_email or (already_authenticated and form.cleaned_data['wants_email_notification']): # Create an address subscription for all of these cases # Hit blockcypher and return subscription id callback_uri = reverse('address_webhook', kwargs={ 'secret_key': WEBHOOK_SECRET_KEY, # hack for rare case of two webhooks requested on same address: 'ignored_key': simple_pw_generator(num_chars=10), }) callback_url = uri_to_url(callback_uri) bcy_id = subscribe_to_address_webhook( subscription_address=initial_address, callback_url=callback_url, coin_symbol=coin_symbol, api_key=BLOCKCYPHER_API_KEY, ) # only notify for deposits AddressSubscription.objects.create( coin_symbol=coin_symbol, b58_address=initial_address, auth_user=auth_user, blockcypher_id=bcy_id, notify_on_deposit=True, notify_on_withdrawal=False, address_forwarding_obj=address_forwarding_obj, ) if user_email: # New signup msg = _(''' Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a> will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>, but you must confirm your email to receive notifications. <br /><br /> <i>%(small_payments_msg)s</i> ''' % msg_merge_dict) messages.success(request, msg, extra_tags='safe') address_forwarding_obj.send_forwarding_welcome_email() return HttpResponseRedirect(reverse('unconfirmed_email')) else: if auth_user.email_verified: msg = _(''' Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a> will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>, and you will immediately receive an email notification at <b>%(user_email)s</b>. <br /><br /> <i>%(small_payments_msg)s</i> ''' % msg_merge_dict) messages.success(request, msg, extra_tags='safe') return HttpResponseRedirect(reverse('dashboard')) else: # existing unconfirmed user msg = _(''' Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a> will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>, but you must confirm your email to receive notifications. <br /><br /> <i>%(small_payments_msg)s</i> ''' % msg_merge_dict) messages.success(request, msg, extra_tags='safe') address_forwarding_obj.send_forwarding_welcome_email() return HttpResponseRedirect(reverse('unconfirmed_email')) elif already_authenticated: # already authenticated and doesn't want subscriptions msg = _(''' Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a> will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>. You will not receive email notifications (<a href="%(subscribe_uri)s">subscribe</a>). <br /><br /> <i>%(small_payments_msg)s</i> ''' % msg_merge_dict) messages.success(request, msg, extra_tags='safe') return HttpResponseRedirect(reverse('dashboard')) else: # New signup sans email msg = _(''' Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a> will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>. You will not receive email notifications (<a href="%(subscribe_uri)s">subscribe</a>). <br /><br /> <i>%(small_payments_msg)s</i> ''' % msg_merge_dict) messages.success(request, msg, extra_tags='safe') return HttpResponseRedirect(destination_addr_uri) elif request.method == 'GET': coin_address = request.GET.get('a') subscriber_email = request.GET.get('e') if coin_address: initial['coin_address'] = coin_address if subscriber_email and not already_authenticated: initial['email'] = subscriber_email if coin_address or subscriber_email: if already_authenticated: form = KnownUserAddressForwardingForm(initial=initial) else: form = NewUserAddressForwardingForm(initial=initial) return { 'form': form, 'coin_symbol': coin_symbol, 'is_input_page': True, }
def subscribe_address(request, coin_symbol): already_authenticated = request.user.is_authenticated() # kind of tricky because we have to deal with both logged in and new users initial = {'coin_symbol': coin_symbol} if already_authenticated: form = KnownUserAddressSubscriptionForm(initial=initial) else: form = NewUserAddressSubscriptionForm(initial=initial) if request.method == 'POST': if already_authenticated: form = KnownUserAddressSubscriptionForm(data=request.POST) else: form = NewUserAddressSubscriptionForm(data=request.POST) if form.is_valid(): coin_symbol = form.cleaned_data['coin_symbol'] coin_address = form.cleaned_data['coin_address'] if already_authenticated: auth_user = request.user else: user_email = form.cleaned_data['email'] # Check for existing user with that email existing_user = get_object_or_None(AuthUser, email=user_email) if existing_user: msg = _('Please first login to this account to create a notification') messages.info(request, msg) return HttpResponseRedirect(existing_user.get_login_uri()) else: # Create user with unknown (random) password auth_user = AuthUser.objects.create_user( email=user_email, password=None, # it will create a random pw creation_ip=get_client_ip(request), creation_user_agent=get_user_agent(request), ) # Login the user # http://stackoverflow.com/a/3807891/1754586 auth_user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, auth_user) # Log the login LoggedLogin.record_login(request) existing_subscription_cnt = AddressSubscription.objects.filter( auth_user=auth_user, b58_address=coin_address).count() if existing_subscription_cnt: msg = _("You're already subscribed to that address. Please choose another address.") messages.warning(request, msg) else: # TODO: this is inefficiently happening before email verification # Hit blockcypher and return subscription id callback_uri = reverse('address_webhook', kwargs={ 'secret_key': WEBHOOK_SECRET_KEY, # hack for rare case of two webhooks requested on same address: 'ignored_key': simple_pw_generator(num_chars=10), }) callback_url = uri_to_url(callback_uri) bcy_id = subscribe_to_address_webhook( subscription_address=coin_address, callback_url=callback_url, coin_symbol=coin_symbol, api_key=BLOCKCYPHER_API_KEY, ) address_subscription = AddressSubscription.objects.create( coin_symbol=coin_symbol, b58_address=coin_address, auth_user=auth_user, blockcypher_id=bcy_id, ) address_uri = reverse('address_overview', kwargs={ 'coin_symbol': coin_symbol, 'address': coin_address, }) if already_authenticated and auth_user.email_verified: msg = _('You will now be emailed notifications for <a href="%(address_uri)s">%(coin_address)s</a>' % { 'coin_address': coin_address, 'address_uri': address_uri, }) messages.success(request, msg, extra_tags='safe') return HttpResponseRedirect(reverse('dashboard')) else: address_subscription.send_notifications_welcome_email() return HttpResponseRedirect(reverse('unconfirmed_email')) elif request.method == 'GET': coin_address = request.GET.get('a') subscriber_email = request.GET.get('e') if coin_address: initial['coin_address'] = coin_address if subscriber_email and not already_authenticated: initial['email'] = subscriber_email if coin_address or subscriber_email: if already_authenticated: form = KnownUserAddressSubscriptionForm(initial=initial) else: form = NewUserAddressSubscriptionForm(initial=initial) return { 'form': form, 'coin_symbol': coin_symbol, 'is_input_page': True, }
def register(self, ae, request): req = json.loads(request.body.decode('utf-8')) msg = check_pipeline(request, ae) if msg: return msg # create the user as active? Usually yes, but the execute_pipeline call inside # check_fields_in_request might modify this req['active'] = True reg_match_fields = [] if ae.extra_fields is not None: reg_match_fields = [ f for f in ae.extra_fields if "match_census_on_registration" in f and f['match_census_on_registration'] ] # NOTE the fields of type "fill_if_empty_on_registration" need # to be empty, otherwise the user is already registered. reg_fill_empty_fields = [] if ae.extra_fields is not None: reg_fill_empty_fields = [ f for f in ae.extra_fields if "fill_if_empty_on_registration" in f and f['fill_if_empty_on_registration'] ] msg = '' email = req.get('email') if isinstance(email, str): email = email.strip() email = email.replace(" ", "") msg += check_field_type(self.email_definition, email) msg += check_field_value(self.email_definition, email) msg += check_fields_in_request(req, ae) if msg: return self.error("Incorrect data", error_codename="invalid_credentials") # get active from req, this value might have changed in check_fields_in_requests active = req.pop('active') if len(reg_match_fields) > 0 or len(reg_fill_empty_fields) > 0: # is the email a match field? match_email = False match_email_element = None for extra in ae.extra_fields: if 'name' in extra and 'email' == extra['name'] and "match_census_on_registration" in extra and extra['match_census_on_registration']: match_email = True match_email_element = extra break # if the email is not a match field, and there already is a user # with that email, reject the registration request if not match_email and User.objects.filter(email=email, userdata__event=ae, is_active=True).count() > 0: return self.error("Incorrect data", error_codename="invalid_credentials") # lookup in the database if there's any user with the match fields # NOTE: we assume reg_match_fields are unique in the DB and required search_email = email if match_email else "" if match_email: reg_match_fields.remove(match_email_element) q = Q(userdata__event=ae, is_active=False, email=search_email) # Check the reg_match_fields for reg_match_field in reg_match_fields: # Filter with Django's JSONfield reg_name = reg_match_field['name'] req_field_data = req.get(reg_name) if reg_name and req_field_data: q = q & Q(userdata__metadata__contains={reg_name: req_field_data}) else: return self.error("Incorrect data", error_codename="invalid_credentials") # Check that the reg_fill_empty_fields are empty, otherwise the user # is already registered for reg_empty_field in reg_fill_empty_fields: # Filter with Django's JSONfield reg_name = reg_empty_field['name'] # Note: the register query _must_ contain a value for these fields if reg_name and reg_name in req and req[reg_name]: q = q & Q(userdata__metadata__contains={reg_name: ""}) else: return self.error("Incorrect data", error_codename="invalid_credentials") user_found = None user_list = User.objects.filter(q) if 1 == user_list.count(): user_found = user_list[0] # check that the unique:True extra fields are actually unique uniques = [] for extra in ae.extra_fields: if 'unique' in extra.keys() and extra.get('unique'): uniques.append(extra['name']) if len(uniques) > 0: base_uq = Q(userdata__event=ae, is_active=True) base_list = User.objects.exclude(id = user_found.id) for reg_name in uniques: req_field_data = req.get(reg_name) if reg_name and req_field_data: uq = base_q & Q(userdata__metadata__contains={reg_name: req_field_data}) repeated_list = base_list.filter(uq) if repeated_list.count() > 0: return self.error("Incorrect data", error_codename="invalid_credentials") # user needs to exist if user_found is None: return self.error("Incorrect data", error_codename="invalid_credentials") for reg_empty_field in reg_fill_empty_fields: reg_name = reg_empty_field['name'] if reg_name in req: user_found.userdata.metadata[reg_name] = req.get(reg_name) user_found.userdata.save() if not match_email: user_found.email = email user_found.save() u = user_found else: msg_exist = exist_user(req, ae, get_repeated=True) if msg_exist: return self.error("Incorrect data", error_codename="invalid_credentials") else: u = create_user(req, ae, active) msg += give_perms(u, ae) if msg: return self.error("Incorrect data", error_codename="invalid_credentials") elif not active: # Note, we are not calling to extend_send_sms because we are not # sending the code in here return {'status': 'ok'} send_codes.apply_async(args=[[u.id,], get_client_ip(request),'email']) return {'status': 'ok'}
def is_localhost(request): return { 'IS_LOCALHOST': utils.get_client_ip(request) == '127.0.0.1' }
def record_login(cls, request): return cls.objects.create( auth_user=request.user, ip_address=get_client_ip(request), user_agent=get_user_agent(request), )