Exemple #1
0
def confirm(request):
    if not request.user.is_authenticated:
        return HttpResponseRedirect(reverse("register"))

    donation = request.GET.get("donation")
    total = 1 if not donation else int(donation) + 1

    cancel_url = (
        "{}?donation={}".format(reverse("confirm"), donation)
        if donation
        else reverse("confirm")
    )
    success_url = (
        "{}?donation={}".format(reverse("memberships_settings"), donation)
        if donation
        else reverse("memberships_settings")
    )
    stripe_gateway = StripeGateway()
    session_id = stripe_gateway.create_checkout_session(
        member=request.user.member,
        success_url=request.build_absolute_uri(success_url),
        cancel_url=request.build_absolute_uri(cancel_url),
    )

    return render(
        request,
        "memberships/confirm.html",
        {
            "donation": donation,
            "total": total,
            "stripe_public_key": settings.STRIPE_PUBLIC_KEY,
            "stripe_session_id": session_id,
            "recaptcha_site_key": settings.RECAPTCHA_SITE_KEY,
        },
    )
Exemple #2
0
 def get(self, request, path, head=False, *args, **kwargs):
     if not self.resource.exists:
         raise Http404("Resource doesn't exists")
     if not path.endswith("/") and self.resource.is_collection:
         return HttpResponseRedirect(request.build_absolute_uri() + "/")
     if path.endswith("/") and self.resource.is_object:
         return HttpResponseRedirect(
             request.build_absolute_uri().rstrip("/"))
     response = HttpResponse()
     if head:
         response['Content-Length'] = 0
     if not self.has_access(self.resource, 'read'):
         return self.no_access()
     if self.resource.is_object:
         response['Content-Type'] = self.resource.content_type
         response['ETag'] = self.resource.getetag
         if not head:
             response['Content-Length'] = self.resource.getcontentlength
             response.content = self.resource.read()
     elif not head:
         response = render_to_response(
             self.template_name,
             dict(resource=self.resource, base_url=self.base_url))
     response['Last-Modified'] = self.resource.getlastmodified
     return response
def paynow_payment(request):
    """This is the functions that initiates the payment process"""
    if request.method == 'POST':
        form = MobilePaymentForm(request.POST)
        if form.is_valid():
            cleaned_data = form.cleaned_data

            # Generate unique Transaction ID
            transaction_id = generate_transaction_id()
            pinfo = dict()
            # Generate Urls to pass to Paynow. These are generated dynamicaly
            # and are absolute
            r = reverse('paynow:paynow_update', args=(transaction_id, ))
            pinfo['resulturl'] = request.build_absolute_uri(r)
            r = reverse('paynow:paynow_return', args=(transaction_id, ))
            pinfo['returnurl'] = request.build_absolute_uri(r)
            # Payment amount
            pinfo['amount'] = str(cleaned_data['amount'])
            # Payment reference
            pinfo['reference'] = transaction_id
            # refer to the project settin
            pinfo['id'] = str(settings.PAYNOW_INTEGRATION_ID)
            pinfo['additionalinfo'] = 'Payment from '
            pinfo['additionalinfo'] += str(cleaned_data['cellphone'])
            if cleaned_data['reference'] != '':
                pinfo['additionalinfo'] += ' - ' + cleaned_data['reference']
            # authemail can be blank. If set it is used in the login in
            # process on paynow
            pinfo['authemail'] = ''
            pinfo['status'] = 'Message'
            # Create the necessary query string using function
            query_string = paynow_create_url_query(
                pinfo, settings.PAYNOW_INTEGRATION_KEY)
            # do a request
            paynow_request = urllib.request.Request(settings.PAYNOW_INIT_URL)
            result = urllib.request.urlopen(paynow_request, query_string)
            result = result.read().decode('utf-8')

            if check_initiate_response(result,
                                       settings.PAYNOW_INTEGRATION_KEY):
                resp = parse_paynow_message(result)
                # save payment to database, and record as unpaid
                payment = PaynowPayment(
                    user=request.user,
                    status='unpaid',
                    cellphone=str(cleaned_data['cellphone']),
                    reference=pinfo['reference'],
                    amount=cleaned_data['amount'],
                    additionalinfo=cleaned_data['reference'],
                    authemail=pinfo['authemail'],
                    init_status=resp['status'],
                    pollurl=resp['pollurl'],
                    browserurl=resp['browserurl'])
                payment.save()
                # redirect browser to paynow site for payment
                return redirect(resp['browserurl'], permanent=True)
            else:
                msg = 'Error in processing payment. Please try again'
                messages.error(request, msg)
    return redirect(reverse('index'))
