Example #1
0
    def add_redmine_activity(project,sprintusertoryForm, request, object):
        bugtracking = BugTrackingFactory.getConnection(project=project)
        try:
            version = sprintusertoryForm[0].sprint.reference
        except:
            version = 1
        artType = ArtifactType.objects.filter(
            level=3
        ).first()
        if request.is_secure():
            url = 'https://' + get_current_site(request).domain + str(
                reverse_lazy('main:userstory-detail', kwargs={'pk': object.pk}))
        else:
            url = 'http://' + get_current_site(request).domain + str(
                reverse_lazy('main:userstory-detail', kwargs={'pk': object.pk}))

        issue = bugtracking.addIssueFromUserStory(
            project_id=project.id,
            subject=object.title + ' ' + artType.trace_code + object.code,
            tracker_id=project.issueOnInsertUserStory,
            description=object.description + ' ' + url,
            fixed_version_id=version,
        )


        userstory = UserStory.objects.filter(project=project, code=object.code).get()
        Artifact.objects.create(project=project,
                                reference=issue.id,
                                type=artType,
                                userstory=userstory)
Example #2
0
def categories_show(request, category_id, slug=None):
    category = get_object_or_404(
                   Category,
                   pk=category_id,
                   site_id=get_current_site(request).id
    )

    if slug is None:
        return HttpResponsePermanentRedirect(category.get_absolute_url())

    jobs = Job.objects.filter(site_id=get_current_site(request).id) \
                      .filter(category_id=category_id) \
                      .filter(paid_at__isnull=False) \
                      .filter(expired_at__isnull=True) \
                      .order_by('-paid_at')
    form = SubscribeForm()
    meta_desc = 'Browse a list of all active %s jobs' % category.name
    feed_url = reverse('categories_feed', args=(category.id, category.slug(),))
    title = '%s Jobs' % category.name
    context = {'meta_desc': meta_desc,
               'link_rss': feed_url,
               'title': title,
               'form': form,
               'jobs': jobs}
    return render(request, 'job_board/jobs_index.html', context)
Example #3
0
 def save(self, *args, **kwargs):
     """
     The save method should create a new OrganizationUser linking the User
     matching the provided email address. If not matching User is found it
     should kick off the registration process. It needs to create a User in
     order to link it to the Organization.
     """
     try:
         user = get_user_model().objects.get(email__iexact=self.cleaned_data['email'])
     except get_user_model().MultipleObjectsReturned:
         raise forms.ValidationError(_("This email address has been used multiple times."))
     except get_user_model().DoesNotExist:
         user = invitation_backend().invite_by_email(
                 self.cleaned_data['email'],
                 **{'domain': get_current_site(self.request),
                     'organization': self.organization,
                     'sender': self.request.user})
     # Send a notification email to this user to inform them that they
     # have been added to a new organization.
     invitation_backend().send_notification(user, **{
         'domain': get_current_site(self.request),
         'organization': self.organization,
         'sender': self.request.user,
     })
     return OrganizationUser.objects.create(user=user,
             organization=self.organization,
             is_admin=self.cleaned_data['is_admin'])
Example #4
0
def companies_show(request, company_id, slug=None):
    company = get_object_or_404(
                  Company,
                  pk=company_id,
                  site_id=get_current_site(request).id
              )

    if slug is None:
        return HttpResponsePermanentRedirect(company.get_absolute_url())

    # We don't use get_list_or_404 here as we redirect to this view after
    # adding a new company and at that point it won't have any jobs assigned
    # to it.
    jobs = Job.objects.filter(site_id=get_current_site(request).id) \
                      .filter(company=company) \
                      .filter(paid_at__isnull=False) \
                      .order_by('-paid_at')
    title = company.name
    meta_desc = 'Browse a list of all active and expired %s jobs' % \
                company.name
    context = {'meta_desc': meta_desc,
               'title': title,
               'company': company,
               'jobs': jobs}
    return render(request, 'job_board/companies_show.html', context)
Example #5
0
def main(request, reclaim_form=None, create_form=None):
    game = get_game(site=get_current_site(request), create=False)
    bingo_board = _get_user_bingo_board(request)

    create_form = CreateForm(prefix="create", game=game)
    reclaim_form = ReclaimForm(prefix="reclaim")

    boards = BingoBoard.objects.filter(game=game)
    old_games = Game.objects.filter(
        site=get_current_site(request)
    ).exclude(
        # games without any boards created
        bingoboard=None
    ).exclude(
        # games without game_id are hidden
        game_id=None
    ).order_by("-created")

    if game is not None:
        old_games = old_games.exclude(id=game.id)

    return render(request, "bingo/main.html", {
        'my_board': bingo_board,
        'create_form': create_form,
        'reclaim_form': reclaim_form,
        'boards': boards,
        'current_game': game,
        'old_games': old_games,
        'can_start_game': not GAME_START_DISABLED,
        })
Example #6
0
    def test_get_current_site_no_site_id_and_handle_port_fallback(self):
        request = HttpRequest()
        s1 = self.site
        s2 = Site.objects.create(domain='example.com:80', name='example.com:80')

        # Host header without port
        request.META = {'HTTP_HOST': 'example.com'}
        site = get_current_site(request)
        self.assertEqual(site, s1)

        # Host header with port - match, no fallback without port
        request.META = {'HTTP_HOST': 'example.com:80'}
        site = get_current_site(request)
        self.assertEqual(site, s2)

        # Host header with port - no match, fallback without port
        request.META = {'HTTP_HOST': 'example.com:81'}
        site = get_current_site(request)
        self.assertEqual(site, s1)

        # Host header with non-matching domain
        request.META = {'HTTP_HOST': 'example.net'}
        self.assertRaises(ObjectDoesNotExist, get_current_site, request)

        # Ensure domain for RequestSite always matches host header
        with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}):
            request.META = {'HTTP_HOST': 'example.com'}
            site = get_current_site(request)
            self.assertEqual(site.name, 'example.com')

            request.META = {'HTTP_HOST': 'example.com:80'}
            site = get_current_site(request)
            self.assertEqual(site.name, 'example.com:80')
Example #7
0
def get_topic(request, topic_name):
    selected_tags = topic_name.strip("/")
    if selected_tags:
        selected_tags = selected_tags.split("/")
    else:
        selected_tags = []

    if request.POST:
        if request.POST.get("link_tag"):
            return save_tag(request, topic_name)
        if request.POST.get("delete_tag"):
            return delete_tag(request, selected_tags)
        else:
            return save_link(request, topic_name)

    template = loader.get_template('topics/show_topic.html')
    links = Link.get_all_links(get_current_site(request), selected_tags)
    links = paginate_links(links, request.GET.get('page'))

    top_tags = list(Tag.get_top_tag_list(get_current_site(request), selected_tags))
    if len(links) < 6:
        top_tags = top_tags[:-1]
    context = RequestContext(request, {
        'links': links,
        'top_tags_first': top_tags[:1],
        'top_tags_rest': top_tags[1:],
        'selected_tags': selected_tags
    })
    return HttpResponse(template.render(context))
Example #8
0
def get_current_domain(request=None):
    from django.conf import settings
    from django.contrib.sites.shortcuts import get_current_site

    # Server name
    if getattr(settings, 'FORCE_DOMAIN', None) is not None:
        servername = settings.FORCE_DOMAIN
    else:
        try:
            servername = get_current_site(request).domain.split(':', 1)[0]
        except:
            global _servername
            if _servername is None:
                _servername = socket.getfqdn()
            servername = _servername

    # Port
    scheme = get_current_scheme(request)

    if getattr(settings, 'FORCE_PORT', None) is not None:
        port = int(settings.FORCE_PORT)
    else:
        try:
            port = int(get_current_site(request).domain.split(':', 1)[1])
        except:
            port = 80 if scheme == 'http' else 443

    if (scheme == 'http' and port != 80) or (scheme == 'https' and port != 443):
        return servername + (':%s' % port)
    else:
        return servername
Example #9
0
        def wrapped_view(request, *args, **kwargs):
            oauth_request = get_oauth_request(request)
            scheme = 'https' if request.is_secure() else 'http'
            domain = get_current_site(request).domain
            if oauth_request is None:
                return invalid_params_response(scheme, domain)

            try:
                consumer = store.get_consumer(
                    request, oauth_request, oauth_request['oauth_consumer_key'])
            except InvalidConsumerError:
                return INVALID_CONSUMER_RESPONSE

            try:
                token = store.get_access_token(
                    request, oauth_request, consumer, oauth_request.get_parameter('oauth_token'))
            except InvalidTokenError:
                return send_oauth_error('https' if request.is_secure() else 'http',
                    get_current_site(request).domain,
                    oauth.Error(_('Invalid access token: %s') % oauth_request.get_parameter('oauth_token')))

            if not verify_oauth_request(request, oauth_request, consumer, token):
                return could_not_verify_oauth_request_response(scheme, domain)

            if self.scope_name and (not token.scope or
                                    token.scope.name != self.scope_name):
                return invalid_scope_response(scheme, domain)

            if token.user:
                request.user = token.user
            return view_func(request, *args, **kwargs)
Example #10
0
    def _build_params(self):
        """
        Ipaymu parameters builder.
        Build params based on ipaymu requirements:
        https://ipaymu.com/cara-integrasi-webstore-tingkat-lanjut/

        ==Should be provided via form submit--------
        'product'  => 'Nama Produk'
        'price'    => '101000'
        'quantity' => 1
        'comments' => 'Keterangan Produk'

        ==Can be provided via Form submit or use default settings value
        'key'      => 'api_key_merchant'
        'action'   => 'payment',
        'ureturn'  => '/ipaymu/success/',
        'ucancel'  => '/ipaymu/canceled/',

        'invoice_number' => uniqid('INV-')
        'paypal_email'   => 'email_paypal_merchant'
        'paypal_price'   => 1

        'format'   => 'json'

        ---------- Django Ipaymu notification point ------------
        'unotify'  => '/ipaymu/notify/',
        """

        self.raw_params = {
            # These parameters must provided via form
            'product': self.data.get('product', 'n/a'),
            'price': self.data.get('price', 0),
            'quantity': self.data.get('quantity', 0),
            'comments': self.data.get('comments', ''),

            # These parameters can be overrided via form or settings
            'key': self.data.get('key') or settings.IPAYMU_APIKEY,
            'action': self.data.get('action') or settings.IPAYMU_ACTION,
            'format': self.data.get('format') or settings.IPAYMU_RETURN_FORMAT,
            'paypal_email': self.data.get('paypal_email') or settings.IPAYMU_PAYPAL_EMAIL,
            'invoice_number': self.data.get('invoice_number', 'n/a'),
            'paypal_price': self.data.get('paypal_price'),

            'ureturn': self.data.get('ureturn') or settings.IPAYMU_RETURN_URL or ('%s%s%s' % (settings.SITE_PROTOCOL,
                                    get_current_site(self.request).domain,
                                    reverse('ipaymu_return_url'))),

            'ucancel': self.data.get('ucancel') or settings.IPAYMU_CANCEL_URL or ('%s%s%s' % (settings.SITE_PROTOCOL,
                                    get_current_site(self.request).domain,
                                    reverse('ipaymu_cancel_url'))),

            'unotify': '%s%s%s' % (settings.SITE_PROTOCOL,
                                    get_current_site(self.request).domain,
                                    reverse('ipaymu_notify_url')),
        }
        return
