Beispiel #1
0
def link_shortener(request):
    pygmy_client = pygmy_client_object(settings, request)
    if request.method == 'POST':
        form = URLForm(request.POST)
        context = dict(form=form)
        if form.is_valid():
            try:
                resp = pygmy_client.shorten(
                    long_url=form.cleaned_data['long_url'],
                    custom_code=form.cleaned_data['custom_url'],
                    secret=form.cleaned_data['secret_key'],
                    expire_after=form.cleaned_data['remember_time'])
            except UnAuthorized as e:
                return render(request,
                              'unauthorized.html',
                              context=API_ERROR(e.args[0]),
                              status=401)
            except (ObjectNotFound, InvalidInput) as e:
                return render(request,
                              '400.html',
                              context=API_ERROR(e.args[0]),
                              status=400)
            short_code = resp['short_code']
        else:
            return render(request,
                          "invalid_form.html",
                          context=context,
                          status=400)
        return redirect('get_short_link', code=short_code)

    if request.method == 'GET':
        return render(request, '400.html', status=400)
Beispiel #2
0
def login(request):
    if request.method == 'POST':
        pygmy_client = pygmy_client_object(settings, request)
        form = LoginForm(request.POST)
        context = dict(form=form)
        if form.is_valid():
            context['login_success'] = True
            try:
                user_obj = pygmy_client.login(
                    email=form.cleaned_data['email'],
                    password=form.cleaned_data['password'])
                context = {'email': user_obj['email'],
                           'f_name': user_obj['f_name'],
                           REFRESH_COOKIE_NAME: user_obj['refresh_token']}
            except InvalidInput as e:
                return render(request, 'unauthorized.html',
                              context=API_ERROR(e.args[0]), status=400)
            except ObjectNotFound as e:
                return render(request, '404.html',
                              context=API_ERROR(e.args[0]), status=404)
            response = redirect('dashboard')
            expires = datetime.datetime.utcnow() + datetime.timedelta(days=7)
            _ = [response.set_cookie(
                    k, v, expires=expires) for k, v in context.items()]
            # access token lifetime till browser session
            response.set_cookie(AUTH_COOKIE_NAME, user_obj['access_token'])
        else:
            response = render(
                request, "invalid_form.html", context=context, status=400)
        return response

    if request.method == 'GET':
        return redirect('/')
Beispiel #3
0
def signup(request):
    if request.method == 'GET':
        return redirect('/')

    if request.method == 'POST':
        pygmy_client = pygmy_client_object(settings, request)
        form = SignUpForm(request.POST)
        context = dict(form=form)
        if not form.is_valid():
            return render(request,
                          "invalid_form.html",
                          context=context,
                          status=400)
        context['signup_success'] = True
        try:
            user_obj = pygmy_client.signup(form.cleaned_data)
            context = {
                'email': user_obj['email'],
                'f_name': user_obj['f_name'],
                REFRESH_COOKIE_NAME: user_obj['refresh_token']
            }
        except (InvalidInput, ObjectNotFound) as e:
            return render(request,
                          '400.html',
                          context=API_ERROR(e.args[0]),
                          status=400)
        response = redirect('/')
        expires = datetime.datetime.utcnow() + datetime.timedelta(days=7)
        _ = [
            response.set_cookie(k, v, expires=expires)
            for k, v in context.items()
        ]
        # access token lifetime till browser session
        response.set_cookie(AUTH_COOKIE_NAME, user_obj['access_token'])
        return response
Beispiel #4
0
def link_auth(request):
    """View for handeling protected short links"""
    if request.method == 'GET':
        code = request.GET.get('next')
        if not code:
            return redirect('400.html')
        return render(request, 'auth/link_auth.html')

    if request.method == 'POST':
        pygmy_client = pygmy_client_object(settings, request)
        data = json.loads(request.body.decode('utf-8'))
        code = data['code']
        secret_key = data['secret_key']
        if not code or not secret_key:
            return render(request, '400.html', status=400)
        try:
            if code.startswith('+') or code.endswith('+'):
                clickmeta = pygmy_client.link_stats(code,
                                                    secret_key=secret_key)
                response = dict(clickmeta=clickmeta)
            else:
                url_obj = pygmy_client.unshorten(code, secret=secret_key)
                response = dict(long_url=url_obj['long_url'])
        except UnAuthorized:
            response = dict(error='Wrong secret key.')
        except ObjectNotFound as e:
            return render(request,
                          '404.html',
                          context=API_ERROR(e.args[0]),
                          status=404)
        # return redirect(long_url, permanent=True)
        return JsonResponse(response)
Beispiel #5
0
def short_link_stats(request, code):
    """Get stats about short code."""
    pygmy_client = pygmy_client_object(settings, request)
    if request.method == 'GET':
        try:
            clickmeta = pygmy_client.link_stats(code)
            clickmeta['country_stats'] = sorted(
                clickmeta['country_stats'].items(),
                key=operator.itemgetter(1),
                reverse=True)

            country_stats = [(country, iso2full.get(country, "unknown"), hits)
                             for (country, hits) in clickmeta['country_stats']]
            clickmeta['country_stats'] = country_stats

            clickmeta['referrer'] = sorted(clickmeta['referrer'].items(),
                                           key=operator.itemgetter(1),
                                           reverse=True)

            context = dict(clickmeta=clickmeta)
        except (ObjectNotFound, LinkExpired) as e:
            return render(request,
                          '404.html',
                          context=API_ERROR(e.args[0]),
                          status=404)
        return render(request, 'pygmy/link_stats.html', context=context)
Beispiel #6
0
def dashboard(request):
    """Returns the list of signed up user links"""
    access_token = request.COOKIES.get(AUTH_COOKIE_NAME)
    if not access_token:
        return render(request, '400.html', context=INVALID_TOKEN, status=400)
    pygmy_client = pygmy_client_object(settings, request)
    try:
        links = pygmy_client.list_links(access_token=access_token)
    except UnAuthorized as e:
        return render(request,
                      'unauthorized.html',
                      context=API_ERROR(e.args[0]),
                      status=403)
    except ObjectNotFound as e:
        return render(
            request, '404.html', context=API_ERROR(e.args[0]), status=404)
    context = dict(links=links)
    return render(request, 'pygmy/dashboard.html', context=context)
Beispiel #7
0
def link_unshorten(request, code):
    """This redirects to the long URL from short URL"""
    pygmy_client = pygmy_client_object(settings, request)
    if request.method == 'GET':
        try:
            url_obj = pygmy_client.unshorten(code)
        except UnAuthorized:
            return redirect('/link/secret?next={}'.format(code))
        except (LinkExpired, ObjectNotFound) as e:
            return render(request, '404.html',
                          context=API_ERROR(e.args[0]), status=404)
        long_url = url_obj['long_url']
        return redirect(long_url, permanent=True)
Beispiel #8
0
def get_short_link(request, code):
    """TODO: Validate code"""
    if request.method == 'GET':
        try:
            # TODO: use urljoin
            schema = 'https://' if request.is_secure() else 'http://'
            url_obj = {}
            url_obj['short_url'] = (schema + request.META['HTTP_HOST'] + '/' +
                                    url_obj.get('short_code', code))
        except ObjectNotFound as e:
            return render(request,
                          '404.html',
                          context=API_ERROR(e.args[0]),
                          status=404)
        context = dict(short_url=url_obj['short_url'], short_code=code)
        return render(request, 'pygmy/short_url.html', context=context)
    return render(request, '400.html', status=400)