views.py 10.1 KB
Newer Older
1
from go.models import URL, RegisteredUser
Jean Michel Rouly's avatar
Jean Michel Rouly committed
2
from go.forms import URLForm, SignupForm
3
from datetime import timedelta
4
from django.conf import settings
5
from django.http import Http404, HttpResponseServerError
6
from django.utils import timezone
Jean Michel Rouly's avatar
Jean Michel Rouly committed
7
from django.contrib.auth.models import User
8
from django.core.exceptions import PermissionDenied, ValidationError
9
from django.core.mail import send_mail
10 11
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test, login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
12
from django.shortcuts import render, get_object_or_404, redirect
13
import os
14

Jean Michel Rouly's avatar
Jean Michel Rouly committed
15 16 17 18 19 20 21

##############################################################################
"""
Define useful helper methods here.
"""


22
def is_approved( user ):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
23 24 25 26 27
    """
    This function checks if a user account has a corresponding RegisteredUser,
    thus checking if the user is registered.
    """

28
    try:
29
        registered = RegisteredUser.objects.get( username=user.username )
30
        return registered.approved
31 32 33
    except RegisteredUser.DoesNotExist:
        return False

Jean Michel Rouly's avatar
Jean Michel Rouly committed
34

35 36 37 38 39 40 41 42 43 44 45 46 47
def is_registered(user):
    """
    This function checks if a user account has a corresponding RegisteredUser,
    thus checking if the user is registered.
    """

    try:
        registered = RegisteredUser.objects.get( username=user.username )
        return True
    except RegisteredUser.DoesNotExist:
        return False


Jean Michel Rouly's avatar
Jean Michel Rouly committed
48 49 50 51 52 53
##############################################################################
"""
Define error page handling here.
"""


