# -*- coding: utf-8 -*-

# Copyright 2012 Rooter Analysis S.L.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.core.urlresolvers import resolve

from tastypie.authorization import Authorization

from moocng.courses.models import Course
from moocng.courses.utils import is_teacher


PERMISSIONS = {
    'get_courses_as_student': 'course.can_list_allcourses',
    'get_passed_courses_as_student': 'course.can_list_passedcourses'
}


class PublicReadTeachersModifyAuthorization(Authorization):

    def is_authorized(self, request, object=None):
        if request.method == 'GET':
            return request.user.is_authenticated()
        else:
            return (request.user.is_authenticated() and
                    (is_teacher(request.user, Course.objects.all()) or
                     request.user.is_staff))


class TeacherAuthorization(Authorization):

    def is_authorized(self, request, object=None):
        return (request.user.is_authenticated() and
                (is_teacher(request.user, Course.objects.all()) or
                 request.user.is_staff))


class UserResourceAuthorization(Authorization):

    def is_authorized(self, request, object=None):
        if request.method == 'GET':
            url_name = resolve(request.path).url_name
            if url_name in PERMISSIONS.keys():
                required_perm = PERMISSIONS.get(url_name)
                return request.user.has_perm(required_perm)
        return False

@@ -830,32 +830,33 @@
 tudent': 'course
+s
 .can_list_allcou
@@ -906,16 +906,17 @@
  'course
+s
 .can_lis
@@ -1672,32 +1672,234 @@
 , object=None):%0A
+        # We check if the method is GET here instead of relaying in the%0A        # tastypie allowed_methods property because of the overrided urls,%0A        # those ignore the allowed_methods restriction%0A
         if reque
@@ -2137,16 +2137,40 @@
 d_perm)%0A
+            return True%0A
         

Fix UserResource Authorization