def send_forget_password_mail(request): """ API for sending verification code on the giving mail :param request: email :return: Success if mail send """ data = json.loads(request.body) email = data.get('email') testing = data.pop("testing", False) try: User.objects.get(email=email) except User.DoesNotExist: logger.log_error(f"User does not exist with given email_id {email}, send mail failed") return api_error_response(message="Please provide the registered email id.", status=400) verification_code = randint(1000, 9999) VerificationCode.objects.filter(email=email, is_active=True).update(is_active=False) code = VerificationCode(email=email, code=verification_code) code.save() if not testing: send_email_sms_and_notification( action_name="forget_password", verification_code=verification_code, email_ids=[email] ) logger.log_info(f"Verification code send successfully to user {email}") return api_success_response(message="Verification code send successfully")
def send_mail_to_a_friend(request): """ Function to send mail to an email_id. :param request: email_id: email_id of a friend list_object or string :return: """ data = json.loads(request.body) email = data.get("email_id") event_id = data.get("event_id") testing = data.pop("testing", False) if not (event_id and email): logger.log_error("Event_id or email is missing in the request") return api_error_response(message="Please provide necessary details", status=400) if isinstance(email, str): email = [email] message = data.get("message") try: event_name = Event.objects.get(id=event_id).name except Event.DoesNotExist: logger.log_error("Invalid email id") return api_error_response(message="Invalid email id", status=400) if not testing: send_email_sms_and_notification(action_name="user_share", message=message, url=EVENT_URL + str(event_id), event_name=event_name, email_ids=email) logger.log_info( f"Mail send successfully to the friend by user {email} for event {event_id}" ) return api_success_response(message="Mail sent successfully", status=200)
def post(self, request): """ Post api method for subscriber notify """ data = request.data event_id = data.get("event_id", None) message = data.get("message", "") _type = data.get("type", "reminder").lower() testing = data.pop("testing", False) if event_id: event_name = Event.objects.values_list("name", flat=True).get(id=event_id) if event_name: self.queryset = self.queryset.filter(event=event_id) response = self.queryset.select_related('user'). \ annotate(email=F('user__email'), users_id=F('user__id')).values("email", "users_id") email_ids = list({_["email"] for _ in response}) user_ids = list({_["users_id"] for _ in response}) if _type == "reminder": action_name = "event_reminder" else: action_name = "send_updates" if not testing: send_email_sms_and_notification(action_name=action_name, email_ids=email_ids, message=message, event_name=event_name, user_ids=user_ids, event_id=event_id) logger.log_info( f"Subscribers notified successfully for event {event_id}.") return api_success_response( message="Subscribers notified successfully.")
def post_save_method(sender, **kwargs): instance = kwargs.get('instance') if instance.method_name == 'old_instance': if instance.previous_state and not instance.is_active: send_email_sms_and_notification(action_name="user_blocked", email_ids=[instance.email]) elif not instance.previous_state and instance.is_active: send_email_sms_and_notification(action_name="user_unblocked", email_ids=[instance.email])
def destroy(self, request, *args, **kwargs): token = get_authorization_header(request).split()[1] payload = jwt.decode(token, SECRET_KEY) user_id = payload['user_id'] event_id = int(kwargs.get('pk')) data = request.data message = data.get("message", "") testing = data.pop("testing", False) logger.log_info( f"Event deletion request from user {user_id} for event {event_id}") try: event = self.queryset.get(id=event_id) except Event.DoesNotExist: logger.log_error( "Given event id {} does not exist".format(event_id)) return api_error_response( message="Given event id {} does not exist".format(event_id)) if self.queryset.get(id=event_id).event_created_by.id != user_id: logger.log_error( "Organizer with id {} is not the organizer of the event id {}". format(user_id, event_id)) return api_error_response( message="You are not the organizer of this event {}".format( event_id), status=400) user_obj = Subscription.objects.filter( event=event_id).select_related('user').annotate( email=F('user__email'), users_id=F('user__id')).values("email", "users_id") email_ids = list({_["email"] for _ in user_obj}) user_ids = list({_["users_id"] for _ in user_obj}) self.queryset.filter(id=event_id).update(is_cancelled=True) self.queryset.filter(id=event_id).update(is_active=False) if not testing: send_email_sms_and_notification(action_name="event_deleted", email_ids=email_ids, message=message, event_name=event.name, user_ids=user_ids, event_id=event_id) logger.log_info( f"Event deletion successful for event_id {event_id} by user {user_id}" ) return api_success_response(message="Event successfully deleted", status=200)
def update(self, request, *args, **kwargs): """ Function to update a particular event :param request: body containing changes to be made :param kwargs: contains event id from the url given :return: changed response of an event """ token = get_authorization_header(request).split()[1] payload = jwt.decode(token, SECRET_KEY) user_id = payload['user_id'] event_id = int(kwargs.get('pk')) data = request.data testing = data.pop("testing", False) user_logged_in = user_id logger.log_info( f"Event update request started by user {user_id} for event {event_id}" ) try: user_role = UserProfile.objects.get( user_id=user_logged_in).role.role except Exception: logger.log_error( f"Event update request by user_id {user_id}: fetching of user role from object failed" ) return api_error_response( message="Not able to fetch the role of the logged in user", status=500) if user_role == 'subscriber': logger.log_error( f"Event update request by user_id {user_id}: a subscriber cannot update event details" ) return api_error_response( message="A subscriber cannot change an event details", status=500) if self.queryset.get( id=event_id).event_created_by.id != user_logged_in: logger.log_error( f"Event update request: LoggedIn user {user_id} is not the organizer of the event with id " f"{event_id} ") return api_error_response( message="You are not the organizer of this event {}".format( event_id), status=400) try: event_obj = Event.objects.get(id=event_id) prev_name = event_obj.name prev_location = event_obj.location prev_date = event_obj.date prev_time = event_obj.time except Event.DoesNotExist: logger.log_error( f"Event update request: event_id {event_id} does not exist") return api_error_response( message=f"Event with id {event_id} does not exist", status=400) try: partial = kwargs.pop('partial', False) if 'event_type' in request.data: request.data['type'] = request.data.pop('event_type') serializer = EventSerializer(event_obj, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) serializer.save() serializer.data['images'] = f"https://s3.{AWS_REGION}.amazonaws.com/{BUCKET}/" \ f"{serializer.data['images']}" serializer.data['event_type'] = serializer.data.pop('type') except Exception as err: logger.log_error(str(err)) return api_error_response( message="Some internal error coming while updating the event", status=500) event_name = event_obj.name field_list = [] prev_list = [] next_list = [] if 'name' in data: field_list.append("name") prev_list.append(prev_name) next_list.append(data.get('name')) if 'location' in data: field_list.append("location") prev_list.append(prev_location) next_list.append(data.get('location')) if 'date' in data: field_list.append("date") prev_list.append(str(prev_date)) next_list.append(data.get('date')) if 'time' in data: field_list.append("time") prev_list.append(str(prev_time)) next_list.append(data.get('time')) field = ", ".join(field_list) prev_value = ", ".join(prev_list) next_value = ", ".join(next_list) user_obj = Subscription.objects.filter( event=event_id).select_related('user').annotate( email=F('user__email'), users_id=F('user__id')).values("email", "users_id") email_ids = list({_["email"] for _ in user_obj}) user_ids = list({_["users_id"] for _ in user_obj}) if field: if not testing: send_email_sms_and_notification(action_name="event_updated", email_ids=email_ids, field=field, prev_value=prev_value, next_value=next_value, event_name=event_name, user_ids=user_ids, event_id=event_id) logger.log_info("Subscribers notified for event details update") logger.log_info( f"Event with id {event_id} successfully updated by user with id {user_id}" ) return api_success_response(data=serializer.data, status=200)
def post(self, request): """ :param request :return: api success response if registration is successful """ logger.log_info("User registration started") data = json.loads(request.body) email = data.get('email') name = data.get('name') contact_number = data.get('contact') address = data.get('address') password = data.get('password') organization = data.get('organization') role_name = data.get('role') testing = data.pop("testing", False) if email is None or password is None or role_name is None: logger.log_error("Email, password or role is missing in registration request") return api_error_response( message='Incomplete or incorrect credentials are provided for registration', status=400) try: # Checking if role is correct or not role_name = role_name.lower() role_obj = Role.objects.get(role=role_name) except Role.DoesNotExist: logger.log_error(f"Role name {role_name} is invalid for registering user {email}") return api_error_response( message='Role assigned is not matching with any role type', status=400) try: user = User.objects.get(email=email) except User.DoesNotExist: # if user is None then new_user will be created user = None if user is not None: logger.log_error(f'A user already exist with the given email id: {email}') return api_error_response(message='A user already exist with the given email id: {}'. format(email), status=400) try: user = User.objects.create_user(email=email, password=password) logger.log_info(f"New user created with email id {email}") user_profile_obj = UserProfile.objects.create( user=user, name=name, contact_number=contact_number, organization=organization, address=address, role=role_obj) user_profile_obj.save() logger.log_info(f"User Details successfully registered for user {email}") if role_name == 'organizer': user.is_active = False user.save() token = {} if not testing: send_email_sms_and_notification(action_name="new_organizer_created", email_ids=[ADMIN_EMAIL], user_email=email) else: token = get_token_for_user(user) token['user'] = produce_object_for_user(user) logger.log_info(f"Registration Successful of the User {email} !!!") return api_success_response(data=token, message='User created successfully', status=201) except Exception as err: logger.log_error(str(err)) return api_error_response(message=str(err), status=400)
def unblock_user(modelAdmin, request, queryset): queryset.update(is_active=True) email_ids = queryset.values_list('email', flat=True) send_email_sms_and_notification(action_name="user_unblocked", email_ids=list(email_ids))