Example #11
0
def applicantregister2(request, pk1):
    #import pdb; pdb.set_trace()
    InviteFormSet = formset_factory(ApplicantForm2)

    if request.method == 'POST':
        formset = InviteFormSet(request.POST)

        if(formset.is_valid()):
            for i in formset:
                mail = i.cleaned_data['Email']
                if MyUser.objects.filter(email=mail).exists():
                    user = MyUser.objects.get(email=mail)
                    u1 = user.id  # get user ID
                    a2 = Project.objects.get(id=pk1)
                    a2.applicant.add(u1)

                    invited_user = MyUser.objects.get(email=mail)
                    current_site = get_current_site(request)
                    message = render_to_string('acc_join_email.html', {
                        'user': invited_user.first_name,
                        'domain': current_site.domain,
                        })
                    mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
                    to_email = mail
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
                else:
                    user = MyUser(email=mail)
                    password = MyUser.objects.make_random_password()
                    user.set_password(password)
                    user.is_active = False
                    user.is_candidate = True
                    user.save()
                    u1 = user.id  # get user id
                    a2 = Project.objects.get(id=pk1)

                    a2.applicant.add(u1)
                    current_site = get_current_site(request)
                    message = render_to_string('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),
                                               })
                    mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
                    to_email = user.email
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
            return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs= {'pk1': pk1}))
        else:
            print("The entered form is not valid")

    else:
        formset = InviteFormSet()
    return render(request, 'applicant_register.html', {'formset': formset})
Example #12
0
def home(request):

    red = request.subdomain
    rk = request.domain
    lair = request.lair
    coll = Coll.objects.filter(site=get_current_site(request))
    sites = get_current_site(request)
    which = Site.objects.get_current()
    part = request.get_host()

    return render_to_response("upload.html", locals(), context_instance=RequestContext(request))
Example #13
0
    def get_context_data(self, **kwargs):
        context = super(ArtifactTraceBugTrackingConfirm, self).get_context_data(**kwargs)
        project = ProjectService.get_project(self.request.session.get('project_id', None))
        if self.request.is_secure():
            context['url']='https://'+get_current_site(self.request).domain+'/'+'artifact/'+str(project.id)+'/tracebugtracking/'
        else:
            context['url'] = 'http://' + get_current_site(
                self.request).domain + '/' + 'artifact/' + str(project.id) + '/tracebugtracking/'

        context['project'] = project
        return context
Example #14
0
    def get_context_data(self, **kwargs):
        context = super(ArtifactCodeConfirm, self).get_context_data(**kwargs)
        project = ProjectService.get_project(self.request.session.get('project_id', None))
        context['local_repository'] = settings.REPOSITORY_DIR
        if self.request.is_secure():
            context['url']='https://'+get_current_site(self.request).domain+'/'+'artifact/'+str(project.id)+'/tracecode/'
        else:
            context['url'] = 'http://' + get_current_site(
                self.request).domain + '/' + 'artifact/' + str(project.id) + '/tracecode/'

        context['project'] = project
        return context
Example #15
0
    def get_context_data(self, **kwargs):
        context = super(OrganizationUserAddFromBrand, self).get_context_data(**kwargs)
        request = self.request
        form = BrandUsersForm(initial={
            "user": request.user,
            "users": None,
        })

        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        if "participant_go" in request.GET:
            if len(request.GET["searchbox"].split()) < 2:
                kwargs["first_name"] = request.GET["searchbox"]
                kwargs["last_name"] = request.GET["searchbox"]
            else:
                names = request.GET["searchbox"].split()
                kwargs["first_name"] = names[0]
                kwargs["last_name"] = names[1]

        current_users = []
        for user in OrganizationUser.objects.filter(organization=self.organization):
            current_users += [user.user.pk]
        if request.user.is_superuser:
            if "first_name" in kwargs and "last_name" in kwargs:
                q = User.objects.filter(~Q(pk__in=current_users), Q(first_name__icontains=kwargs["first_name"]) | Q(
                    last_name__icontains=kwargs["last_name"]),
                                        is_active=True, profile__site_registered=get_current_site(request))
            else:
                q = User.objects.filter(~Q(pk__in=current_users), is_active=True,
                                        profile__site_registered=get_current_site(request))
        else:
            if "first_name" in kwargs and "last_name" in kwargs:
                q = User.objects.filter(~Q(pk__in=current_users), Q(first_name__icontains=kwargs["first_name"]) | Q(
                    last_name__icontains=kwargs["last_name"]),
                                        is_active=True, profile__site_registered=request.user.profile.site_registered)
            else:
                q = User.objects.filter(~Q(pk__in=current_users), is_active=True,
                                        profile__site_registered=request.user.profile.site_registered)
        q = q.order_by("first_name")
        p = Paginator(q, 40, request=request).page(page)
        form.fields["users"] = BundledModelMultipleChoiceField(
            queryset=p.object_list)
        # for uop in form.fields["users"]:
        # if self.organization.is_member(uop.user):
        #      pass
        context["pager"] = p
        context["show_users"] = True
        context["manageform"] = form
        context["search_textbox"] = mycoracle_forms.UsersSearchForm()
        return context
Example #16
0
    def test_views_with_other_user(self):
        user = UserF.create()
        group = UserGroupF.create()
        view = UserGroupData.as_view()

        request = HttpRequest()
        request.method = 'GET'
        request.user = user
        response = view(
            request,
            project_id=group.project.id,
            group_id=group.id
        ).render()

        rendered = render_to_string(
            'users/usergroup_data.html',
            {
                'error_description': 'Project matching query does not exist.',
                'error': 'Not found.',
                'user': user,
                'PLATFORM_NAME': get_current_site(request).name,
                'GEOKEY_VERSION': version.get_version()
            }
        )
        self.assertEqual(unicode(response.content), rendered)

        category = CategoryFactory.create(**{'project': group.project})
        request = HttpRequest()
        request.method = 'POST'
        request.user = user
        request.POST = {
            'permission': 'restricted',
            'filters': '{ "%s": { } }' % category.id
        }
        response = view(
            request,
            project_id=group.project.id,
            group_id=group.id
        ).render()

        rendered = render_to_string(
            'users/usergroup_data.html',
            {
                'error_description': 'Project matching query does not exist.',
                'error': 'Not found.',
                'user': user,
                'PLATFORM_NAME': get_current_site(request).name,
                'GEOKEY_VERSION': version.get_version()
            }
        )
        self.assertEqual(unicode(response.content), rendered)
        self.assertIsNone(Group.objects.get(pk=group.id).filters)
Example #17
0
 def get_email_context(self, user):
     token = self.token_generator.make_token(user)
     uid = encode_uid(user.pk)
     domain = django_settings.DJOSER.get('DOMAIN') or get_current_site(self.request).domain
     site_name = django_settings.DJOSER.get('SITE_NAME') or get_current_site(self.request).name
     return {
         'user': user,
         'domain': domain,
         'site_name': site_name,
         'uid': uid,
         'token': token,
         'protocol': 'https' if self.request.is_secure() else 'http',
     }
Example #18
0
def callback_view(request, **args):
    d = {}
    if "error" in args:
        d["error"] = args["error"]

    try:
        oauth_token = Token.objects.get(key=args["oauth_token"])
    except AttributeError as e:
        send_oauth_error("https" if request.is_secure() else "http", get_current_site(request).domain, e)
    except Token.DoesNotExist as e:
        send_oauth_error("https" if request.is_secure() else "http", get_current_site(request).domain, e)
    d["verifier"] = oauth_token.verifier
    return render(request, "oauth_verifier_pin.html", d)
Example #19
0
def register(request):
    if (request.method=='POST'):
        form = RegisterForm(data=request.POST)
        if(form.is_valid()):
            #check captcha first
            session = UserSession.objects.get(session_key=request.session.session_key)
            print("session captcha: "+session.captcha)
            print("form captcha: "+form.cleaned_data["captcha"])
            if(session.captcha != form.cleaned_data["captcha"]):
                messages.add_message(request, messages.ERROR, _('The captcha was entered wrong.'))
            else:
                referer = request.META.get('HTTP_REFERER')
                user = form.save()
                user.groups.add(Group.objects.get(name='User'))
                user.is_active = False
                user.set_password(user.password)
                user.save()
                import uuid
                lv_uuid = str(uuid.uuid1())[0:30]

                message = """<html>
                <body>
                    <h3>Registration at """+get_current_site(request).name+"""</h3><br/>
                    <p>
                        Please click the following link to end your registration.
                    </p>
                    <p>
                        <a href='https://"""+get_current_site(request).domain+""""/user/activate/"""+lv_uuid+"""/'>Activation Link</a>
                    </p>
                </html>
                """

                send_mail('Registration at '+get_current_site(request).name, 'Hello '+user.username+
                          '\n\nPlease click the following the link to end your registration.\n\n'+
                          'Activation Link: https://'+get_current_site(request).domain+'/user/activate/'+lv_uuid+'/', settings.SYSTEMMAIL,
                        [user.email], fail_silently=False,html_message=message)
                profile = UserProfile()
                profile.user = user
                profile.posts = 0
                profile.threads = 0
                profile.activate = lv_uuid
                profile.theme = Theme.objects.get(default=True)
                profile.banned = False
                profile.save()
                messages.add_message(request, messages.INFO, _('User successful registrated.'))
                #return redirect(urlresolvers.reverse('board.views.index'))
                return redirect(referer)
    else:
        form = RegisterForm()
        f_profile = ProfileForm()
    return render_to_response('user/register.html',{'form':form},context_instance=RequestContext(request))
Example #20
0
    def get_context_data(self, **kwargs):
        context = super(ArtifactDocumentForm, self).get_context_data(**kwargs)
        project = ProjectService.get_project(self.request.session['project_id'])
        context['project']=project
        context['local_repository']=settings.REPOSITORY_DIR
        if self.request.is_secure():
            url = 'https://'+get_current_site(self.request).domain
        else:
            url = 'http://'+get_current_site(self.request).domain

        if 'userstory' in self.kwargs: #userstory
            userstory = UserStoryService.get_userstory(self.request.session['project_id'], self.kwargs['userstory'])
            context['artifacttype'] = ArtifactTypeService.get_artifactstype(self.request.session['project_id'], 3, 0)
            context['artifact'] = UserStoryService.get_artifacts(self.request.session['project_id'], userstory)
            context['page_title'] = _('UserStory Artifacts')
            context['url'] = url+'/userstory/'+str(userstory.id)+'/detail/artifact/'
            context['breadcrumbs'] = userstories_breadcrumbs(
                self.request.session.get('project_id'),
                self.kwargs.get('requeriment_id'),
                self.kwargs.get('sprint_id'),
                self.kwargs.get('userstory'),
                'Artifacts'
            )
        elif 'sprint_id' in self.kwargs:
            sprint = SprintService.get_sprint(self.request.session['project_id'], self.kwargs['sprint_id'])
            context['artifacttype'] = ArtifactTypeService.get_artifactstype(self.request.session['project_id'], 2, 0)
            context['artifact'] = SprintService.get_artifacts(self.request.session['project_id'], sprint)
            context['page_title'] = _('Sprint Artifacts')
            context['breadcrumbs'] = (
               {'link': reverse_lazy('main:home'), 'class': '', 'name': _('Home')},
               {'link': reverse_lazy('main:sprint'), 'class': '', 'name': _('Sprint')},
               {'link': reverse_lazy('main:sprint-details',kwargs={'sprint_id':sprint.id}), 'class': '', 'name': sprint},
               {'link': '#', 'class': '', 'name': _('Artifacts')},
            )
        elif 'requeriment_id' in self.kwargs:
            requeriment = RequerimentService.get_requeriment(self.request.session['project_id'], self.kwargs['requeriment_id'])
            context['artifacttype'] = ArtifactTypeService.get_artifactstype(self.request.session['project_id'], 1, 0)
            context['artifact'] = RequerimentService.get_artifacts(self.request.session['project_id'], requeriment)
            context['page_title'] = _('Requeriment Artifacts')
            context['breadcrumbs'] = (
                {'link': reverse_lazy('main:home'), 'class': '', 'name': _('Home')},
                {'link': reverse_lazy('main:requeriment'), 'class': '', 'name': _('Requeriment')},
                {'link': reverse_lazy('main:requeriment-details', kwargs={'pk': requeriment.id}), 'class': '',
                 'name': requeriment.code},
                {'link': '#', 'class': '', 'name': _('Artifacts')},
            )
        else:
            context['artifact'] = ProjectService.get_artifacts(self.request.session['project_id'])
            context['artifacttype'] = ArtifactTypeService.get_artifactstype(self.request.session['project_id'], 0, 0)
            context['page_title'] = _('Project Artifacts')
        return context
Example #21
0
 def prowl(key, pomodoro):
     requests.post('https://api.prowlapp.com/publicapi/add', data={
         'apikey': key,
         'application': 'Pomodoro - {}'.format(get_current_site(None)),
         'event': 'Pomodoro Complete',
         'url': 'https://{}{}'.format(
             get_current_site(None),
             pomodoro.get_absolute_url()),
         'description': '{} - {} - {}'.format(
             pomodoro.title,
             pomodoro.category,
             pomodoro.duration,
         ), 
     }).raise_for_status()
Example #22
0
    def test_clear_site_cache_domain(self):
        site = Site.objects.create(name="example2.com", domain="example2.com")
        request = HttpRequest()
        request.META = {"SERVER_NAME": "example2.com", "SERVER_PORT": "80"}
        get_current_site(request)  # prime the models.SITE_CACHE
        expected_cache = {site.domain: site}
        self.assertEqual(models.SITE_CACHE, expected_cache)

        # Site exists in 'default' database so using='other' shouldn't clear.
        clear_site_cache(Site, instance=site, using="other")
        self.assertEqual(models.SITE_CACHE, expected_cache)
        # using='default' should clear.
        clear_site_cache(Site, instance=site, using="default")
        self.assertEqual(models.SITE_CACHE, {})
Example #23
0
def jobs_show(request, job_id, slug=None):
    job = get_object_or_404(
              Job, pk=job_id, site_id=get_current_site(request).id
          )

    if slug is None:
        return HttpResponsePermanentRedirect(job.get_absolute_url())

    site = get_current_site(request)
    # If the browsing user does not own the job, and the job has yet to be paid
    # for, then 404
    if (job.user.id != request.user.id and not request.user.is_staff and
            job.paid_at is None):
        raise Http404("No Job matches the given query.")
    # If someone views an unpaid job (job owner or admin), display the job's
    # created_at date instead of paid_at
    if job.paid_at is None:
        post_date = job.created_at
    else:
        post_date = job.paid_at
    md = markdown.Markdown(safe_mode='remove')
    job.description_md = md.convert(job.description)
    job.application_info_md = md.convert(job.application_info)
    job.remote = "Yes" if job.remote else "No"
    if job.remote == "Yes":
        meta_desc = '%s is hiring a remote %s. Apply today!' % \
                    (job.company.name, job.title)
    else:
        meta_desc = '%s is hiring a %s in %s, %s. Apply today!' % \
                    (job.company.name, job.title, job.city, job.state)
    title = "%s @ %s" % (job.title, job.company.name)
    stripe_key = site.siteconfig.stripe_publishable_key

    tokens = 0
    if hasattr(job.user, 'usertoken'):
        if job.user.usertoken.tokens > 0:
            tokens = job.user.usertoken.tokens

    context = {'job': job,
               'post_date': post_date,
               'meta_desc': meta_desc,
               'title': title,
               'remote': site.siteconfig.remote,
               'stripe_publishable_key': stripe_key,
               'price': site.siteconfig.price,
               'price_in_cents': site.siteconfig.price_in_cents(),
               'tokens': tokens}
    return render(request, 'job_board/jobs_show.html', context)
Example #24
0
def hooks(request):
    if not request.META['lrs-user'][0]:
        return HttpResponse(request.META['lrs-user'][1], status=401)
    user = request.META['lrs-user'][1]
    if request.method == "POST":
        if request.body:
            try:
                body = convert_to_datatype(request.body)
            except Exception:
                return HttpResponseBadRequest("Could not parse request body")
            try:
                body['user'] = user
                hook = Hook.objects.create(**body)
            except IntegrityError as e:
                return HttpResponseBadRequest("Something went wrong: %s already exists" % body['name'])
            except Exception as e:
                return HttpResponseBadRequest("Something went wrong: %s" % e.message)
            else:
                hook_location = "%s://%s%s/%s" % ('https' if request.is_secure() else 'http',
                    get_current_site(request).domain, reverse('adl_lrs.views.my_hooks'), hook.hook_id)
                resp_data = hook.to_dict()
                resp_data['url'] = hook_location
                resp = HttpResponse(json.dumps(resp_data),
                                    content_type="application/json", status=201)
                resp['Location'] = hook_location
                return resp
        else:
            return HttpResponseBadRequest("No request body found")
    else:
        hooks = Hook.objects.filter(user=user)
        resp_data = [h.to_dict() for h in hooks]
        return HttpResponse(json.dumps(resp_data), content_type="application/json", status=200)
Example #25
0
    def process_response(self, request, response):
        # No need to check for a redirect for non-404 responses.
        if response.status_code != 404:
            return response

        full_path = request.get_full_path()
        current_site = get_current_site(request)

        r = None
        try:
            r = Redirect.objects.get(site=current_site, old_path=full_path)
        except Redirect.DoesNotExist:
            pass
        if r is None and settings.APPEND_SLASH and not request.path.endswith('/'):
            try:
                r = Redirect.objects.get(
                    site=current_site,
                    old_path=request.get_full_path(force_append_slash=True),
                )
            except Redirect.DoesNotExist:
                pass
        if r is not None:
            if r.new_path == '':
                return self.response_gone_class()
            return self.response_redirect_class(r.new_path)

        # No redirect was found. Return the response.
        return response
Example #26
0
def sender(request, subject, template_name, context, to):
    site = get_current_site(request)
    context.update({
        'site_name': site.name,
        'domain': site.domain,
        'protocol': 'https' if request.is_secure() else 'http'
    })
    message = render_to_string(template_name, context)

    # todo: remove in Spirit 0.5 (use DEFAULT_FROM_EMAIL)
    from_email = "{site_name} <{name}@{domain}>".format(
        name="noreply",
        domain=site.domain,
        site_name=site.name
    )

    # todo: remove
    if settings.DEFAULT_FROM_EMAIL != 'webmaster@localhost':
        from_email = settings.DEFAULT_FROM_EMAIL

    for recipient in to:
        try:
            send_mail(
                subject=subject,
                message=message,
                from_email=from_email,
                recipient_list=[recipient]
            )
        except OSError as err:
            logger.exception(err)
Example #27
0
 def save(self, domain_override=None,
          subject_template_name='registration/password_reset_subject.txt',
          email_template_name='registration/password_reset_email.html',
          use_https=False, token_generator=default_token_generator,
          from_email=None, request=None, html_email_template_name=None,
          extra_email_context=None):
     """
     Generates a one-use only link for resetting password and sends to the
     user.
     """
     email = self.cleaned_data["email"]
     for user in self.get_users(email):
         if not domain_override:
             current_site = get_current_site(request)
             site_name = current_site.name
             domain = current_site.domain
         else:
             site_name = domain = domain_override
         context = {
             'email': user.email,
             'domain': domain,
             'site_name': site_name,
             'uid': urlsafe_base64_encode(force_bytes(user.pk)),
             'user': user,
             'token': token_generator.make_token(user),
             'protocol': 'https' if use_https else 'http',
         }
         if extra_email_context is not None:
             context.update(extra_email_context)
         self.send_mail(subject_template_name, email_template_name,
                        context, from_email, user.email,
                        html_email_template_name=html_email_template_name)
