Exemple #1
0
    def form_valid(self, form):
        bad_request = validate_captcha(form.data['g-recaptcha-response'])
        if bad_request:
            return bad_request

        try:
            member = Member.objects.get(
                Q(student_id=form.data['student_id'])
            )
            member.username = form.data['nickname']
            member.password = make_password(form.data['password'])
            member.did_sign_up = True
        except:
            return HttpResponseNotAllowed("부원으로 등록되어 있지 않습니다. 관리자에게 문의하여 주십시오.")

        try:
            send_template_email(
                title='계정 활성화 확인 이메일', 
                template_name='user/email_body/activation.html', 
                context=self.create_template_email_context(form.data, member),
                to=member.email
            )

            self.success_url += f'?address={member.email}'
            member.save()
            return super().form_valid(form)
        except Exception as e:
            print(e)
            return HttpResponseServerError("500 내부 서버 오류. 이메일 전송에 실패하였습니다. 회원가입을 다시 진행해 주세요.")
Exemple #2
0
    def handle(self, *args, **kwargs):
        now = timezone.now()

        if now.date() not in settings.DEADLINE_REMINDER_DATES:
            return

        users = (User.objects.annotate(
            num_submissions=Count("submissions")).filter(num_submissions=0))

        fmt_priority_deadline = settings.PRIORITY_DEADLINE.strftime("%B %d")
        fmt_final_deadline = settings.FINAL_DEADLINE.strftime("%B %d")
        passed_priority = now >= settings.PRIORITY_DEADLINE

        if passed_priority:
            template_name = 'deadline_email.html'
        else:
            template_name = 'priority_deadline_email.html'

        for user in users.distinct():
            if not kwargs["dry_run"]:
                subject = ("Don't forget to apply for TotalityHacks!")
                send_template_email(
                    user.email,
                    subject,
                    template_name,
                    {
                        "user": user,
                        "registration_url": settings.EMAIL_REDIRECT_URL,
                        "priority_deadline": fmt_priority_deadline,
                        "final_deadline": fmt_final_deadline,
                    },
                )

        self.stdout.write("Sent deadline reminder email to {} user(s).".format(
            users.count()))
Exemple #3
0
    def post(self, request):
        if not request.data['email']:
            return Response({
                "success": False,
                "message": (
                    "You must enter an email to send the password reset "
                    "request to."
                )
            }, status=status.HTTP_400_BAD_REQUEST)
        user = User.objects.filter(email=request.data['email'])
        if user.exists():
            user = user.first()

            # send account recovery email to user
            current_site = get_current_site(request)
            send_template_email(
                user.email,
                'Password reset request for your account.',
                'acc_recover_email.html',
                {
                    'user': user,
                    'domain': current_site.domain,
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': account_activation_token.make_token(user),
                },
            )

        return Response({
            "success": True,
            "message": "If your email address exists in our database,"
                       " you will receive an email with instructions for"
                       " how to reset your password in a few minutes."
        }, status=status.HTTP_200_OK)
Exemple #4
0
    def create(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.create(request.data)
        else:
            return Response(
                {"success": False, "errors": serializer.errors},
                status=status.HTTP_400_BAD_REQUEST,
            )

        current_site = get_current_site(request)
        send_template_email(
            user.email,
            'Activate your account!',
            'acc_active_email.html',
            {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            },
        )

        # send intro email
        send_template_email(
            user.email,
            'Thanks for applying!',
            'intro_email.html',
            {},
            sent_by=settings.INTRO_EMAIL_FROM,
            hours=settings.INTRO_EMAIL_DELAY,
        )

        # notify the slack channel
        if settings.SLACK_TOKEN:
            send_to_slack(
                "A new user {} just made an account!".format(user.username),
                settings.SLACK_TOKEN,
                settings.SLACK_CHANNEL,
            )

        token, _ = Token.objects.get_or_create(user=user)

        return Response({
            "success": True,
            "message": (
                "Account created! You will need to verify your email address "
                "before logging in. You may need to check your spam."
            ),
            "token": token.key,
        }, status=status.HTTP_201_CREATED)
Exemple #5
0
    def perform_create(self, serializer):
        app, _ = Application.objects.get_or_create(user=self.request.user)

        if not app.submissions.exists() and settings.SLACK_TOKEN:
            send_to_slack(
                ":tada: New application submission! {} :tada:"
                .format(self.request.user.username),
                settings.SLACK_TOKEN,
                settings.SLACK_CHANNEL,
            )

        serializer.save(application=app, user=self.request.user)

        # send confirmation email to user
        user = self.request.user
        subject = 'Application Submitted!'
        send_template_email(user.email, subject, 'app_submitted.html', {})
    def handle(self, *args, **kwargs):
        now = timezone.now()
        all_users = User.objects.none()
        for drip_day in settings.DRIP_EMAIL_DAYS:
            start_range = now - timedelta(days=drip_day)
            start_range = start_range.replace(hour=0,
                                              minute=0,
                                              second=0,
                                              microsecond=0)
            end_range = start_range + timedelta(days=1)

            if not kwargs["start"]:
                self.stdout.write(
                    "Sending email for users registered between {} and {}...".
                    format(start_range, end_range))
            else:
                self.stdout.write(
                    "Sending email for users registered before {}...".format(
                        end_range))

            users = (User.objects.annotate(
                num_submissions=Count("submissions")).filter(
                    num_submissions=0).filter(date_joined__lt=end_range))

            if not kwargs["start"]:
                users = users.filter(date_joined__gt=start_range)

            all_users |= users

        for user in users.distinct():
            if not kwargs["dry_run"]:
                subject = ("Don't forget to submit"
                           " your application for TotalityHacks!")
                send_template_email(
                    user.email,
                    subject,
                    'drip_email.html',
                    {
                        "user": user,
                        "registration_url": settings.EMAIL_REDIRECT_URL,
                    },
                )

        self.stdout.write("Sent drip email to {} user(s).".format(
            users.count()))
Exemple #7
0
    def form_valid(self, form):
        bad_request = validate_captcha(form.data['g-recaptcha-response'])
        if bad_request:
            return bad_request

        recruitment = Recruitment.objects.filter(is_published=True).first()

        ids = list(form.cleaned_data.keys())

        questions = Question.objects.filter(id__in=map(int, ids),
                                            recruitment=recruitment)
        questions = list(questions)

        applicant_profile = self.get_applicant_profile_from_cookie()

        applicant, created = Applicant.objects.update_or_create(
            student_id=applicant_profile['student_id'],
            defaults={
                'recruitment': recruitment,
                'name': applicant_profile['username'],
                'email': applicant_profile['email'],
                'phone_number': applicant_profile['phone_number'],
                'passed': False
            })

        answers = []
        for q in questions:
            answer, created = Answer.objects.update_or_create(
                question=q,
                applicant=applicant,
                defaults={'answer': str(form.cleaned_data[str(q.pk)])})
            answers.append(answer)

        send_template_email(title=f'{applicant.name}님, ISTEAM에 지원해 주셔서 감사합니다!',
                            template_name='recruit/email_body.html',
                            to=applicant.email,
                            context={
                                'applicant': applicant,
                                'answers': answers
                            })

        return super().form_valid(form)