def callback_google_auth(request):
    """
        Check if params is correct, get user credentials and return the redirect url
    """
    if request.method != "GET":
        logger.error("Request method is not GET")
        return HttpResponse(status=400)
    if 'state' not in request.GET or 'code' not in request.GET or 'scope' not in request.GET:
        logger.debug("State, Code or Scope not found in request.GET")
        return HttpResponse(status=400)
    state = request.GET.get('state')
    CLIENT_CONFIG = utils_youtube.create_client_config()

    # This scope will allow the application to create and remove livestreams
    SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
    # Use the client_secret.json file to identify the application requesting
    # authorization. The client ID (from that file) and access scopes are
    # required.
    try:
        flow = google_auth_oauthlib.flow.Flow.from_client_config(
            client_config=CLIENT_CONFIG,
            scopes=SCOPES,
            state=state)
        url_aux = request.build_absolute_uri(reverse('callback_google_auth'))
        flow.redirect_uri = url_aux.replace("http://", "https://")

        url_aux = request.build_absolute_uri()
        authorization_response = url_aux.replace("http://", "https://")
        flow.fetch_token(authorization_response=authorization_response)
        next_url = base64.b64decode(state).decode(
            'utf-8')  # decode Studio EOL URL
        # Store the credentials in the session.
        # ACTION ITEM for developers:
        #     Store user's access and refresh tokens in your data store if
        #     incorporating this code into your real app.
        credentials = flow.credentials
    except InvalidGrantError:
        logger.error(
            "Error with Exchange authorization code for refresh and access tokens, User {}".format(
                request.user
            ))
        return HttpResponse(status=400)
    # Load credentials from the session.
    credentials_dict = {
        'token': credentials.token,
        'refresh_token': credentials.refresh_token,
        'token_uri': credentials.token_uri,
        'scopes': credentials.scopes,
        'expiry': str(credentials.expiry)}
    data = utils_youtube.check_permission_youtube(credentials_dict, request.user)
    EolGoogleAuth.objects.update_or_create(
        user=request.user,
        defaults={'credentials':json.dumps(credentials_dict),
        'channel_enabled':data['channel'],
        'livebroadcast_enabled':data['livestream'],
        'custom_live_streaming_service': data['livestream_zoom']})
    return HttpResponseRedirect(next_url)
Exemple #5
0
    def wrapper(request, *args, **kwargs):
        #decode jwt token
        request_path = request.build_absolute_uri()
        request_host = request.get_host()
        if request.is_secure:
            skip_length = 7 + len(request_host)
            request_path = request_path[skip_length:]
        else:
            skip_length = 6 + len(request_host)
            request_path = request_path[skip_length:]
        try:
            token = request.COOKIES['IdToken']
            if token == '':
                redirect_path = "/login/?next=" + request_path
                return redirect(redirect_path)
        except:
            redirect_path = "/login/?next=" + request_path
            return redirect(redirect_path)

        status, claims = is_token_valid(token)
        if status:
            return f(request,claims['email'],idtoken=token,*args, **kwargs)
        else:
            redirect_path = "/login/?next=" + request_path
            return redirect(redirect_path)
Exemple #6
0
def ows(request):
    params = {key.upper(): request.GET[key] for key in request.GET.keys()}
    url = "{0}?{1}".format(settings.GISQUICK_MAPSERVER_URL.rstrip("/"),
                           request.environ['QUERY_STRING'])

    abs_project = abs_project_path(params.get('MAP'))
    url = set_query_parameters(url, {'MAP': abs_project})

    owsrequest = urllib.request.Request(url)
    owsrequest.add_header("User-Agent", "Gisquick")

    resp_content = b""
    with contextlib.closing(urllib.request.urlopen(owsrequest)) as resp:
        while True:
            data = resp.read()
            if not data:
                break
            resp_content += data

        if params.get('REQUEST', '') == 'GetCapabilities':
            resp_content = resp_content.replace(
                settings.GISQUICK_MAPSERVER_URL.encode(),
                request.build_absolute_uri(request.path).encode())

        content_type = resp.getheader('Content-Type')
        status = resp.getcode()
        return HttpResponse(resp_content,
                            content_type=content_type,
                            status=status)
