Commit 01ba42fc authored by alexandre's avatar alexandre

WIP. removed guardian and started to fix js

parent 3c9e636d
......@@ -28,8 +28,6 @@ INSTALLED_APPS = [
'django.contrib.flatpages',
'guardian',
'adminsortable2',
'taggit',
......@@ -133,7 +131,6 @@ STATICFILES_FINDERS = (
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend', # this is default
'guardian.backends.ObjectPermissionBackend',
)
......
from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from adminsortable2.admin import SortableAdminMixin, SortableInlineAdminMixin
from .models import Attachment, Score, FeaturedScore
......@@ -13,8 +12,10 @@ class AttachmentAdmin(admin.ModelAdmin):
pass
class ScoreAdmin(GuardedModelAdmin):
pass
class ScoreAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
# obj.user = request.user
super(ScoreAdmin, self).save_model(request, obj, form, change)
admin.site.register(FeaturedScore, FeaturedScoreAdmin)
......
......@@ -44,6 +44,10 @@ class Score(models.Model):
def __str__(self):
return self.title
# def save(self, *args, **kwargs):
# import ipdb; ipdb.set_trace()
# super(Score, self).save(*args, **kwargs) # Call the "real" save() method.
def get_absolute_url(self):
return "/partitions/{}".format(self.id)
......
......@@ -4,7 +4,7 @@ from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField
from taggit_serializer.serializers import (TagListSerializerField,
TaggitSerializer)
from guardian.shortcuts import assign_perm, get_users_with_perms, get_user_perms, remove_perm
### from guardian.shortcuts import assign_perm, get_users_with_perms, get_user_perms, remove_perm
from django.contrib.auth.models import User
from django.contrib.flatpages.models import FlatPage
......@@ -35,54 +35,40 @@ class AttachmentSerializer(serializers.HyperlinkedModelSerializer):
# read_only_fields = ('attachment',)
class PermissionListSerializer(serializers.ListSerializer):
def to_representation(self, obj):
perms = get_users_with_perms(obj, attach_perms=True)
return [{"username": k.username, "permissions": v} for k, v in perms.items()]
def to_internal_value(self, data):
print(data)
# return data
# I don't understand why I can't just return data
return {"permissions": data}
class PermissionSerializer(serializers.Serializer):
class Meta:
list_serializer_class = PermissionListSerializer
class ScoreSerializer(TaggitSerializer, serializers.HyperlinkedModelSerializer):
id = serializers.ReadOnlyField()
tags = TagListSerializerField(required=False)
permissions = PermissionSerializer(source="*", many=True)
is_editable = serializers.SerializerMethodField()
created_by = UserSerializer()
shared_with = UserSerializer(many=True)
class Meta:
model = Score
fields = '__all__'
def create(self, validated_data):
validated_data.pop('permissions', None)
instance = Score.objects.create(**validated_data)
assign_perm("view_score", self.context['request'].user, instance)
return instance
# def create(self, validated_data):
# validated_data.pop('permissions', None)
# instance = Score.objects.create(**validated_data)
# assign_perm("view_score", self.context['request'].user, instance)
# return instance
def get_is_editable(self, obj):
return self.context['request'].user.has_perm('change_score', obj)
current_user = self.context['request'].user
return obj.created_by == current_user
# return self.context['request'].user.has_perm('change_score', obj)
def update(self, instance, validated_data):
instance = super(ScoreSerializer, self).update(instance, validated_data)
for user, perms in get_users_with_perms(instance, attach_perms=True).items():
for perm in perms:
remove_perm(perm, user, instance)
### for user, perms in get_users_with_perms(instance, attach_perms=True).items():
# for perm in perms:
### remove_perm(perm, user, instance)
for i in instance.permissions:
user = User.objects.get(username=i.get('username'))
perms = i.get('permissions')
for perm in perms:
assign_perm(perm, user, instance)
# for i in instance.permissions:
# user = User.objects.get(username=i.get('username'))
# perms = i.get('permissions')
# for perm in perms:
### assign_perm(perm, user, instance)
return instance
......
......@@ -6,7 +6,6 @@ window.W = window.W || {};
(function(undefined) {
'use strict';
Marionette.TemplateCache.prototype.compileTemplate = function compileTemplate(rawTemplate, options) {
return W.extendedTemplate(rawTemplate, options);
}
......@@ -31,7 +30,6 @@ window.W = window.W || {};
W.config = W.config || {};
W.config.lang = W.utils.getUserLanguage();
var scoreApp = new W.ScoreApp();
scoreApp.start();
})();
......@@ -74,9 +74,11 @@ window.W = window.W || {};
W.UserAuthModel = Backbone.Model.extend({
urlRoot: '/rest-auth/user/',
defaults: {
username: ""
},
idAttribute: "pk",
// defaults: {
// username: ""
// },
url: function () {
var original_url = Backbone.Model.prototype.url.call(this);
......@@ -84,6 +86,10 @@ window.W = window.W || {};
return parsed_url;
},
isLoggedIn: function () {
return this.model.id ? true : false
}
});
......
......@@ -54,7 +54,7 @@ window.W.utils = window.W.utils || {};
if (string in entries) {
return entries[string];
} else {
console.log(string + " n'est pas traduit");
// console.log(string + " n'est pas traduit");
return string;
}
}
......
......@@ -1918,9 +1918,9 @@ window.W = window.W || {};
var sliderView = new W.SliderView({ depth: this.model.getDepth() });
this.showChildView('slider', sliderView);
var permissions = this.model.get("permissions");
var permissionView = new W.PermissionView({ collection: permissions });
this.showChildView('permissions', permissionView);
// var permissions = this.model.get("permissions");
// var permissionView = new W.PermissionView({ collection: permissions });
// this.showChildView('permissions', permissionView);
this.getRegion('mainline').$el.nestedSortable({
placeholder: 'axis placeholder',
......@@ -2574,7 +2574,8 @@ window.W = window.W || {};
url: form.attr('action'),
success: function(data, textStatus, jqXHR){
that.trigger('hide:modal');
model.set(model.defaults);
model.clear();
// model.set(model.defaults); // makes sure the username is set
},
error: function(xhr, ajaxOptions, thrownError){
alert('logout failed - please try again');
......@@ -2752,10 +2753,18 @@ window.W = window.W || {};
}
},
templateContext: function () {
return {
'isLoggedIn': this.model.id ? true : false
}
},
onRender: function () {
var myCreateView = new W.CreateView();
this.showChildView('create', myCreateView);
if (this.model.id) {
var myCreateView = new W.CreateView();
this.showChildView('create', myCreateView);
}
}
});
......
......@@ -16,12 +16,13 @@
<div id="create"></div>
<nav class="main-header__user">
<% if (username) { %>
<%- isLoggedIn %> -----
<% if (isLoggedIn) { %>
<%- t('Bienvenue') %> <a href="/compte"><%- username %></a> <a href="#" class="js-logout">(←)</a>
<% } %>
<ul>
<% if (username) { %>
<% if (isLoggedIn) { %>
<!-- <li><a href="#" class="js-logout"><%- t('Se déconnecter') %></a></li> -->
<% } else { %>
<li><a href="#" class="js-login"><%- t('Se connecter') %></a> <!--<a href="#" class="js-register"><%- t('S’inscrire') %></a>--></li>
......
from django.views.generic.base import TemplateView
from rest_framework import viewsets, permissions, authentication
from rest_framework import viewsets, permissions
from rest_framework.authentication import SessionAuthentication
from rest_framework.pagination import PageNumberPagination
from rest_framework.parsers import FormParser, MultiPartParser, JSONParser
from rest_framework.filters import OrderingFilter, SearchFilter, DjangoObjectPermissionsFilter
from rest_framework.filters import OrderingFilter, SearchFilter, DjangoObjectPermissionsFilter, BaseFilterBackend
from rest_framework.decorators import action
from django_filters import BooleanFilter
from django_filters import rest_framework as filters
from django_filters.rest_framework import DjangoFilterBackend, FilterSet
from .models import Attachment, Score, FeaturedScore
from .serializers import AttachmentSerializer, ScoreSerializer, ScoreLightSerializer, UserSerializer, FlatPageSerializer
from guardian.shortcuts import get_anonymous_user
from django.contrib.auth.models import User
from guardian.shortcuts import get_objects_for_user
# from django.contrib.auth import get_user
### from guardian.shortcuts import get_anonymous_user
### from guardian.shortcuts import get_objects_for_user
from rest_framework.response import Response
from collections import OrderedDict
from django.db import models
from django.db.models import Q
from playground.models import Score
from taggit.models import Tag
from django.contrib.flatpages.models import FlatPage
......@@ -61,29 +64,6 @@ class ScoreFilter(FilterSet):
fields = ('title', 'score_type', 'is_featured', 'shared_with', 'language', 'tags')
class ScoreAuthentication(authentication.SessionAuthentication):
def authenticate(self, request):
"""
Returns a `User` if the request session currently has a logged in user.
Otherwise returns AnonymousUser if no user is supplied, or `None` if
user is inactive.
"""
# Get the session-based user from the underlying HttpRequest object
user = getattr(request._request, 'user', None)
# Unauthenticated, CSRF validation not required
if not user:
return (get_anonymous_user(), None)
elif not user.is_active:
return None
self.enforce_csrf(request)
# CSRF passed with authenticated user
return (user, None)
class ScorePermissions(permissions.DjangoObjectPermissions):
"""
Similar to `DjangoObjectPermissions`, but adding 'view' permissions.
......@@ -101,6 +81,47 @@ class ScorePermissions(permissions.DjangoObjectPermissions):
}
class ScorePermission(permissions.BasePermission):
"""
Object-level permission to only allow owners or guests of an object to edit it.
Assumes the model instance has `created_by`, `shared_with` and `is_public` attributes.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request if score is public,
if obj.is_public and request.method in permissions.SAFE_METHODS:
return True
else:
return obj.created_by == request.user or request.user in obj.shared_with.all()
class ScoreFilterBackend(BaseFilterBackend):
"""
Filter that only allows users to see their own objects.
"""
# def filter_queryset(self, request, queryset, view):
# import ipdb; ipdb.set_trace()
# qs1 = queryset.filter(is_public=True)
# # returns Public scores only for Anonymous users
# if request.user.is_anonymous():
# return qs1
# qs2 = queryset.filter(created_by=request.user)
# qs3 = queryset.filter(shared_with=request.user)
# # returns public scores together with owned or shared-with scores
# return qs1.union(qs2, qs3)
def filter_queryset(self, request, queryset, view):
# returns Public scores only for Anonymous users
if request.user.is_anonymous():
return queryset.filter(is_public=True)
else:
return queryset.filter(Q(is_public=True)
| Q(created_by=request.user)
| Q(shared_with=request.user))
class ScoreViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
......@@ -108,9 +129,10 @@ class ScoreViewSet(viewsets.ModelViewSet):
_ignore_model_permissions = True # Seems essential to django guardian
queryset = Score.objects.all()
pagination_class = ScoreViewSetPagination
filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter, DjangoObjectPermissionsFilter)
authentication_classes = (ScoreAuthentication,)
permission_classes = (ScorePermissions,)
# filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter, ScoreFilterBackend)
filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter, ScoreFilterBackend)
authentication_classes = (SessionAuthentication,)
permission_classes = (ScorePermission,)
search_fields = ('title', 'score_author', 'performance_author')
# filter_fields = ('title', 'score_type')
filter_class = ScoreFilter
......@@ -142,25 +164,25 @@ class ScoreViewSet(viewsets.ModelViewSet):
data = [{'value': i['language'], 'label': i['language'], 'n': i['n']} for i in data if i['language']]
return Response(data)
def get_queryset(self):
"""
Filter featured scores
"""
queryset = super(ScoreViewSet, self).get_queryset()
shared_with = self.request.query_params.get('shared_with', None)
if shared_with is not None:
# Do not return scores for AnonymousUser
if (self.request.user.is_anonymous()):
return queryset.none()
return get_objects_for_user(self.request.user, 'playground.view_score')
is_featured= self.request.query_params.get('is_featured', None)
if is_featured is not None:
ids = FeaturedScore.objects.all().order_by('-order').values_list("score__id", flat=True)
return queryset.filter(id__in=ids)
return queryset
# def get_queryset(self):
# """
# Filter featured scores
# """
# queryset = super(ScoreViewSet, self).get_queryset()
# shared_with = self.request.query_params.get('shared_with', None)
# if shared_with is not None:
# # Do not return scores for AnonymousUser
# if (self.request.user.is_anonymous()):
# return queryset.none()
# ### return get_objects_for_user(self.request.user, 'playground.view_score')
# is_featured= self.request.query_params.get('is_featured', None)
# if is_featured is not None:
# ids = FeaturedScore.objects.all().order_by('-order').values_list("score__id", flat=True)
# return queryset.filter(id__in=ids)
# return queryset
def get_serializer_class(self, *args, **kwargs):
"""
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment