views.py 12.3 KB
Newer Older
1
# Django Imports
2
from django.conf import settings
3
from django.http import HttpResponseServerError  # Http404
4
from django.utils import timezone
5
from django.core.exceptions import PermissionDenied  # ValidationError
6
from django.core.mail import send_mail, EmailMessage
7
from django.contrib.auth import REDIRECT_FIELD_NAME
David Haynes's avatar
David Haynes committed
8
from django.contrib.auth.models import User
9
from django.contrib.auth.decorators import user_passes_test, login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
10
from django.shortcuts import render, get_object_or_404, redirect
11

12 13 14 15 16 17
# App Imports
from go.models import URL, RegisteredUser
from go.forms import URLForm, SignupForm

# Other Imports
from datetime import timedelta
Jean Michel Rouly's avatar
Jean Michel Rouly committed
18

Jean Michel Rouly's avatar
Jean Michel Rouly committed
19
def index(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
20 21 22 23 24 25 26
    """
    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
27

28 29 30
    # If the user is not authenticated, show them a public landing page.
    if not request.user.is_authenticated():
        return render(request, 'public_landing.html')
31 32
    # If the user isn't approved, don't give them any leeway.
    elif not request.user.registereduser.approved:
33 34
        return render(request, 'not_registered.html')

35
    url_form = URLForm(host=request.META.get('HTTP_HOST'))  # unbound form
36 37

    if request.method == 'POST':
38
        url_form = URLForm(request.POST, host=request.META.get('HTTP_HOST'))  # bind dat form
39 40
        if url_form.is_valid():

Jean Michel Rouly's avatar
Jean Michel Rouly committed
41 42
            # We don't commit the url object yet because we need to add its
            # owner, and parse its date field.
43 44 45
            url = url_form.save(commit=False)
            url.owner = request.user

Jean Michel Rouly's avatar
Jean Michel Rouly committed
46
            # If the user entered a short url, it's already been validated,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
47 48
            # so accept it. If they did not, however, then generate a
            # random one and use that instead.
49
            short = url_form.cleaned_data.get('short').strip()
50 51 52
            if len(short) > 0:
                url.short = short
            else:
53 54 55 56 57 58
                # 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(
59
                        render(request, '500.html', {})
60 61 62
                    )
                else:
                    url.short = random_short
63

Jean Michel Rouly's avatar
Jean Michel Rouly committed
64 65 66
            # 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.
67
            expires = url_form.cleaned_data.get('expires')
68 69 70 71 72 73 74

            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)
Matthew Rodgers's avatar
Matthew Rodgers committed
75 76
            elif expires == URLForm.CUSTOM:
                url.expires = url_form.cleaned_data.get('expires_custom')
77
            else:
78
                pass  # leave the field NULL
79

Jean Michel Rouly's avatar
Jean Michel Rouly committed
80 81
            # Make sure that our new URL object is clean, then save it and
            # let's redirect to view this baby.
82 83
            url.full_clean()
            url.save()
Jean Michel Rouly's avatar
Jean Michel Rouly committed
84
            return redirect('view', url.short)
85

86
    return render(request, 'core/index.html', {
87
        'form': url_form,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
88 89 90
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
91

Jean Michel Rouly's avatar
Jean Michel Rouly committed
92
def view(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
93 94 95 96 97
    """
    This view allows the user to view details about a URL. Note that they
    do not need to be logged in to view info.
    """

Nicholas Anderson's avatar
Nicholas Anderson committed
98
    domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
99

100
    url = get_object_or_404(URL, short__iexact=short)
101

Jean Michel Rouly's avatar
Jean Michel Rouly committed
102
    return render(request, 'view.html', {
103
        'url': url,
104
        'domain': domain,
105 106 107
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
108

109
@login_required
110
def my_links(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
111 112 113 114 115
    """
    This view displays all the information about all of your URLs. You
    obviously need to be logged in to view your URLs.
    """

116
    if not request.user.registereduser.approved:
117
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
118

119
    urls = URL.objects.filter(owner=request.user)
120

121
    domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
122

123
    return render(request, 'my_links.html', {
124 125
        'urls': urls,
        'domain': domain,
126 127 128
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
129

130
@login_required
131
def delete(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
132 133 134 135 136
    """
    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.
    """

137
    if not request.user.registereduser.approved:
138
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
139

140
    url = get_object_or_404(URL, short__iexact=short)
141 142
    if url.owner == request.user:
        url.delete()
143 144
        return redirect('my_links')
    else:
145
        raise PermissionDenied()
146

Jean Michel Rouly's avatar
Jean Michel Rouly committed
147

148
@login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
149
def signup(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
150
    """
151
    This view presents the user with a registration form. You can register yourself.
Jean Michel Rouly's avatar
Jean Michel Rouly committed
152
    """
153
    # Do not display signup page to registered or approved users (Staff can still see these pages)
154 155 156 157 158 159 160
    if request.user.registereduser.registered and not request.user.is_staff:
        return render(request, 'registered.html', {})
    elif request.user.registereduser.approved and not request.user.is_staff:
        return render(request, 'core/index.html', {})

    signup_form = SignupForm(request)

161
    if request.user.is_staff:
David Haynes's avatar
David Haynes committed
162
        signup_form = SignupForm(request)
163
    else:
David Haynes's avatar
David Haynes committed
164
        signup_form = SignupForm(request,
165 166
            initial={'full_name': request.user.first_name + " " + request.user.last_name})
        signup_form.fields['full_name'].widget.attrs['readonly'] = 'readonly'
Jean Michel Rouly's avatar
Jean Michel Rouly committed
167 168

    if request.method == 'POST':
169 170 171
        signup_form = SignupForm(request, request.POST, instance=request.user.registereduser,
            initial={'full_name': request.user.first_name + " " + request.user.last_name})
        signup_form.fields['full_name'].widget.attrs['readonly'] = 'readonly'
172

173 174
        if signup_form.is_valid():
            description = signup_form.cleaned_data.get('description')
175
            full_name = signup_form.cleaned_data.get('full_name')
176
            organization = signup_form.cleaned_data.get('organization')
177
            registered = signup_form.cleaned_data.get('registered')
178

179 180
            # Only send mail if we've defined the mailserver
            if settings.EMAIL_HOST and settings.EMAIL_PORT:
181 182
                user_mail = username + settings.EMAIL_DOMAIN
                # Email sent to notify Admins
183
                to_admin = EmailMessage(
184 185 186 187 188 189
                    'Signup from %s' % (request.user.username),
                    ######################
                    '%s signed up at %s\n\n'
                    'Username: %s\n'
                    'Organization: %s\n\n'
                    'Message: %s\n\n'
190 191
                    'You can contact the user directly by replying to this email or '
                    'reply all to contact the user and notfiy the mailing list.\n'
192 193 194 195 196 197
                    'Please head to go.gmu.edu/useradmin to approve or '
                    'deny this application.'
                    % (str(full_name), str(timezone.now()).strip(),
                    str(request.user.username), str(organization), str(description)),
                    ######################
                    settings.EMAIL_FROM,
198 199 200
                    [settings.EMAIL_TO],
                    reply_to=[user_mail]
                ).send(fail_silently=False)
201
                # Confirmation email sent to Users
202
                send_mail(
203 204 205 206 207 208 209 210 211 212 213 214 215
                    'We have received your Go application!',
                    ######################
                    'Hey there %s,\n\n'
                    'The Go admins have received your application and are '
                    'currently in the process of reviewing it.\n\n'
                    'You will receive another email when you have been '
                    'approved.\n\n'
                    '- Go Admins'
                    % (str(full_name)),
                    ######################
                    settings.EMAIL_FROM,
                    [user_mail]
                )
216

217
            signup_form.save()
218
            return redirect('registered')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
219

220
    return render(request, 'core/signup.html', {
221
        'form': signup_form,
222
        'registered': False,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
223 224
    },
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
225

Jean Michel Rouly's avatar
Jean Michel Rouly committed
226

Jean Michel Rouly's avatar
Jean Michel Rouly committed
227
def redirection(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
228 229 230
    """
    This view redirects a user based on the short URL they requested.
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
231

232
    url = get_object_or_404(URL, short__iexact=short)
Jean Michel Rouly's avatar
Jean Michel Rouly committed
233
    url.clicks = url.clicks + 1
234

235 236 237 238
    domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
    if url.target == domain + short:
        return redirect('404.html')

239 240 241 242 243 244
    if 'qr' in request.GET:
        url.qrclicks += 1

    if 'social' in request.GET:
        url.socialclicks += 1

Jean Michel Rouly's avatar
Jean Michel Rouly committed
245
    url.save()
246

Jean Michel Rouly's avatar
Jean Michel Rouly committed
247 248 249 250 251
    """
    Include server-side tracking because there is no template displayed to
    the user which would include javascript tracking.
    """

252 253
    from piwikapi.tracking import PiwikTracker
    from django.conf import settings
254
    # First, if PIWIK variables are undefined, don't try to push
255
    if settings.PIWIK_SITE_ID != "" and settings.PIWIK_URL != "":
256 257 258 259 260 261 262
        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
263

264
    return redirect(url.target)
Jean Michel Rouly's avatar
Jean Michel Rouly committed
265 266


267 268 269 270 271 272 273 274 275 276 277 278 279
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
280
def useradmin(request):
281 282 283 284 285
    """
    This view is a simplified admin panel, so that staff don't need to log in
    to approve links
    """
    if request.POST:
286
        userlist = request.POST.getlist('username')
287
        if '_approve' in request.POST:
288 289 290 291
            for name in userlist:
                toapprove = RegisteredUser.objects.get(username=name)
                toapprove.approved = True
                toapprove.save()
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
                    user_mail = toapprove.username + settings.EMAIL_DOMAIN
                    send_mail(
                        'Your Account has been Approved!',
                        ######################
                        'Hey there %s,\n\n'
                        'The Go admins have reviewed your application and have '
                        'approved you to use Go!\n\n'
                        'Head over to go.gmu.edu to create your first address.\n\n'
                        '- Go Admins'
                        % (str(toapprove.full_name)),
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
307
        elif '_deny' in request.POST:
308 309
            for name in userlist:
                todeny = RegisteredUser.objects.get(username=name)
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
                    user_mail = todeny.username + settings.EMAIL_DOMAIN
                    send_mail(
                        'Your Account has been Denied!',
                        ######################
                        'Hey there %s,\n\n'
                        'The Go admins have reviewed your application and have '
                        'decided to not approve you to use Go.\n\n'
                        'Please reach out to srct@gmu.edu to appeal '
                        'this decision.\n\n'
                        '- Go Admins'
                        % (str(todeny.full_name)),
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
326
                todeny.delete()
327
    need_approval = RegisteredUser.objects.filter(approved=False)
328
    return render(request, 'admin/useradmin.html', {
329 330 331
        'need_approval': need_approval
    },
    )