Exemple #7
0
def zoom_api(request):
    """
        GET REQUEST
        Generate refresh token from Zoom Api
        Update refresh token in models
        Redirect to Studio EOL
    """
    # check method and params
    if request.method != "GET":
        return HttpResponse(status=400)
    if 'code' not in request.GET or 'redirect' not in request.GET:
        return HttpResponse(status=400)

    user = request.user
    authorization_code = request.GET.get('code')
    redirect = base64.b64decode(request.GET.get('redirect')).decode(
        'utf-8')  # decode Studio EOL URL
    redirect_uri = request.build_absolute_uri().split(
        '&code')[0]  # build uri without code param
    #redirect_uri = redirect_uri.replace('http', 'https')
    token = get_refresh_token(authorization_code, redirect_uri)
    if 'error' in token:
        logger.error("Error get_refresh_token {}".format(token['error']))
        return HttpResponse(status=400)

    _update_auth(user, token['refresh_token'])

    return HttpResponseRedirect(redirect)
Exemple #8
0
def gettoken(request):
    auth_code = request.GET['code']
    redirect_uri = request.build_absolute_uri(
        reverse('authorization:gettoken'))
    token = get_token_from_code(auth_code, redirect_uri)
    access_token = token['access_token']
    info = get_me(access_token)
    mail = None
    if info['mail']:
        mail = info['mail']
    else:
        mail = info['userPrincipalName']
    username = mail.split('@')[0]
    if not User.objects.filter(username=username).exists():
        user = User.objects.create_user(username, mail)
        user.first_name = info['displayName']
        user.save()
    user = User.objects.get(username=username)
    request.session['mail'] = mail  # info['mail']
    request.session['fullName'] = info['displayName']
    role = None
    if Student.objects.filter(student_id=user.id).exists():
        role = 'student'
    elif Teacher.objects.filter(teacher_id=user.id).exists():
        role = 'teacher'
    elif Methodist.objects.filter(methodist_id=user.id).exists():
        role = 'methodist'
    request.session['role'] = role
    request.session['user_id'] = user.id
    if role == 'teacher':
        find_branches(user.id)
    return HttpResponseRedirect('../../')
def get_redirect_url(request):
    if getattr(s, 'REDIRECT_URL'):
        return s.REDIRECT_URL

    # Hack the request.GET
    if FLD not in request.GET:
        get = request.GET.copy()
        get.update({
            FLD: request.build_absolute_uri(request.path_info)
        })
        request.GET = get

    return urlquote("{request_url}?{query_string}".format(
        request_url=request.build_absolute_uri(r('ulogin_postback')),
        query_string=smart_unicode(urllib.parse.unquote(request.GET.urlencode()))
    ))
Exemple #10
0
def post_share(request, post_id):
    # Retrieve post by id
    post = get_object_or_404(Post, id=post_id, status='published')
    sent = False
    if request.method == 'POST':
        # Form was submitted
        form = EmailPostForm(request.POST)
        if form.is_valid():
            # Form fields passed validation
            cd = form.cleaned_data
            post_url = request.build_absolute_uri(post.get_absolute_url())
            subject = '{} ({}) recommends you reading "{}"'.format(
                cd['name'], cd['email'], post.title)
            message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(
                post.title, post_url, cd['name'], cd['comments'])
            send_mail(subject, message, '*****@*****.**', [cd['to']])
            sent = True
            create_action(request.user, 'shared via email a post titled ',
                          post)
        return render(request, 'posts/share.html', {
            'post': post,
            'form': form,
            'sent': sent,
            'cd': cd
        })
        # ... send email
    else:
        form = EmailPostForm()
        return render(request, 'posts/share.html', {
            'post': post,
            'form': form,
            'sent': sent
        })
Exemple #11
0
def home(request):
    if 'mail' in request.session:
        return HttpResponseRedirect('../')
    redirect_uri = request.build_absolute_uri(
        reverse('authorization:gettoken'))
    sign_in_url = get_signin_url(redirect_uri)
    context = {'signin_url': sign_in_url}
    return render(request, 'authorization/authorization.html', context)