54
def error_404(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
55 56 57 58
    """
    Error 404 view, in case a url is not found.
    """

59 60 61 62 63
    return render(request, '404.html', {
    },
    )

def error_500(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
64 65 66 67
    """
    Error 500 view, in case a server error occurs.
    """

68 69 70 71
    return render(request, '500.html', {
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
72 73 74 75 76 77
##############################################################################
"""
Define user views here.
"""


78
@login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
79
def index(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
80 81 82 83 84 85 86
    """
    This view handles the homepage that the user is presented with when
    they request '/'. If they're not logged in, they're redirected to
    login. If they're logged in but not registered, they're given the
    not_registered error page. If they are logged in AND registered, they
    get the URL registration form.
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
87

Jean Michel Rouly's avatar
Jean Michel Rouly committed
88
    # If the user isn't registered, don't give them any leeway.
89
    if not is_approved(request.user):
90 91
        return render(request, 'not_registered.html')

92 93 94 95 96 97
    url_form = URLForm() # unbound form

    if request.method == 'POST':
        url_form = URLForm( request.POST ) # bind dat form
        if url_form.is_valid():

Jean Michel Rouly's avatar
Jean Michel Rouly committed
98 99
            # We don't commit the url object yet because we need to add its
            # owner, and parse its date field.
100 101 102
            url = url_form.save(commit=False)
            url.owner = request.user

Jean Michel Rouly's avatar
Jean Michel Rouly committed
103
            # If the user entered a short url, it's already been validated,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
104 105
            # so accept it. If they did not, however, then generate a
            # random one and use that instead.
106
            short = url_form.cleaned_data.get('short').strip()
107 108 109
            if len(short) > 0:
                url.short = short
            else:
110 111 112 113 114 115 116 117 118 119
                # If the user didn't enter a short url, generate a random
                # one. However, if a random one can't be generated, return
                # a 500 server error.
                random_short = URL.generate_valid_short()
                if random_short is None:
                    return HttpResponseServerError(
                        render(request, '500.html', {})
                    )
                else:
                    url.short = random_short
120

Jean Michel Rouly's avatar
Jean Michel Rouly committed
121 122 123
            # Grab the expiration field value. It's currently an unsable
            # string value, so we need to parse it into a datetime object
            # relative to right now.
124
            expires = url_form.cleaned_data.get('expires')
125 126 127 128 129 130 131 132 133 134

            if expires == URLForm.DAY:
                url.expires = timezone.now() + timedelta(days=1)
            elif expires == URLForm.WEEK:
                url.expires = timezone.now() + timedelta(weeks=1)
            elif expires == URLForm.MONTH:
                url.expires = timezone.now() + timedelta(weeks=3)
            else:
                pass # leave the field NULL

Jean Michel Rouly's avatar
Jean Michel Rouly committed
135 136
            # Make sure that our new URL object is clean, then save it and
            # let's redirect to view this baby.
137 138
            url.full_clean()
            url.save()
Jean Michel Rouly's avatar
Jean Michel Rouly committed
139
            return redirect('view', url.short)
140 141 142

    return render(request, 'index.html', {
        'form': url_form,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
143 144 145
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
146

Jean Michel Rouly's avatar
Jean Michel Rouly committed
147
def view(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
148 149 150 151 152
    """
    This view allows the user to view details about a URL. Note that they
    do not need to be logged in to view info.
    """

Jean Michel Rouly's avatar
Jean Michel Rouly committed
153
    url = get_object_or_404(URL, short__iexact = short)
154

Jean Michel Rouly's avatar
Jean Michel Rouly committed
155
    return render(request, 'view.html', {
156 157 158 159
        'url': url,
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
160

161
@login_required
162
def my_links(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
163 164 165 166 167
    """
    This view displays all the information about all of your URLs. You
    obviously need to be logged in to view your URLs.
    """

168
    if not is_approved(request.user):
169
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
170

171
    urls = URL.objects.filter( owner = request.user )
172 173 174

    domain = request.META.get('HTTP_HOST') + "/"

175
    return render(request, 'my_links.html', {
176
        'urls' : urls,
177
        'domain' : domain,
178 179 180
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
181

182
@login_required
183
def delete(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
184 185 186 187 188
    """
    This view deletes a URL if you have the permission to. User must be
    logged in and registered, and must also be the owner of the URL.
    """

189
    if not is_approved(request.user):
190
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
191

Jean Michel Rouly's avatar
Jean Michel Rouly committed
192
    url = get_object_or_404(URL, short__iexact = short )
193 194
    if url.owner == request.user:
        url.delete()
195 196
        return redirect('my_links')
    else:
197
        raise PermissionDenied()
198

Jean Michel Rouly's avatar
Jean Michel Rouly committed
199

200
@login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
201
def signup(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
202 203 204 205 206
    """
    This view presents the user with a registration form. You can register
    yourself, or another person.

    """
207 208 209 210 211 212 213 214 215 216 217 218 219
    if is_registered(request.user) and not request.user.is_staff:
        return render(request, 'signup.html', {
            'registered': True,
        },
        )

    signup_form = SignupForm(initial={'username': request.user.username})
    # Non-staff have the username field read-only and pre-filled
    if request.user.is_staff:
        signup_form = SignupForm()
    else:
        signup_form = SignupForm(initial={'username': request.user.username})
        signup_form.fields['username'].widget.attrs['readonly'] = 'readonly'
Jean Michel Rouly's avatar
Jean Michel Rouly committed
220 221

    if request.method == 'POST':
222 223 224
        signup_form = SignupForm(request.POST, initial={'approved': False,
            'username': request.user.username})

225
        if signup_form.is_valid():
226 227 228 229 230
            # Prevent hax: if not staff, force the username back to the request username.
            if not request.user.is_staff:
                username = request.user.username
            else:
                username = signup_form.cleaned_data.get('username')
231 232
            full_name = signup_form.cleaned_data.get('full_name')
            description = signup_form.cleaned_data.get('description')
233

234 235 236 237 238 239 240
            # Only send mail if we've defined the mailserver
            if settings.EMAIL_HOST and settings.EMAIL_PORT:
                send_mail('Signup from %s' % (username), '%s signed up at %s\n'
                    'Username: %s\nMessage: %s\nPlease attend to this request at '
                    'your earliest convenience.' % (str(full_name),
                    str(timezone.now()).strip(), str(username), str(description)),
                    settings.EMAIL_FROM, [settings.EMAIL_TO])
241

242 243
            signup_form.save()

244
            return redirect('registered')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
245

Jean Michel Rouly's avatar
Jean Michel Rouly committed
246
    return render(request, 'signup.html', {
247
        'form': signup_form,
248
        'registered': False,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
249 250
    },
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
251

Jean Michel Rouly's avatar
Jean Michel Rouly committed
252

Jean Michel Rouly's avatar
Jean Michel Rouly committed
253
def redirection(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
254 255 256
    """
    This view redirects a user based on the short URL they requested.
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
257

Jean Michel Rouly's avatar
Jean Michel Rouly committed
258
    url = get_object_or_404( URL, short__iexact = short )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
259 260
    url.clicks = url.clicks + 1
    url.save()
261

Jean Michel Rouly's avatar
Jean Michel Rouly committed
262 263 264 265 266
    """
    Include server-side tracking because there is no template displayed to
    the user which would include javascript tracking.
    """

267 268
    from piwikapi.tracking import PiwikTracker
    from django.conf import settings
269 270 271 272 273 274 275 276 277
    # First, if PIWIK variables are undefined, don't try to push
    if settings.PIWIK_SITE_ID is not "" and settings.PIWIK_URL is not "":
        try:
            piwiktracker = PiwikTracker(settings.PIWIK_SITE_ID, request)
            piwiktracker.set_api_url(settings.PIWIK_URL)
            piwiktracker.do_track_page_view('Redirect to %s' % url.target)
        # Second, if we do get an error, don't let that keep us from redirecting
        except:
            pass
278 279

    return redirect( url.target )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
280 281


282 283 284 285 286 287 288 289 290 291 292 293 294
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='about'):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, displaying the login page if necessary.
    """
    return user_passes_test(
        lambda u: u.is_active and u.is_staff,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )(view_func)


@staff_member_required
Chris Reffett's avatar
Chris Reffett committed
295
def useradmin(request):
296 297 298 299 300
    """
    This view is a simplified admin panel, so that staff don't need to log in
    to approve links
    """
    if request.POST:
301
        userlist = request.POST.getlist('username')
302
        if '_approve' in request.POST:
303 304 305 306
            for name in userlist:
                toapprove = RegisteredUser.objects.get(username=name)
                toapprove.approved = True
                toapprove.save()
307
        elif '_deny' in request.POST:
308 309 310
            for name in userlist:
                todeny = RegisteredUser.objects.get(username=name)
                todeny.delete()
311
    need_approval = RegisteredUser.objects.filter(approved=False)
Chris Reffett's avatar
Chris Reffett committed
312
    return render(request, 'useradmin.html',{
313 314 315 316 317
        'need_approval': need_approval
    },
    )


Jean Michel Rouly's avatar
Jean Michel Rouly committed
318 319 320 321 322 323 324 325 326 327 328
##############################################################################
"""
Define static user views here.
"""


def about(request):
    return render(request, 'about.html', {
    },
    )

329 330 331 332
def registered(request):
    return render(request, 'registered.html', {
    },
    )