Example #28
0
def send_activation_email(
        user=None, request=None, from_email=None,
        subject_template='users/activation_email_subject.html',
        email_template='users/activation_email.html', html_email_template=None):

    if not user.is_active and settings.USERS_VERIFY_EMAIL:
        token_generator = EmailActivationTokenGenerator()

        current_site = get_current_site(request)

        context = {
            'email': user.email,
            'site': current_site,
            'expiration_days': settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS,
            'user': user,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': token_generator.make_token(user=user),
            'protocol': 'https' if request.is_secure() else 'http',
        }

        subject = render_to_string(subject_template, context)
        # email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = render_to_string(email_template, context)

        email_message = EmailMultiAlternatives(subject, body, from_email, [user.email])
        if html_email_template is not None:
            html_email = render_to_string(html_email_template, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()
Example #29
0
    def save(self, *args, **kwargs):
        instance = super(GroupForm, self).save(*args, **kwargs)
        if 'email' in self.changed_data:
            # Send confirmation link.
            context = {
                'group': instance,
                'email': instance.email,
                'site': get_current_site(self.request),
                'token': self.generator.make_token(instance),
                'protocol': 'https' if self.request.is_secure() else 'http',
            }
            from_email = settings.DEFAULT_FROM_EMAIL

            subject = loader.render_to_string(self.subject_template_name,
                                              context)
            # Email subject *must not* contain newlines
            subject = ''.join(subject.splitlines())
            body = loader.render_to_string(self.body_template_name, context)

            if self.html_email_template_name:
                html_email = loader.render_to_string(self.html_email_template_name,
                                                     context)
            else:
                html_email = None
            send_mail(subject, body, from_email, [instance.email],
                      html_message=html_email)
        return instance
Example #30
0
File: views.py Project: FUUK/fuuk
def flatpage(request, url):
    """
    Copy of a `flatpage` view from `django.contrib.flatpages`. Use our `FlatPage` model instead of django one.
    """
    if not url.startswith('/'):
        url = '/' + url
    site_id = get_current_site(request).id
    try:
        f = get_object_or_404(FlatPage, url=url, sites=site_id)
    except Http404:
        try:
            if not url.endswith('/') and settings.APPEND_SLASH:
                url += '/'
                f = get_object_or_404(FlatPage, url=url, sites=site_id)
                return HttpResponsePermanentRedirect('%s/' % request.path)
            else:
                raise
        except Http404:
            # XXX: Temporary redirection of the old person URLs to the new URLs
            resolver = RegexURLResolver(r'^/', HUMAN_PATTERNS)
            match = resolver.resolve(url)
            if Person.objects.filter(is_active=True, human__nickname=match.kwargs['slug']).exists():
                return HttpResponsePermanentRedirect(urljoin('/people/person/', url[1:]))
            raise
    return render_flatpage(request, f)
Example #31
0
def index(request):
    phones = Phone.objects.all()
    messengers = Messenger.objects.all()
    social_links = SocialLink.objects.all()
    schedule = Schedule.objects.all()
    emails = Email.objects.all()
    addresses = Address.objects.all()

    partners = Partner.objects.all()
    brands = Brand.objects.all()

    slides = Slide.objects.all()
    slide_first = slides.first()

    info_blocks = InfoBlock.objects.all()

    main_info = AboutUs.objects.all().first()

    proses = OurPros.objects.all()

    last_news = News.objects.filter(published=True).order_by('-pk')[:2]

    alert_success2 = 1  # по умолчанию
    if request.method == "POST":
        form2 = RepairForm(request.POST)
        if form2.is_valid():
            if request.recaptcha_is_valid:
                name = form2.cleaned_data['name']
                phone = form2.cleaned_data['phone']
                repair_date = form2.cleaned_data['repair_date']
                repair_time = form2.cleaned_data['repair_time']
                car = form2.cleaned_data['car']
                description = form2.cleaned_data['description']

                repair = Repair.objects.create(
                    phone=phone,
                    name=name,
                    repair_date=repair_date,
                    repair_time=repair_time,
                    car=car,
                    description=description,
                )

                try:
                    current_site = get_current_site(request)
                    mail_subject = 'Новая заявка на сайте: ' + current_site.domain
                    message = render_to_string('repairs/repair_message.html', {
                        'domain': current_site.domain,
                        'repair': repair,
                    })
                    to_email = MailToString.objects.first().email
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
                    alert_success2 = 2  # письмо не отправлено
                except:
                    alert_success2 = 3  # письмо отправлено
            else:
                alert_success2 = 0  # неправильная рекапча
    else:
        form2 = RepairForm()

    context = {
        'phones': phones,
        'messengers': messengers,
        'social_links': social_links,
        'schedule': schedule,
        'emails': emails,
        'addresses': addresses,
        'partners': partners,
        'brands': brands,
        'last_news': last_news,
        'slides': slides,
        'slide_first': slide_first,
        'info_blocks': info_blocks,
        'main_info': main_info,
        'proses': proses,
        'form2': form2,
        'alert_success2': alert_success2,
    }

    return render(request, 'landing/index.html', context)
Example #32
0
    def post(self, request, format=None):
        """

        :param request: type of request to server here it is POST
        :param format: format of data to be passed to server. default is None
        :return: json response with status code for registration of user
        """
        try:
            data = request.data
            if data is None:
                return Response({'error': 'Enter Data'},
                                status=status.HTTP_400_BAD_REQUEST)

            # define a serializer object of UserSerializer and get data
            serializer = UserSerializer(data=data)
            username = data['username']

            if User.objects.filter(username=username).exists():
                return Response({'Error': 'User already Exists'},
                                status=status.HTTP_400_BAD_REQUEST)

            if serializer.is_valid():  # check for valid data in serializer

                user = serializer.save()  # make user object from serializer
                # payload to generate token
                payload = {"user_id": user.pk, "username": user.username}

                # generate jwt token
                token = jwt.encode(payload=payload,
                                   key=settings.JWT_SECRET_KEY).decode('utf-8')

                # get current site
                current_site = get_current_site(request)

                # subject for mail
                subject = "Activate Your ChatApp Account"

                # message to be sent in mail
                message = render_to_string(
                    'account_activate.html', {
                        'user': user,
                        'domain': current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                        'token': token
                    })

                # sender and receiver mails
                from_email = settings.EMAIL_HOST_USER
                to_send = [user.email]

                # send mail method to send mail
                send_mail(subject,
                          message,
                          from_email,
                          to_send,
                          fail_silently=False)

                return Response(serializer.data, status=status.HTTP_200_OK)

        except ValueError:
            return Response({'data': serializer.errors},
                            status=status.HTTP_400_BAD_REQUEST)
Example #33
0
 def post(self, request):
     context = {
         'data': request.POST,
         'has_error': False,
     }
     email = request.POST['email'].lower()
     password = request.POST.get('password')
     password2 = request.POST.get('password2')
     username = request.POST.get('username')
     full_name = request.POST.get('name')
     if len(password) < 6:
         messages.add_message(request, messages.ERROR,
                              'Passwords should have atleast 6 characters')
         context['has_error'] = True
     if password != password2:
         messages.add_message(request, messages.ERROR,
                              'Passwords Do not match')
         context['has_error'] = True
     if not validate_email(email):
         messages.add_message(request, messages.ERROR,
                              'Please Provide a valid email')
         context['has_error'] = True
     if CustomUser.objects.filter(email=email).exists():
         messages.add_message(
             request, messages.ERROR,
             'The email provided is in use***********************')
         context['has_error'] = True
     if CustomUser.objects.filter(username=username).exists():
         messages.add_message(request, messages.ERROR,
                              'The Username provided is in use')
         context['has_error'] = True
     if context['has_error']:
         return render(request, 'authentication/register.html', context)
     else:
         user = CustomUser.objects.create_user(username=username,
                                               email=email)
         user.set_password(password)
         user.first_name = full_name
         user.last_name = full_name
         user.is_active = False
         user.save()
         uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
         domain = get_current_site(request).domain
         link = reverse('activate',
                        kwargs={
                            'uidb64': uidb64,
                            'token': generate_token.make_token(user)
                        })
         activate_url = 'http://' + domain + link
         email_subject = "Activate your account"
         email_body = 'Hi ' + user.email + ' Please use this link to verify your account\n' + activate_url
         email = EmailMessage(
             email_subject,
             email_body,
             '*****@*****.**',
             [email],
         )
         email.send(fail_silently=False)
         messages.add_message(request, messages.SUCCESS,
                              'Account created successfully')
         return redirect('login')
Example #34
0
def register(request):
    if not request.user.is_authenticated:
        try:
            if request.method == 'POST':
                first_name=request.POST['first_name']
                last_name=request.POST['last_name']
                username=request.POST['username']
                email=request.POST['email']
                phone=request.POST['phone']
                password=request.POST['password']
                password2=request.POST['password2']
                pattern="[a-z]+[A-Z]+[a-z|A-Z|@|#|0-9]+[a-z|A-Z|@|#|0-9]+[a-z|A-Z|@|#|0-9]+[a-z|A-Z|@|#|0-9]+[a-z|A-Z|@|#|0-9]+[a-z|A-Z|@|#|0-9]+"
                if password == password2:
                    if match(pattern,password):
                            if CustomUser.objects.filter(username=username).exists():
                                messages.error(request,'usernmae exsits')
                                return redirect('register')
                            else:
                                if CustomUser.objects.filter(email=email).exists():
                                    messages.error(request,'email exsits')
                                    return redirect('register')
                                else:
                                    user=CustomUser.objects.create_user(username=username,password=password,first_name=first_name,last_name=last_name,email=email,phone=phone)
                                    #auth.login(request,user)
                                    #messages.success(request,'you are now logged in')
                                    #return redirect('index')
                                    user.is_active=False
                                    user.save()
                                    current_site = get_current_site(request)
                                    email_subject = 'Activate Your Account'
                                    message_tosend = render_to_string('accounts/activate_account.html', {
                                        'user': user,
                                        'domain': current_site.domain,
                                        'uid': urlsafe_base64_encode(force_bytes(user.id)),
                                        'token': account_activation_token.make_token(user),
                                        
                                    })
                                    send_mail(
                                            email_subject,
                                            message_tosend,'*****@*****.**',[email],
                                            fail_silently=False
                                    )
                                    messages.success(request,'check your email for activating your account')
                                    return redirect('login')
                    else:
                        messages.error(request,'password must contain atleast one uppercase and one digit')
                        return redirect('register')

                else:
                    messages.error(request,'password not match')
                    return redirect('register')
            else:
                return render(request,'accounts/register.html')
        except :
            if request.user.is_authenticated:
                auth.logout(request)
            messages.error(request,'Error Exits: we are trying to solve try again later')
            return redirect('login')
    else:
        messages.error(request,'You are already logged in')
        return redirect('dashboard')
 def send_email_confirmation(self, email_address):
     email_address.send_confirmation(site=get_current_site(self.request))
def student_management(request, name="All Students"):
    # gets current researcher for use later
    added_by = Researcher.objects.get(email=request.user)

    # if the label with label_name = name is not found load default of All Students
    if not SubjectLabel.objects.filter(label_name=name, researcher=added_by):
        name = "All Students"

    # if the table for All Students is deleted or does not exist, make it and add all students the researcher
    # has added and add them to it.
    if not SubjectLabel.objects.filter(label_name='All Students', researcher=added_by):
       all_stu_lbl = SubjectLabel().create_label('All Students', added_by)
       all_students = Student.objects.filter(added_by=added_by, is_active=True)
       for stud in all_students:
           all_stu_lbl.students.add(stud)

    # if researcher presses a submit button
    if request.method == "POST":
        if request.POST.get('student_email'):  # create new student
            form = SendEmail(request.POST)

            if form.is_valid():
                email = form.cleaned_data.get('student_email')
                if not Student.objects.filter(email=email):
                    # creates a student with blank fist and last names, then the password is set to unusable
                    first_name = ""
                    last_name = ""
                    password = ""
                    user = Student.objects.create(email=email, first_name=first_name, last_name=last_name, password=password, added_by=added_by, )
                    user.set_unusable_password()

                    # adds a student to the "All Students" label
                    label = SubjectLabel.objects.get(label_name="All Students", researcher=added_by)
                    label.students.add(user)

                    # collects the current domain of the website and the users uid
                    current_site = get_current_site(request)
                    site = current_site.domain
                    uid = urlsafe_base64_encode(force_bytes(user.pk))

                    # creates the subject and message content for the emails
                    subject = 'Activate your Simulated Conversations account'
                    message = 'Hi, \nPlease register here: \nhttp://' + site + '/student/register/'\
                        + uid + '\n'

                    # sends the email
                    send_mail(subject, message, '*****@*****.**', [email], fail_silently=False)
                else:
                    messages.error(request, 'Student already exists', fail_silently=False)
            else:
                messages.error(request, 'Invalid input', fail_silently=False)

        if request.POST.get('email'):
            form = AddToLabel(request.POST)

            if form.is_valid():
                email = form.cleaned_data.get('email')
                # checks to make sure user exists
                if Student.objects.filter(email=email):

                    # adds student to current label
                    user = Student.objects.get(email=email)
                    label = SubjectLabel.objects.get(label_name=name, researcher=added_by)
                    label.students.add(user)

                else:
                    messages.error(request, 'Student does not already exist', fail_silently=False)
            else:
                messages.error(request, 'Invalid input', fail_silently=False)

        if request.POST.get('label_name'):  # create new label
            save_folder = NewLabel(request.POST)
            if save_folder.is_valid():
                label_name = save_folder.cleaned_data.get("label_name")

                # if the label does not already exist, create it
                if not SubjectLabel.objects.filter(label_name=label_name, researcher=added_by):
                    SubjectLabel().create_label(label_name, added_by)
                else:
                    messages.error(request, 'Label name already exists',
                                   fail_silently=False)

    # creates the table for the labels
    all_lbl = SubjectLabel.objects.filter(researcher=added_by).values('label_name')
    label_table = LabelList(all_lbl, prefix="1-")
    RequestConfig(request, paginate={"per_page": 20}).configure(label_table)

    # creates the table for the students in current label
    if not name == 'All Students':
        stu_contents = SubjectLabel.objects.filter(label_name=name, researcher=added_by).values(
            'students__first_name',
            'students__last_name',
            'students__email',
            'students__registered')
        student_table = StudentList(stu_contents, prefix="2-")
        RequestConfig(request, paginate={"per_page": 20}).configure(student_table)
    else:
        stu_contents = Student.objects.filter(added_by=added_by).values(
            'first_name',
            'last_name',
            'email',
            'registered')
        student_table = AllStudentList(stu_contents, prefix="2-")
        RequestConfig(request, paginate={"per_page": 10}).configure(student_table)

    return render(request, 'student_management.html',  {"name": name, "form": AddToLabel(), "form2": NewLabel(),
                                                        "form3": SendEmail(), 'stu_table': student_table,
                                                        'lbl_table': label_table})
Example #37
0
    def post(self, request, *args, **kwargs):
        """
        Loop over all users and send emails.
        """
        to_email = request.data.get("email")
        users = self.get_users(to_email)

        if len(users) == 0 and getattr(settings, "RESET_PASSWORD_VERBOSE_ERRORS", True):
            raise ValidationError(
                {"detail": "No users with email {0} found.", "args": [to_email]}
            )

        for user in users:
            current_site = get_current_site(request)
            site_name = current_site.name
            if has_perm(user, "users.can_change_password") or has_perm(
                user, "users.can_manage"
            ):
                context = {
                    "email": to_email,
                    "site_name": site_name,
                    "protocol": "https" if self.use_https else "http",
                    "domain": current_site.domain,
                    "path": "/login/reset-password-confirm/",
                    "user_id": urlsafe_base64_encode(
                        force_bytes(user.pk)
                    ),  # urlsafe_base64_encode decodes to ascii
                    "token": default_token_generator.make_token(user),
                    "username": user.get_username(),
                }
                body = self.get_email_body(**context)
            else:
                # User is not allowed to reset his permission. Send only short message.
                body = f"""
                    You do not have permission to reset your password at {site_name}.

                    Please contact your local administrator.

                    Your username, in case you've forgotten: {user.get_username()}
                    """
            # Send a django.core.mail.EmailMessage to `to_email`.
            subject = f"Password reset for {site_name}"
            subject = "".join(subject.splitlines())
            from_email = None  # TODO: Add nice from_email here.
            email_message = mail.EmailMessage(subject, body, from_email, [to_email])
            try:
                email_message.send()
            except smtplib.SMTPRecipientsRefused:
                raise ValidationError(
                    {
                        "detail": "Error: The email to {0} was refused by the server. Please contact your local administrator.",
                        "args": [to_email],
                    }
                )
            except smtplib.SMTPAuthenticationError as e:
                # Nice error message on auth failure
                raise ValidationError(
                    {
                        "detail": "Error {0}: Authentication failure. Please contact your administrator.",
                        "args": [e.smtp_code],
                    }
                )
            except ConnectionRefusedError:
                raise ValidationError(
                    {
                        "detail": "Connection refused error. Please contact your administrator."
                    }
                )
        return Response()
def get_site(request):
    return {'current_site': get_current_site(request)}
    def post(self, request, next=None, using=None):
        """
        Post a comment.

        HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
        errors a preview template, ``comments/preview.html``, will be rendered.
        """
        # Fill out some initial data fields from an authenticated user, if present
        data = request.POST.copy()
        if request.user.is_authenticated:
            if not data.get('name', ''):
                data["name"] = request.user.get_full_name() or request.user.get_username()
            if not data.get('email', ''):
                data["email"] = request.user.email

        # Look up the object we're trying to comment about
        ctype = data.get("content_type")
        object_id = data.get("object_id")
        if ctype is None or object_id is None:
            return CommentPostBadRequest("Missing content_type or object_id field.")
        try:
            model = apps.get_model(*ctype.split(".", 1))
            target = model._default_manager.using(using).get(pk=object_id)
        except TypeError:
            return CommentPostBadRequest(
                "Invalid content_type value: %r" % escape(ctype))
        except AttributeError:
            return CommentPostBadRequest(
                "The given content-type %r does not resolve to a valid model." % escape(ctype))
        except ObjectDoesNotExist:
            return CommentPostBadRequest(
                "No object matching content-type %r and object PK %r exists." % (
                    escape(ctype), escape(object_id)))
        except (ValueError, ValidationError) as e:
            return CommentPostBadRequest(
                "Attempting go get content-type %r and object PK %r exists raised %s" % (
                    escape(ctype), escape(object_id), e.__class__.__name__))

        # Do we want to preview the comment?
        preview = "preview" in data

        # Construct the comment form
        form = get_form()(target, data=data)

        # Check security information
        if form.security_errors():
            return CommentPostBadRequest(
                f"The comment form failed security verification:"
                f" {escape(str(form.security_errors()))}")

        # If there are errors or if we requested a preview show the comment
        if form.errors or preview:
            app_lbl = model._meta.app_label
            nm = model._meta.model_name
            template_list = [
                # These first two exist for purely historical reasons.
                # Django v1.0 and v1.1 allowed the underscore format for
                # preview templates, so we have to preserve that format.
                f"comments/{app_lbl}_{nm}_preview.html",
                f"comments/{app_lbl}_preview.html",
                # Now the usual directory based template hierarchy.
                f"comments/{app_lbl}/{nm}/preview.html",
                f"comments/{app_lbl}/preview.html",
                "comments/preview.html",
            ]
            return render(request, template_list,
                          {
                              "comment": form.data.get("comment", ""),
                              "form": form,
                              "next": data.get("next", next),
                          },
                          )

        # Otherwise create the comment
        comment = form.get_comment_object(site_id=get_current_site(request).id)
        comment.ip_address = request.META.get("REMOTE_ADDR", None) or None
        if request.user.is_authenticated:
            comment.user = request.user

        # Signal that the comment is about to be saved
        responses = signals.comment_will_be_posted.send(
            sender=comment.__class__,
            comment=comment,
            request=request
        )

        for (receiver, response) in responses:
            if response is False:
                return CommentPostBadRequest(
                    "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

        # Save the comment and signal that it was saved
        comment.save()
        signals.comment_was_posted.send(
            sender=comment.__class__,
            comment=comment,
            request=request
        )

        return next_redirect(request, fallback=next or 'comments-comment-done',
                             c=comment._get_pk_val())
def con_orga(request, ind_id):
    if request.method == 'POST':
        form = PostForm2(request.POST)
        if form.is_valid():

            ind_location_list = industry.objects.get(
                pk=ind_id).location.split(',')

            name_person = form.cleaned_data['name_person']
            industry_name = industry_name = industry.objects.get(
                pk=ind_id).id_name
            industry_branch = ind_location_list[2]
            organisation_name = form.cleaned_data['organisation_name']
            email = form.cleaned_data['email']
            date_visit = form.cleaned_data['date_visit']
            slot_time = form.cleaned_data['slot_time']
            visiting_members = form.cleaned_data['visiting_members']
            street_name = form.cleaned_data['street_name']
            city_name = form.cleaned_data['city_name']
            pin_code = form.cleaned_data['pin_code']
            code = rand_str()
            user1 = User.objects.get(username=request.user.username)
            p = BookingListOrga(user1=user1,
                                name_person=name_person,
                                industry_name=industry_name,
                                industry_branch=industry_branch,
                                email=email,
                                organisation_name=organisation_name,
                                date_visit=date_visit,
                                slot_time=slot_time,
                                visiting_members=visiting_members,
                                street_name=street_name,
                                city_name=city_name,
                                pin_code=pin_code,
                                code=code)
            p.save()
            total = Tickets.objects.filter(day=date_visit).filter(
                slot=slot_time).count()
            if total == 0:
                tick = Tickets.objects.create(day=date_visit,
                                              slot=slot_time,
                                              ticks=20 - visiting_members)
                tick.save()
            else:
                tick = Tickets.objects.filter(day=date_visit).filter(
                    slot=slot_time)
                for tc in tick:
                    num = tc.ticks
                tk = Tickets.objects.get(pk=tc.id)
                tk.ticks = num - visiting_members
                tk.save()

            transport = request.POST['transport']
            if transport == 'none':
                user = form.save(commit=False)
                user.is_active = False
                current_site = get_current_site(request)
                to_email = email
                site = 'booking/tick_orga_other.html'
                sending_email(site=site,
                              user=user,
                              current_site=current_site,
                              code=code,
                              to_email=to_email)
                return redirect('searchBarApp:searching')
            elif transport == 'bus':
                user = form.save(commit=False)
                user.is_active = False
                current_site = get_current_site(request)
                to_email = email
                site = 'booking/tick_orga_other.html'
                sending_email(site=site,
                              user=user,
                              current_site=current_site,
                              code=code,
                              to_email=to_email)
                return render(request, 'booking/bus_book_orga.html')
            elif transport == 'train':
                user = form.save(commit=False)
                user.is_active = False
                current_site = get_current_site(request)
                to_email = email
                site = 'booking/tick_indi_other.html'
                sending_email(site=site,
                              user=user,
                              current_site=current_site,
                              code=code,
                              to_email=to_email)
                return render(request, 'booking/train_book_orga.html')
            elif transport == 'plane':
                user = form.save(commit=False)
                user.is_active = False
                current_site = get_current_site(request)
                to_email = email
                site = 'booking/tick_indi_other.html'
                sending_email(site=site,
                              user=user,
                              current_site=current_site,
                              code=code,
                              to_email=to_email)
                return render(request, 'booking/air_book_orga.html')
            else:
                return HttpResponse(
                    "<h3>How can you get here without clicking any option <br> It is a miracle and you truely are a genius</h3>"
                )
        else:
            print(PostForm2.errors)
    else:
        form = PostForm2()
    return render(request,
                  'booking/book_orga.html',
                  context={
                      'form': form,
                      'ind_id': ind_id
                  })
Example #41
0
def parent_sign_up(request):
    if request.method == "POST":
        user_form = UserForm(request.POST)
        parents_form = parents_Form(request.POST)
        if user_form.is_valid():
            Parents = parents_form.save(commit=False)
            username = request.POST['username']
            password = request.POST['password']

            # 자녀와 동기화

            code_valid = Parents.c_code_valid
            children = customer_tbl.objects.get(c_code=code_valid)
            children.c_code = code_valid
            children.save()

            # User 생성

            account = User.objects.create_user(username=username,
                                               password=password)

            # 학부모 권한 부여

            content_type = ContentType.objects.get_for_model(consult_tbl)
            permission = Permission.objects.get(
                codename='can_view_consult',
                content_type=content_type,
            )
            user = get_user_model().objects.all().last()
            user.user_permissions.add(permission)

            # db에 user 정보 저장

            customer = customer_tbl.objects.get(user=account.id)
            customer.c_name = request.POST['c_name']
            customer.c_phone = request.POST['c_phone']
            customer.c_gender = request.POST['c_gender']
            customer.c_join = timezone.now()
            customer.c_add = request.POST['c_add']
            customer.c_birth = request.POST['c_birth']
            customer.c_code_valid = Parents.c_code_valid
            customer.c_state = True
            customer.save()

            # 인증파트
            account.is_active = False  # 유저 비활성화
            account.save()
            current_site = get_current_site(request)
            message = render_to_string(
                'sign_up/activation_email.html', {
                    'user': account,
                    'domain': current_site.domain,
                    'uid': urlsafe_base64_encode(force_bytes(account.pk)),
                    'token': account_activation_token.make_token(account),
                })
            send_mail(
                '계정 활성화 확인 이메일.',
                [username],
                message,
            )

            return redirect("/sign/activate_complete")
    else:
        user_form = UserForm()
        parents_form = parents_Form()
    context = {'user_form': user_form, 'parents_form': parents_form}
    return render(request, 'sign_up/p_signup.html', context)
Example #42
0
def register(request):
    """
    Desc: Function is to register the user information and store in the database

    input: HTTPRequest

    return: 

    """
    #checks the method is post or not if yes fetches the data
    if request.method == 'POST':
        first_name = request.POST['First_Name']
        last_name = request.POST['Last_Name']
        username = request.POST['User_Name']
        email = request.POST['email']
        password1 = request.POST['password1']
        password2 = request.POST['password2']

        #Checks whether the two passwords are the same which have entered
        if password1 == password2:
            #check the username is existed in database using the filter object by django
            if User.objects.filter(username=username).exists():
                messages.info(request, 'User-Name taken')
                return redirect('register')
            #checks the email is existed in database using the filter object by django
            elif User.objects.filter(email=email).exists():

                messages.info(request, 'Email taken')
                return redirect('register')

            #else create user in the database
            else:
                user = User.objects.create_user(username=username,
                                                email=email,
                                                password=password1,
                                                first_name=first_name,
                                                last_name=last_name)
                user.is_active = False
                user.save()
                #using the jwt token
                payload = {'id': username}
                key = "encode"
                algorithm = 'HS256'
                current_site = get_current_site(request)
                mail_subject = "Activate your account"
                #loading a template and rendering it with a context
                message = render_to_string(
                    'acc_active.html',
                    {
                        'user': username,
                        'domain': current_site.domain,
                        # Generating the token by sending payload, key, alogorithm
                        'token': Token.encode(payload, key, algorithm),
                    })
                to_email = User.objects.get(email=email)
                #Sending a single message to the recipient list
                send_mail(mail_subject, message, EMAIL_HOST_USER,
                          [to_email.email])
                #print('User created')

                #redirects to the homepage
                messages.info(request, 'verify the mail')
                return redirect('/')

        #gives a message as password not matching and
        #returns an HttpResponse object with that rendered text
        else:
            messages.info(request, 'Password Not Matching')
            return render(request, "register.html")

    #Combines a given template with a given context dictionary
    #and returns an HttpResponse object with that rendered text
    else:

        return render(request, 'register.html')
Example #43
0
def is_site_premium(request):
    return SubscriptionSettings.objects.get(
        pk=get_current_site(request)).premium_enabled
Example #44
0
    def post(self, request):

        context = {'data': request.POST, 'has_error': False}

        email = request.POST.get('email')
        username = request.POST.get('username')
        full_name = request.POST.get('name')
        password = request.POST.get('password')
        # password2 = request.POST.get('password2')

        if len(password) < 6:
            messages.add_message(request, messages.ERROR,
                                 'Password too short.')
            context['has_error'] = True

        # if password != password2:
        # 	messages.add_message(request, messages.ERROR, 'Password not match.')
        # 	context['has_error'] = True

        if not validate_email(email):
            messages.add_message(request, messages.ERROR,
                                 'Please provide a valid email')
            context['has_error'] = True

        try:
            if User.objects.filter(email=email):
                messages.add_message(request, messages.ERROR, 'Email taken')
                context['has_error'] = True

        except Exception as identifier:
            pass

        try:
            if User.objects.filter(username=username):
                messages.add_message(request, messages.ERROR, 'Username taken')
                context['has_error'] = True

        except Exception as identifier:
            pass

        # print(data,'++')

        if context['has_error']:
            return render(request, 'auth/register.html', context)

        user = User.objects.create_user(username=username, email=email)
        user.set_password(password)
        user.full_name = full_name
        user.last_name = full_name
        user.is_active = False

        user.save()
        current_site = get_current_site(request)
        email_subject = 'Active your Account',
        message = render_to_string(
            'auth/activate.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': generate_token.make_token(user)
            })

        email_message = EmailMessage(email_subject, message,
                                     settings.EMAIL_HOST_USER, [email])
        email_message.send()
        messages.add_message(request, messages.SUCCESS,
                             'Account created successfully..')

        return redirect('login')
Example #45
0
	def wrapper(request):
		site = get_current_site(request)
		if site.id == 1:
			return func(request)
		else:
			return redirect('consultation')
Example #46
0
def current_site(request):
    return {
        'site': get_current_site(request),
    }
Example #47
0
def login(request,
          template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.GET.get(redirect_field_name, '')
    ip = get_remote_ip(request)

    if request.method == "POST":
        login = request.POST.get('login', '').strip()
        failed_attempt = get_login_failed_attempts(username=login, ip=ip)
        remember_me = True if request.POST.get('remember_me',
                                               '') == 'on' else False
        redirect_to = request.POST.get(redirect_field_name, '') or redirect_to

        # check the form
        used_captcha_already = False
        if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
            form = authentication_form(data=request.POST)
        else:
            if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
                form = CaptchaAuthenticationForm(data=request.POST)
                used_captcha_already = True
            else:
                form = authentication_form(data=request.POST)

        if form.is_valid():
            return _handle_login_form_valid(request, form.get_user(),
                                            redirect_to, remember_me)

        # form is invalid
        user_logged_in_failed.send(sender=None, request=request)
        failed_attempt = incr_login_failed_attempts(username=login, ip=ip)

        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                # log user in if password is valid otherwise freeze account
                logger.warn(
                    'Login attempt limit reached, try freeze the user, email/username: %s, ip: %s, attemps: %d'
                    % (login, ip, failed_attempt))
                email = Profile.objects.get_username_by_login_id(login)
                if email is None:
                    email = login
                try:
                    user = User.objects.get(email)
                    if user.is_active:
                        user.freeze_user(notify_admins=True)
                        logger.warn(
                            'Login attempt limit reached, freeze the user email/username: %s, ip: %s, attemps: %d'
                            % (login, ip, failed_attempt))
                except User.DoesNotExist:
                    logger.warn(
                        'Login attempt limit reached with invalid email/username: %s, ip: %s, attemps: %d'
                        % (login, ip, failed_attempt))
                    pass
                form.errors['freeze_account'] = _(
                    'This account has been frozen due to too many failed login attempts.'
                )
            else:
                # use a new form with Captcha
                logger.warn(
                    'Login attempt limit reached, show Captcha, email/username: %s, ip: %s, attemps: %d'
                    % (login, ip, failed_attempt))
                if not used_captcha_already:
                    form = CaptchaAuthenticationForm()

    else:
        ### GET
        failed_attempt = get_login_failed_attempts(ip=ip)
        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                form = authentication_form()
            else:
                logger.warn(
                    'Login attempt limit reached, show Captcha, ip: %s, attempts: %d'
                    % (ip, failed_attempt))
                form = CaptchaAuthenticationForm()
        else:
            form = authentication_form()

    request.session.set_test_cookie()
    current_site = get_current_site(request)

    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    enable_sso = getattr(settings, 'ENABLE_SHIB_LOGIN', False) or \
                 getattr(settings, 'ENABLE_KRB5_LOGIN', False) or \
                 getattr(settings, 'ENABLE_ADFS_LOGIN', False) or \
                 getattr(settings, 'ENABLE_OAUTH', False) or \
                 getattr(settings, 'ENABLE_CAS', False) or \
                 getattr(settings, 'ENABLE_REMOTE_USER_AUTHENTICATION', False)

    login_bg_image_path = get_login_bg_image_path()

    return render(
        request, template_name, {
            'form': form,
            redirect_field_name: redirect_to,
            'site': current_site,
            'site_name': get_site_name(),
            'remember_days': config.LOGIN_REMEMBER_DAYS,
            'signup_url': signup_url,
            'enable_sso': enable_sso,
            'login_bg_image_path': login_bg_image_path,
        })
Example #48
0
 def get_queryset(self, request):
     qs = super(SiteAdmin, self).get_queryset(request)
     if not request.user.is_superuser:
         qs = qs.filter(site=get_current_site(request))
     return qs
Example #49
0
 def form_valid(self, form):
     obj = form.save(commit=False)
     obj.site = get_current_site(self.request)
     obj.save()
     form.instance.notify_users()
     return super(ContactUsFormView, self).form_valid(form)
Example #50
0
    def post(self, request):
        register_form = UserRegistrationForm(request.POST, request.FILES)
        profile_form = ProfileForm(request.POST)

        if register_form.is_valid() and profile_form.is_valid():
            recaptcha_response = request.POST.get('g-recaptcha-response')
            validate_url = 'https://www.google.com/recaptcha/api/siteverify'
            properties = {
                'secret': settings.GOOGLE_SECRET_KEY,
                'response': recaptcha_response
            }
            response = requests.get(validate_url, params=properties)
            if response.json()['success']:
                username = register_form.cleaned_data['username']
                first_name = register_form.cleaned_data['first_name']
                last_name = register_form.cleaned_data['last_name']
                email = register_form.cleaned_data['email']
                password = register_form.cleaned_data['password1']
                about = profile_form.cleaned_data['about']

                if about == '':
                    about = 'Write a little about yourself here...'

                some_user = User.objects.create_user(username=username,
                                                     email=email,
                                                     password=password,
                                                     first_name=first_name,
                                                     last_name=last_name)
                some_user.is_active = False
                some_user.save()

                some_user_profile = Profile(user=some_user, about=about)
                some_user_profile.save()

                current_site = get_current_site(request)
                mail_subject = 'Activate your account'
                message_content = render_to_string(
                    'ActiveEmail.html', {
                        'user': some_user,
                        'domain': current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(
                            some_user.pk)),
                        'token':
                        account_activation_token.make_token(some_user),
                        'request': request
                    })
                to_email = register_form.cleaned_data.get('email')

                message = Mail(
                    from_email='[email protected].'
                    'cloudapp.azure.com',
                    to_emails=to_email,
                    subject=mail_subject,
                    html_content=message_content)
                try:
                    sg = SendGridAPIClient(settings.SENDGRID_KEY)
                    response = sg.send(message)
                    print(response.status_code)
                except Exception as e:
                    print(e.message)

                messages.error(request,
                               'A notification will come to your mail now')
                return redirect('user_authentication_url')
            else:
                messages.error(request, 'Excuse me. You are a robot...')

        self.context.update({
            'title': 'Registration - BotConstructor',
            'register_form': register_form
        })
        return render(request, 'Users/SignUp.html', self.context)
Example #51
0
def register(request):

    if request.method == 'POST':
        # first_name = request.POST['first_name']
        # last_name = request.POST['last_name']
        username = request.POST['username']
        email = request.POST['email']
        # gender = request.POST['exampleRadios']
        # dateofbirth = request.POST['dob']
        password1 = request.POST['password1']
        password2 = request.POST['password2']
        # print(len(password1))

        if password1 == password2:
            if User.objects.filter(username=username).exists():
                messages.warning(request, 'USERNAME TAKEN')
                return redirect('register')

            elif User.objects.filter(email=email).exists():
                messages.warning(request, 'EMAIL TAKEN')
                return redirect('register')

            elif len(email) == 0:
                messages.warning(request, 'EMAIL MISSING')
                return redirect('register')

            # elif len(first_name) == 0:
            #     messages.warning(request,'FIRST NAME MISSING')
            #     return redirect('register')

            # elif len(last_name) == 0:
            #     messages.warning(request,'LAST NAME MISSING')
            #     return redirect('register')

            elif len(username) == 0:
                messages.warning(request, 'USER NAME MISSING')
                return redirect('register')

            elif len(password1) == 0:
                messages.warning(request, 'PASSWORD CANNOT BE EMPTY!!')
                return redirect('register')

            elif len(password1) < 6:
                messages.warning(request, 'PASSWORD IS lESS THAN 6 CHARACTERS')
                return redirect('register')

            else:
                user = User.objects.create_user(username=username,
                                                password=password1,
                                                email=email)
                # newextended = extended(name=username, dateofbirth=dateofbirth, gender=gender, user=user)
                # newextended.save()
                # obj = KirrURL(user = user)
                # obj.save()
                user.is_active = False
                user.save()

                #email sending
                uidb64 = urlsafe_base64_encode(force_bytes(user.pk))

                domain = get_current_site(request).domain
                link = reverse('activate',
                               kwargs={
                                   'uidb64': uidb64,
                                   'token': token_generator.make_token(user)
                               })

                activate_url = 'http://' + domain + link
                email_body = 'Hi ' + user.username + \
                    ' Please use this link to verfiy your account\n' + activate_url

                email_subject = 'Activate your account Kirr.co'

                email = EmailMessage(
                    email_subject,
                    email_body,
                    '*****@*****.**',
                    [email],
                )
                EmailThreading(email).start()
                messages.success(request, 'USER CREATED')
                return redirect('login')

        else:
            messages.warning(request, 'PASSWORD NOT MATCHING!!')
            return redirect('register')

        return redirect('/')

    else:
        return render(request, 'register.html')
Example #52
0
def mainview(request, view_data):
    response, site, cachekey = view_data
    if not response:
        site = models.Site.objects.get(django_site=get_current_site(request))
        feed, tag = request.GET.get('feed'), request.GET.get('tag')

        if feed:
            try:
                feed = models.Feed.objects.get(pk=feed)
            except ObjectDoesNotExist:
                raise Http404
        page = fjlib.get_page(request, site)
        object_list = page['posts']
        subscribers = site.active_subscribers

        # TODO: remove all remaining tag cloud stuff
        tag_obj, tag_cloud = None, tuple()
        try:
            user_obj = None
            if feed:
                user_obj = models.Subscriber.objects.get(site=site, feed=feed)
        except ObjectDoesNotExist:
            raise Http404

        site_proc_tags = site.processing_tags.strip()
        if site_proc_tags != 'none':
            site_proc_tags = filter( None, map(op.methodcaller('strip'), site.processing_tags.split(',')) )
            # XXX: database hit that can be cached
            for site_feed, posts in it.groupby(object_list, key=op.attrgetter('feed')):
                proc = site_feed.processor_for_tags(site_proc_tags)
                if proc:
                    proc.apply_overlay_to_posts(posts)
        # TODO: cleanup
        ctx = {
            'last_modified': max(it.imap(
                    op.attrgetter('date_updated'), object_list ))\
                if len(object_list) else datetime(1970, 1, 1, 0, 0, 0, 0, timezone.utc),
            'object_list': object_list,
            'subscribers':  subscribers.select_related('feed'),
            'tag': tag_obj,
            'feed': feed,
            'url_suffixi': ''.join((
                '/feed/{0}'.format(feed.id) if feed else '',
                '/tag/{0}'.format(escape(tag)) if tag else '' )),

            ## DEPRECATED:
            # Totally misnamed and inconsistent b/w user/user_obj,
            #  use "feed" and "subscribers" instead.
            'user_id': feed and feed.id,
            'user': user_obj,

            'num_next': page['num_next'],
            'num_previous': page['num_previous'],
            'previous_since_date': page['previous_since_date'],
            'previous_until_date': page['previous_until_date'],
            'next_since_date': page['next_since_date'],
            'next_until_date': page['next_until_date'],
            'subscriber_filter': page['subscriber_filter'],
            'url_parameters': request.GET,
        }
        ctx2 = fjlib.get_extra_context(request)
        for key in ctx2:
            ctx[key] = ctx2[key]
        response = render(request, u'feedjack/{0}/post_list.html'.format(site.template), ctx)
        # per host caching, in case the cache middleware is enabled
        patch_vary_headers(response, ['Host'])
        if site.use_internal_cache:
            fjcache.cache_set( site, cachekey,
                (response, ctx_get(ctx, 'last_modified')) )
    else:
        response = response[0]
    return response
Example #53
0
def video_oembed(request):
    if not request.GET.get('url'):
        raise SuspiciousOperation('URL must be specified')
    format = "xml" if request.GET.get("format") == "xml" else "json"

    data = {}
    data['type'] = "video"
    data['version'] = "1.0"
    data['provider_name'] = TITLE_SITE
    protocole = "https" if request.is_secure() else "http"
    data['provider_url'] = "%s://%s" % (protocole,
                                        get_current_site(request).domain)
    data['width'] = 640
    data['height'] = 360

    reg = (r'^https?://(.*)/video/(?P<slug>[\-\d\w]+)/' +
           r'(?P<slug_private>[\-\d\w]+)?/?(.*)')
    url = request.GET.get('url')
    p = re.compile(reg)
    m = p.match(url)

    if m:
        video_slug = m.group('slug')
        slug_private = m.group('slug_private')
        try:
            id = int(video_slug[:video_slug.find("-")])
        except ValueError:
            raise SuspiciousOperation('Invalid video id')
        video = get_object_or_404(Video, id=id)

        data['title'] = video.title
        data['author_name'] = video.owner.get_full_name()
        data['author_url'] = "%s%s?owner=%s" % (
            data['provider_url'], reverse('videos'), video.owner.username)
        data['html'] = (
            "<iframe src=\"%(provider)s%(video_url)s%(slug_private)s" +
            "?is_iframe=true\" width=\"640\" height=\"360\" style=\"" +
            "padding: 0; margin: 0; border:0\" allowfullscreen ></iframe>") % {
                'provider': data['provider_url'],
                'video_url': reverse('video', kwargs={'slug': video.slug}),
                'slug_private': "%s/" % slug_private if slug_private else ""
            }
    else:
        return HttpResponseNotFound('<h1>Url not match</h1>')

    if format == "xml":
        xml = """
            <oembed>
                <html>
                    %(html)s
                </html>
                <title>%(title)s</title>
                <provider_name>%(provider_name)s</provider_name>
                <author_url>%(author_url)s</author_url>
                <height>%(height)s</height>
                <provider_url>%(provider_url)s</provider_url>
                <type>video</type>
                <width>%(width)s</width>
                <version>1.0</version>
                <author_name>%(author_name)s</author_name>
            </oembed>
        """ % {
            'html': data['html'].replace('<', '&lt;').replace('>', '&gt;'),
            'title': data['title'],
            'provider_name': data['provider_name'],
            'author_url': data['author_url'],
            'height': data['height'],
            'provider_url': data['provider_url'],
            'width': data['width'],
            'author_name': data['author_name']
        }
        return HttpResponse(xml, content_type='application/xhtml+xml')
        # return HttpResponseNotFound('<h1>XML not implemented</h1>')
    else:
        return JsonResponse(data)
def site(request):
    # type: (django.http.request.HttpRequest) -> dict
    """Returns site settings which can be accessed with 'site' key."""
    return {'site': get_current_site(request)}
Example #55
0
 def get_domain(self, request):
     current_site = get_current_site(request)
     return current_site.domain
Example #56
0
def send_comment_notification_emails(sender, **kwargs):
    """
    Any time a comment is posted on an application, this sends email to the
    application owner and anyone else who previously commented.
    """
    current_comment = kwargs["comment"]
    app = current_comment.content_object
    assert isinstance(app, Application)

    logger.info("Received comment signal on app number {app.pk}; preparing "
                "to send notification emails".format(app=app))

    if "request" in kwargs:
        # This is the expected case; the comment_was_posted signal should send
        # this.
        request = kwargs["request"]
    else:
        # But if there's no request somehow, get_current_site has a sensible
        # default.
        request = None

    base_url = get_current_site(request).domain
    logger.info("Site base_url is {base_url}".format(base_url=base_url))
    app_url = "https://{base}{path}".format(base=base_url,
                                            path=app.get_absolute_url())
    logger.info("app_url is {app_url}".format(app_url=app_url))

    # If the editor who owns this application was not the comment poster, notify
    # them of the new comment.
    if current_comment.user != app.editor.user:
        if app.editor.user.email:
            logger.info("we should notify the editor")
            email = CommentNotificationEmailEditors()
            logger.info("email constructed")
            email.send(
                app.editor.user.email,
                {
                    "user": app.editor.wp_username,
                    "lang": app.editor.user.userprofile.lang,
                    "app": app,
                    "app_url": app_url,
                    "partner": app.partner,
                    "submit_date": current_comment.submit_date,
                    "commenter": current_comment.user.editor.wp_username,
                    "comment": current_comment.comment,
                },
            )
            logger.info("Email queued for {app.editor.user.email} about "
                        "app #{app.pk}".format(app=app))

    # Send emails to the last coordinator to make a status change to this
    # application, as long as they aren't the ones leaving the comment.
    app_versions = Version.objects.get_for_object(app)

    # 'First' app version is the most recent
    recent_app_coordinator = app_versions.first().revision.user
    if recent_app_coordinator and recent_app_coordinator != current_comment.user:
        if recent_app_coordinator != app.partner.coordinator and not (
                recent_app_coordinator.is_staff):
            recent_app_coordinator = app.partner.coordinator
        email = CommentNotificationCoordinators()
        email.send(
            recent_app_coordinator.email,
            {
                "user": recent_app_coordinator.editor.wp_username,
                "lang": recent_app_coordinator.userprofile.lang,
                "app": app,
                "app_url": app_url,
                "partner": app.partner,
                "submit_date": current_comment.submit_date,
                "commenter": current_comment.user.editor.wp_username,
                "comment": current_comment.comment,
            },
        )
        logger.info(
            "Coordinator email queued for {app.editor.user.email} about app "
            "#{app.pk}".format(app=app))

    # Send to any previous commenters on the thread, other than the editor,
    # the person who left the comment just now, and the last coordinator.
    all_comments = Comment.objects.filter(
        object_pk=app.pk,
        content_type__model="application",
        content_type__app_label="applications",
    )
    users = set([comment.user for comment in all_comments])

    users.remove(current_comment.user)
    try:
        users.remove(app.editor.user)
    except KeyError:
        # If the editor is not among the prior commenters, that's fine; no
        # reason they should be.
        pass
    if recent_app_coordinator:
        try:
            users.remove(recent_app_coordinator)
        except KeyError:
            # Likewise, coordinator might not have commented.
            pass

    for user in users:
        if user:
            # Allow emails to be sent to system users with no editor object.
            if hasattr(user, "editor"):
                username = user.editor.wp_username
            else:
                username = user.username
            email = CommentNotificationEmailOthers()
            email.send(
                user.email,
                {
                    "user": username,
                    "lang": user.userprofile.lang,
                    "app": app,
                    "app_url": app_url,
                    "partner": app.partner,
                    "submit_date": current_comment.submit_date,
                    "commenter": current_comment.user.editor.wp_username,
                    "comment": current_comment.comment,
                },
            )
            logger.info("Email queued for {app.editor.user.email} about app "
                        "#{app.pk}".format(app=app))
Example #57
0
def User_Registration(request):
    forms = {}
    if request.method == 'POST':
        forms['User_Creation_Form'] = UserCreationForm(request.POST)
        forms['User_Registration_Form'] = User_Registration_Form(
            request.POST, request.FILES)
        if forms['User_Registration_Form'].is_valid(
        ) and forms['User_Creation_Form'].is_valid():
            email = forms['User_Registration_Form'].cleaned_data.get('email')
            role = forms['User_Registration_Form'].cleaned_data.get('role')
            try:
                obj = Email.objects.get(email=email)
                try:
                    obj2 = User.objects.get(email=email)
                    context = {
                        'message':
                        "This email-id is already registered with us",
                        'forms': forms
                    }
                    return render(request, 'users/User_Registration.html',
                                  context)
                except:
                    obj2 = True
                if role != obj.role:
                    obj = False
                    context = {
                        'message': "Please select correct role",
                        'forms': forms
                    }
                    return render(request, 'users/User_Registration.html',
                                  context)
            except:
                obj = False
                context = {
                    'message':
                    "You are not registered by your college. Please contact your college",
                    'forms': forms
                }
                return render(request, 'users/User_Registration.html', context)

            username = forms['User_Creation_Form'].cleaned_data.get('username')
            password = forms['User_Creation_Form'].cleaned_data.get(
                'password1')
            current_user = User(username=username, email=email)
            current_user.set_password(password)
            current_user.is_active = False
            current_user.save()
            current_site = get_current_site(request)
            mail_subject = 'digital college account'
            message = render_to_string(
                'users/activate_email.html', {
                    'current_user':
                    current_user,
                    'domain':
                    current_site.domain,
                    'uid':
                    urlsafe_base64_encode(force_bytes(
                        current_user.pk)).decode(),
                    'token':
                    account_activation_token.make_token(current_user),
                })
            to_email = forms['User_Registration_Form'].cleaned_data.get(
                'email')
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.send()
            first_name = forms['User_Registration_Form'].cleaned_data.get(
                'First_Name')
            last_name = forms['User_Registration_Form'].cleaned_data.get(
                'Last_Name')

            college_id = forms['User_Registration_Form'].cleaned_data.get(
                'college_id')

            current_user = Registered_User(
                user=current_user,
                email=email,
                First_Name=first_name,
                Last_Name=last_name,
                role=role,
                college_id=college_id,
            )
            if 'image' in request.FILES:
                image = request.FILES['image']
                current_user.image = image
            current_user.save()
            return render(request, 'users/email_verification.html')

    else:
        forms['User_Creation_Form'] = UserCreationForm()
        forms['User_Registration_Form'] = User_Registration_Form()
    return render(request, 'users/User_Registration.html', {'forms': forms})
Example #58
0
 def get_context_data(self, **kwargs):
     ctx = kwargs
     ctx["confirmation"] = self.object
     site = get_current_site(self.request)
     ctx.update({"site": site})
     return ctx
Example #59
0
def College_Registration(request):
    forms = {}
    if request.method == 'POST':
        forms['User_Creation_Form'] = UserCreationForm(request.POST,
                                                       request.FILES)
        forms['College_Registration_Form'] = College_Registration_Form(
            request.POST, request.FILES)
        if forms['College_Registration_Form'].is_valid(
        ) and forms['User_Creation_Form'].is_valid():
            current_user = forms['User_Creation_Form'].save(commit=False)
            username = forms['User_Creation_Form'].cleaned_data.get('username')
            email = forms['College_Registration_Form'].cleaned_data.get(
                'email')
            password = forms['User_Creation_Form'].cleaned_data.get(
                'password1')
            current_user = User(username=username, email=email)
            current_user.set_password(password)
            current_user.is_active = False
            current_user.save()
            current_site = get_current_site(request)
            mail_subject = 'digital college account'

            message = render_to_string(
                'users/activate_email.html', {
                    'current_user':
                    current_user,
                    'domain':
                    current_site.domain,
                    'uid':
                    urlsafe_base64_encode(force_bytes(
                        current_user.pk)).decode(),
                    'token':
                    account_activation_token.make_token(current_user),
                })
            to_email = forms['College_Registration_Form'].cleaned_data.get(
                'email')
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.send()
            Name_Of_College = forms[
                'College_Registration_Form'].cleaned_data.get(
                    'Name_Of_College')
            email = forms['College_Registration_Form'].cleaned_data.get(
                'email')
            College_Registration_Number = forms[
                'College_Registration_Form'].cleaned_data.get(
                    'College_Registration_Number')
            City = forms['College_Registration_Form'].cleaned_data.get('City')
            State = forms['College_Registration_Form'].cleaned_data.get(
                'State')
            current_user = Registered_College(
                user=current_user,
                Name_Of_College=Name_Of_College,
                email=email,
                College_Registration_Number=College_Registration_Number,
                City=City,
                State=State,
            )
            if 'image' in request.FILES:
                image = request.FILES['image']
                current_user.image = request.FILES['image']
            current_user.save()
            return render(request, 'users/email_verification.html')

    else:
        forms['User_Creation_Form'] = UserCreationForm()
        forms['College_Registration_Form'] = College_Registration_Form()
    return render(request, 'users/College_Registration.html', {'forms': forms})
Example #60
0
def student_sign_up(request):
    if request.method == "POST":
        user_form = UserForm(request.POST)
        student_form = student_Form(request.POST)
        if user_form.is_valid():

            Student = student_form.save(commit=False)
            username = request.POST['username']
            password = request.POST['password']

            # c_code 생성

            random_code = ''
            string_code = string.ascii_letters + string.digits

            for i in range(6):
                random_code += random.choice(string_code)

            Student.c_code = random_code
            print(random_code)

            #db에 정보 저장

            account = User.objects.create_user(username=username,
                                               password=password)
            customer = customer_tbl.objects.get(user=account.id)
            customer.c_name = request.POST['c_name']
            customer.c_phone = request.POST['c_phone']
            customer.c_gender = request.POST['c_gender']
            customer.c_join = timezone.now()
            customer.c_add = request.POST['c_add']
            customer.c_birth = request.POST['c_birth']
            customer.c_school = request.POST['c_school']
            customer.c_code = Student.c_code
            customer.c_state = True
            customer.save()
            # 인증파트
            account.is_active = False  # 유저 비활성화
            account.save()
            current_site = get_current_site(request)
            message = render_to_string(
                'sign_up/activation_email.html', {
                    'user': account,
                    'domain': current_site.domain,
                    'uid': urlsafe_base64_encode(force_bytes(account.pk)),
                    'token': account_activation_token.make_token(account),
                })
            send_mail(
                '계정 활성화 확인 이메일.',
                [username],
                message,
            )

            return redirect("/sign/activate_complete")

    else:
        student_form = student_Form()
        user_form = UserForm()

    context = {'user_form': user_form, 'student_form': student_form}
    return render(request, 'sign_up/c_signup.html', context)