Exemple #12
0
def oidc_failed(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    access_warn(request, "401 Unauthorized by oidc")
    return render("oidc_failed.mako",
                  request,
                  dict(uri=request.build_absolute_uri()),
                  status=401)
Exemple #13
0
def get_badge_url(request, releasewatch):
    if not releasewatch:
        return

    selector = encode_badge_selector(releasewatch)
    uri = reverse("badge_info", kwargs={"selector": selector})
    params = [
        ("label", "release"),
        ("query", "$.status"),
        ("maxAge", str(60 * 60 * 12)),  # 12 hrs
        ("uri", request.build_absolute_uri(uri)),
        ("link", request.build_absolute_uri("/")),
    ]

    url = "%s?%s" % (BADGE_URL, urllib.parse.urlencode(params))
    logger.info("%r selector, url: %r %r", releasewatch, selector, url)

    return url
Exemple #14
0
def build_absolute_uri(request, url):
	"""
	把相对地址转换成绝对地址
	"""
	if not url:
		return ""
	if not url.startswith("http"):
		return request.build_absolute_uri(url)
	return url
Exemple #15
0
def payments_send_confirmation(request, email):
    dashboard_url = request.build_absolute_uri(reverse("dashboard"))
    from tapiriik.web.email import generate_message_from_template, send_email
    message, plaintext_message = generate_message_from_template(
        "email/payment_confirm.html", {"url": dashboard_url})
    send_email(email,
               "Thanks, %s!" % request.POST["first_name"],
               message,
               plaintext_message=plaintext_message)
Exemple #16
0
	def retrieve(self, request, img_uuid=None):
		res = get_one_entity.delay(img_uuid)
		task_res = res.get()
		domain = request.build_absolute_uri('/')[:-1]
		# file = open("/media/vect-"+img_uuid+".mesh")
		# return HttpResponse(str(file), content_type='application/octet-stream')
		with urllib.request.urlopen(domain+"/media/vect-"+img_uuid+".mesh") as url:
			s = url.read()
			return HttpResponse(s, content_type='application/octet-stream')
Exemple #17
0
def get_google_credential(request):
    client_key = json.load(open('static/Portfolio/json/google.json'))
    flow = client.OAuth2WebServerFlow(
        client_id=client_key['web']['client_id'],
        client_secret=client_key['web']['client_secret'],
        scope='https://www.googleapis.com/auth/userinfo.profile',
        redirect_uri=request.build_absolute_uri(reverse('finish_google_auth'))
    )
    return flow
Exemple #18
0
def sso(request):
    payload = request.GET.get('sso')
    signature = request.GET.get('sig')

    if None in [payload, signature]:
        return HttpResponseBadRequest(
            'No SSO payload or signature. Please contact support if this problem persists.'
        )

    ## Validate the payload

    try:
        payload = urllib.parse.unquote(payload)
        decoded = base64.decodestring(payload)
        assert 'nonce' in decoded
        assert len(payload) > 0
    except AssertionError:
        return HttpResponseBadRequest(
            'Invalid payload. Please contact support if this problem persists.'
        )

    key = str(settings.DISCOURSE_SSO_SECRET)  # must not be unicode
    h = hmac.new(key, payload, digestmod=hashlib.sha256)
    this_signature = h.hexdigest()

    if this_signature != signature:
        return HttpResponseBadRequest(
            'Invalid payload. Please contact support if this problem persists.'
        )

    ## Build the return payload

    qs = parse_qs(decoded)
    params = {
        'nonce': qs['nonce'][0],
        'email': request.user.email,
        'external_id': request.user.id,
        'username': request.user.username,
        'name': request.user.get_full_name(),
        'avatar_url':
        request.build_absolute_uri(request.user.profile.photo.url),
        'avatar_force_update': True,
        'admin': request.user.is_staff,
        'moderator': request.user.is_staff
    }

    return_payload = base64.encodestring(urllib.parse.urlencode(params))
    h = hmac.new(key, return_payload, digestmod=hashlib.sha256)
    query_string = urllib.parse.urlencode({
        'sso': return_payload,
        'sig': h.hexdigest()
    })

    ## Redirect back to Discourse

    url = '%s/session/sso_login' % settings.DISCOURSE_BASE_URL
    return HttpResponseRedirect('%s?%s' % (url, query_string))
Exemple #19
0
def payments_claim_initiate(request, user, email):
    payment = Payments.GetPayment(email=email)
    if payment is None:
        return False
    claim_code = Payments.GenerateClaimCode(user, payment)
    reclaim_url = request.build_absolute_uri(reverse("payments_claim_return", kwargs={"code": claim_code}))
    from tapiriik.web.email import generate_message_from_template, send_email
    message, plaintext_message = generate_message_from_template("email/payment_reclaim.html", {"url":reclaim_url})
    send_email(email, "Reclaim your payment on tapiriik.sfrunners.club", message, plaintext_message=plaintext_message)
    return True
Exemple #20
0
def parse_openid_response(request):
    """Parse an OpenID response from a Django request."""
    # Short cut if there is no request parameters.
    #if len(request.REQUEST) == 0:
    #    return None

    current_url = request.build_absolute_uri()

    consumer = make_consumer(request)
    return consumer.complete(dict(list(request.REQUEST.items())), current_url)
Exemple #21
0
def autorization_pdf_maker(request, parcela_id):
    now = datetime.datetime.now()
    parcela = get_object_or_404(Parcela, id=parcela_id)
    html = render_to_string('parcelas/pdf_autorizacion.html',
                            {'parcela': parcela,
                             'now': now})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename=parcela_{}.pdf'.format(parcela.id)
    weasyprint.HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response)
    return response
Exemple #22
0
def payments_claim_initiate(request, user, email):
    payment = Payments.GetPayment(email=email)
    if payment is None:
        return False
    claim_code = Payments.GenerateClaimCode(user, payment)
    reclaim_url = request.build_absolute_uri(reverse("payments_claim_return", kwargs={"code": claim_code}))
    from tapiriik.web.email import generate_message_from_template, send_email
    message, plaintext_message = generate_message_from_template("email/payment_reclaim.html", {"url":reclaim_url})
    send_email(email, "Reclaim your payment on tapiriik.com", message, plaintext_message=plaintext_message)
    return True
Exemple #23
0
def start_meeting(request):
    """
        Start a meeting with registrants (only hoster can do)
    """
    # check method and params
    if request.method != "GET":
        return HttpResponse(status=400)
    if request.user.is_anonymous:
        logger.error("EolZoom: User is Anonymous")
        return HttpResponse(status=400)
    if 'code' not in request.GET or 'data' not in request.GET:
        return HttpResponse(status=400)

    user = request.user
    authorization_code = request.GET.get('code')
    # data with meeting_id and course_id (BASE64)
    data = base64.b64decode(request.GET.get('data'))
    args = json.loads(data.decode("utf-8"))
    aux = ['block_id', 'course_id', 'meeting_id', 'restricted_access', 'email_notification']
    if not all([x in args for x in aux]):
        logger.error("EolZoom: Error with data: {}".format(args))
        return HttpResponse(status=400)
    try:
        usage_key = UsageKey.from_string(args['block_id'])
        course_key = CourseKey.from_string(args['course_id'])
    except InvalidKeyError:
        logger.error("EolZoom: Error with course_id or usage_key, data: {}".format(args))
        return HttpResponse(status=400)
    if type(args['restricted_access']) is not bool or type(args['email_notification']) is not bool:
        logger.error("EolZoom: Error with data(restricted_access or email_notification): {}".format(args))
        return HttpResponse(status=400)
    try:
        meeting_id = args['meeting_id']
        zoom_mapp = EolZoomMappingUserMeet.objects.get(meeting_id=meeting_id)
        if user != zoom_mapp.user:
            logger.error("EolZoom: Error in start_meeting, request.user != user_model.user, request.user: {}, user_model.user: {}".format(user, zoom_mapp.user))
            return HttpResponse(status=400)
        zoom_mapp.course_key = usage_key.course_key
        zoom_mapp.restricted_access = args['restricted_access']
        zoom_mapp.email_notification = args['email_notification']
        zoom_mapp.usage_key = usage_key
        zoom_mapp.save()
    except EolZoomMappingUserMeet.DoesNotExist:
        logger.error("EolZoom: Error with EolZoomMappingUserMeet dont exists, meeting_id: {}".format(meeting_id))
        return HttpResponse(status=400)
    redirect_uri = request.build_absolute_uri().split(
        '&code')[0]  # build uri without code param
    #redirect_uri = redirect_uri.replace('http', 'https')
    token = get_refresh_token(authorization_code, redirect_uri)
    if 'error' in token:
        logger.error("Error get_refresh_token {}".format(token['error']))
        return HttpResponse(status=400)
    _update_auth(user, token['refresh_token'])

    return HttpResponseRedirect(create_start_url(args['meeting_id']))
Exemple #24
0
def get_request_key(request):
    """Ask tequla server for the key"""

    params = "urlaccess=" + request.build_absolute_uri(
    ) + "\nservice=" + settings.TEQUILA_SERVICE + "\nrequest=name,firstname,email,uniqueid"
    if settings.TEQUILA_ALLOW_GUEST:
        params += '\nallows=categorie=epfl-guests'
    f = urllib.request.urlopen(
        settings.TEQUILA_SERVER + '/cgi-bin/tequila/createrequest',
        params.encode())
    return re.search('key=(.*)', f.read().decode()).group(1)
Exemple #25
0
def wm_update(request, username):
	'''
	Password Manager: store new user password in db
	'''
	try:
		username = str(username)
		full_url = ''.join([request.build_absolute_uri()])
		_get_user = web_manager_password.objects.create(site_url=full_url, account_name=str(username), account_password=encrypt_password(request.POST['fld_n_password']))
		return HttpResponseRedirect(reverse_lazy("web_manager:manage_password", kwargs={'username':username}))
	except:
		return HttpResponseRedirect(reverse_lazy("web_manager:manage_password", username))
    def login(self, request, user):
        """
        Preserve badgr_app session data across Django login() boundary
        """
        badgr_app = get_session_badgr_app(request)

        if badgr_app is None:
            url = request.build_absolute_uri()
            print(('Badgr app is none in login {}'.format(url)))
        ret = super(BadgrAccountAdapter, self).login(request, user)
        set_session_badgr_app(request, badgr_app)
        return ret
Exemple #27
0
def get_pdfas_url(request, sign_data):
    values = {
        'connector': 'onlinebku',
        'invoke-app-url': request.build_absolute_uri(reverse('ecs.signature.views.sign_receive', kwargs={'pdf_id': sign_data.id})),
        'invoke-app-url-target': '_top',
        'invoke-app-error-url': request.build_absolute_uri(reverse('ecs.signature.views.sign_error', kwargs={'pdf_id': sign_data.id})),
        'locale': 'DE',
        'num-bytes': str(len(sign_data['pdf_data'])),
        'sig_type': 'SIGNATURBLOCK_DE',
        'pdf-url': request.build_absolute_uri(reverse('ecs.signature.views.sign_send', kwargs={'pdf_id': sign_data.id})),

        'verify-level': 'intOnly', # Dies bedeutet, dass eine Signaturprüfung durchgeführt wird, allerdings ohne Zertifikatsprüfung.
        'filename': sign_data['document_filename'],

        #'preview': 'false',
        #'mode': 'binary',
        #'inline': 'false',
        #'pdf-id': sign_data.id,
    }
    data = urllib.parse.urlencode({k: v.encode('utf-8') for k, v in values.items()})
    return '{0}Sign?{1}'.format(settings.PDFAS_SERVICE, data)
Exemple #28
0
    def __init__(self, request, *args, **kwargs):
        super(DjangoError, self).__init__(*args, **kwargs)

        self.update({
            'url': request.build_absolute_uri(),
            'type': 'django',
        })

        try:
            self['user'] = json.dumps(self.get_user_info(request))
        except Exception:
            logger.exception("Exception whilst reporting error to keyerror.com")
Exemple #29
0
 def redirect_weixin_login(self, request):
     """
     跳转到微信登录
     """
     url = urllib.parse.urlparse(request.build_absolute_uri())
     path = weixin_settings.WEIXIN_LOGIN_URL
     query = urllib.parse.urlencode({'c_url': request.get_full_path()})
     callback_url = urllib.parse.urlunsplit(
         (url.scheme, url.netloc, path, query, url.fragment))
     state = self.set_weixin_oauth_state(request)
     redirect_uri = self.get_oauth_redirect_url(callback_url, state)
     return HttpResponseRedirect(redirect_uri)
def transform_usage_error(caller, self, request, *args, **kwargs):
    """
    Can be used for both html and ajax requests, so only 'error' HTTP codes should be returned
    if an exception is encountered.
    """
    dm = request.datamanager

    return_to_home_url = game_view_url("pychronia_game-homepage", datamanager=dm)
    return_to_home = HttpResponseRedirect(return_to_home_url)

    from ..authentication import TEMP_URL_USERNAME
    return_to_login_url = game_view_url("pychronia_game-login", datamanager=dm)
    return_to_login_next_url = request.build_absolute_uri()
    # we do a HACK to deal with in-url usernames (except UNIVERSAL_URL_USERNAME username, which stays as is)
    return_to_login_next_url = return_to_login_next_url.replace("/%s/" % dm.user.username, "/%s/" % TEMP_URL_USERNAME)
    return_to_login_qs = urllib.parse.urlencode(dict(next=return_to_login_next_url))
    return_to_login = HttpResponseRedirect("%s?%s" % (return_to_login_url, return_to_login_qs))

    assert urlresolvers.resolve(return_to_home_url)
    try:

        return caller(self, request, *args, **kwargs)

    except AccessDeniedError as e:

        if request.is_ajax():
            return HttpResponseForbidden(repr(e))

        if request.datamanager.user.is_impersonation:
            # Will mainly happen when we switch between two impersonations with different access rights, on a restricted page
            dm.user.add_warning(_("Currently impersonated user can't access view '%s'") % self.TITLE)
        else:
            dm.user.add_error(_("Access denied to page %s") % self.TITLE)
            dm.logger.warning("Access denied to page %s" % self.TITLE, exc_info=True)

        if not request.datamanager.user.impersonation_target and request.datamanager.user.is_anonymous:
            return return_to_login  # special case for REAL anonymous users
        return return_to_home

    except (GameError, POSError) as e:

        if request.is_ajax():
            return HttpResponseBadRequest(repr(e))

        dm.logger.critical("Unexpected game error in %s" % self.NAME, exc_info=True)
        dm.user.add_error(_("An unexpected server error occurred, please retry (%s)") % (
        e if dm.is_master() else _("contact webmaster if it persists")))
        return return_to_home

    # else, we let 500 handler take are of all other (very abnormal) exceptions

    assert False
Exemple #31
0
def render_openid_request(request, openid_request, return_to, trust_root=None):
    """Render an OpenID authentication request."""
    if trust_root is None:
        trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                             request.build_absolute_uri('/'))

    if openid_request.shouldSendRedirect():
        redirect_url = openid_request.redirectURL(trust_root, return_to)
        return HttpResponseRedirect(redirect_url)
    else:
        form_html = openid_request.htmlMarkup(
            trust_root, return_to, form_tag_attrs={'id': 'openid_message'})
        return HttpResponse(form_html, content_type='text/html;charset=UTF-8')
Exemple #32
0
def view_post(request, slug):
    post = get_object_or_404(Blog, slug=slug)

    rest_url_a = "http://api.facebook.com/restserver.php?format=json&method=links.getStats&urls="+"http://"+post.url
    rest_url_b = rest_url_a.replace('http://www.heyandie.com/blog','http://www.heyandie.com/article')

    response_a = urllib.request.urlopen(rest_url_a)
    response_b = urllib.request.urlopen(rest_url_b)

    data_a = json.loads(response_a.read().decode('utf-8'))
    data_b = json.loads(response_b.read().decode('utf-8'))

    share_count = 0;
    if 0 in data_a:
        share_count += data_a[0]['total_count']

    if 0 in data_b:
        share_count += data_b[0]['total_count']

    og_tags = {
        'fb:app_id': 224598357874885,
        'og:type': 'article',
        'article:publisher': 'https://facebook.com/andie.rabino',
        'og:site_name': 'Andie Rabino',
        'og:title': post.title,
        'og:description': post.excerpt,
        'og:url': request.build_absolute_uri(reverse('view_blog_post', kwargs={'slug':post.slug})),
        'og:image': request.build_absolute_uri(reverse('index')) + post.image
    }
    title = post.title
    return render_to_response('blog/post.html', {
        'og_tags': og_tags,
        'post': post,
        'title': title,
        'posts': Blog.objects.exclude(id__in=(post.id,)).order_by('-posted')[:4],
        'header_class': "header-white",
        'share_count': share_count
    })
Exemple #33
0
def oauth_session(request, state=None, token=None):
    """ Constructs the OAuth2 session object. """
    if settings.DISCORD_REDIRECT_URI is not None:
        redirect_uri = MYURL+'discord/cb'
    else:
        redirect_uri = request.build_absolute_uri(
            reverse('discord_bind_callback'))
    scope = (['email','identify',] if settings.DISCORD_EMAIL_SCOPE
             else ['identity', 'guilds.join'])
    return OAuth2Session(settings.DISCORD_CLIENT_ID,
                         redirect_uri=redirect_uri,
                         scope=scope,
                         token=token,
                         state=state)
Exemple #34
0
def sso(request):
    payload = request.GET.get('sso')
    signature = request.GET.get('sig')

    if None in [payload, signature]:
        return HttpResponseBadRequest('No SSO payload or signature. Please contact support if this problem persists.')

    ## Validate the payload

    try:
        payload = urllib.parse.unquote(payload)
        decoded = base64.decodestring(payload)
        assert 'nonce' in decoded
        assert len(payload) > 0
    except AssertionError:
        return HttpResponseBadRequest('Invalid payload. Please contact support if this problem persists.')

    key = str(settings.DISCOURSE_SSO_SECRET) # must not be unicode
    h = hmac.new(key, payload, digestmod=hashlib.sha256)
    this_signature = h.hexdigest()

    if this_signature != signature:
        return HttpResponseBadRequest('Invalid payload. Please contact support if this problem persists.')

    ## Build the return payload

    qs = parse_qs(decoded)
    params = {
        'nonce': qs['nonce'][0],
        'email': request.user.email,
        'external_id': request.user.id,
        'username': request.user.username,
        'name': request.user.get_full_name(),
        'avatar_url': request.build_absolute_uri(request.user.profile.photo.url),
        'avatar_force_update': True,
        'admin': request.user.is_staff,
        'moderator': request.user.is_staff
    }

    return_payload = base64.encodestring(urllib.parse.urlencode(params))
    h = hmac.new(key, return_payload, digestmod=hashlib.sha256)
    query_string = urllib.parse.urlencode({'sso': return_payload, 'sig': h.hexdigest()})

    ## Redirect back to Discourse

    url = '%s/session/sso_login' % settings.DISCOURSE_BASE_URL
    return HttpResponseRedirect('%s?%s' % (url, query_string))
Exemple #35
0
def index(request):
    before = request.GET.get('before')
    after = request.GET.get('after')
    form = ImageForm({'before': before, 'after': after})
    if form.is_valid():
        before, after = form.generateImages()
        context = {
            'before': before,
            'after': after
        }
    else:
        example = reverse('homepage')
        context = {
            'usage': True,
            'example': request.build_absolute_uri(example)
        }
    return render(request, 'home.html', context)
def home(request):
    context = {}
    context['server'] = request.build_absolute_uri('/')
    verify_auth(request, context)
    try:
        if r.get('recent') == b'null' or r.get('recent') == None:
            context['cached'] = False  
            item_req = urllib.request.Request('http://' + settings.EXP_API + ':8000/api/data/recent/6')
            item_json = urllib.request.urlopen(item_req).read().decode('utf-8')
            resp = json.loads(item_json)
            r.set('recent', item_json)
        else:
            context['cached'] = True 
            resp = json.loads(r.get('recent').decode('utf-8'))
    except redis.ConnectionError:
        item_req = urllib.request.Request('http://' + settings.EXP_API + ':8000/api/data/recent/6')
        item_json = urllib.request.urlopen(item_req).read().decode('utf-8')
        resp = json.loads(item_json)
    context["items"] = resp["resp"]["items"]
    context["location"] = "home"
    return render(request, "index.html", context)
Exemple #37
0
def index(request):
	if request.method == 'POST':
		dudas_form = DudasForm(request.POST)

		if dudas_form.is_valid():
			nom = escape(dudas_form.cleaned_data['nombre'])
			tip = int(dudas_form.cleaned_data['tipo'])
			mail = escape(dudas_form.cleaned_data['email'])
			det = escape(dudas_form.cleaned_data['detalle'])
			
			# Enviar notificación
			TIPOS_DUDAS = ( ('-1', '-- Seleccione un tipo --'), ('0', 'Área comercial'), ('1', 'Área académica'), ('2', 'Registro y Control'),  ('3', 'Área financiera'), ('4', 'Área de marketing'), ('5', 'Otras cuestiones'))
			path = request.build_absolute_uri(reverse('faq:index'))
			mensj = "Se ha recibido una nueva duda desde " + path +".\n\nNombre: " + nom + "\nCorreo electrónico: " + mail + "\nDetalle: " + det
			email_dest = '*****@*****.**'

			send_mail('Formación CRM - Duda de ' + TIPOS_DUDAS[tip+1][1], mensj, settings.DEFAULT_FROM_EMAIL, [email_dest], fail_silently=False)
			
			return render(request, 'faq/redirect.html')
			
		else:
			return render(request, 'faq/index.html', { 'dudas_form': dudas_form })
			
	else:   # GET
		dudas_form = DudasForm()
		fuente = get_object_or_404(FuentesJSON, nombre = "faq")

		response = urllib.request.urlopen(fuente.filename_fuente)
		preguntas = json.loads(response.read().decode('utf-8'))

		context = {
				'dudas_form': dudas_form,
				'preguntas': preguntas
		}
		
		return render(request, 'faq/index.html', context)
Exemple #38
0
def payments_send_confirmation(request, email):
    dashboard_url = request.build_absolute_uri(reverse("dashboard"))
    from tapiriik.web.email import generate_message_from_template, send_email

    message, plaintext_message = generate_message_from_template("email/payment_confirm.html", {"url": dashboard_url})
    send_email(email, "Thanks, %s!" % request.POST["first_name"], message, plaintext_message=plaintext_message)
Exemple #39
0
    def get_url(self, request): return request.build_absolute_uri()

    def get_redirect(self, request, url):