#2: Admins can now manage other users' content.

This commit is contained in:
Peter Deltchev 2016-06-14 01:27:56 -07:00
parent 3864ea7a1f
commit a482a183dc
21 changed files with 119 additions and 97 deletions

View file

@ -20,18 +20,25 @@
namespace Poniverse\Ponyfm\Commands;
use Gate;
use Poniverse\Ponyfm\Models\Album;
use Poniverse\Ponyfm\Models\Image;
use Auth;
use Poniverse\Ponyfm\Models\User;
use Validator;
class CreateAlbumCommand extends CommandBase
{
private $_input;
/**
* @var User
*/
private $_albumOwner;
public function __construct($input)
{
$this->_input = $input;
$this->_albumOwner = User::find($this->_input['user_id']);
}
/**
@ -39,9 +46,7 @@ class CreateAlbumCommand extends CommandBase
*/
public function authorize()
{
$user = \Auth::user();
return $user != null;
return $this->_albumOwner !== null && Gate::allows('create-album', $this->_albumOwner);
}
/**
@ -54,7 +59,8 @@ class CreateAlbumCommand extends CommandBase
'title' => 'required|min:3|max:50',
'cover' => 'image|mimes:png|min_width:350|min_height:350',
'cover_id' => 'exists:images,id',
'track_ids' => 'exists:tracks,id'
'track_ids' => 'exists:tracks,id',
'user_id' => 'exists:users,id'
];
$validator = Validator::make($this->_input, $rules);
@ -64,7 +70,7 @@ class CreateAlbumCommand extends CommandBase
}
$album = new Album();
$album->user_id = Auth::user()->id;
$album->user_id = $this->_albumOwner->id;
$album->title = $this->_input['title'];
$album->description = $this->_input['description'];
@ -73,7 +79,7 @@ class CreateAlbumCommand extends CommandBase
} else {
if (isset($this->_input['cover'])) {
$cover = $this->_input['cover'];
$album->cover_id = Image::upload($cover, Auth::user())->id;
$album->cover_id = Image::upload($cover, $this->_albumOwner)->id;
} else {
if (isset($this->_input['remove_cover']) && $this->_input['remove_cover'] == 'true') {
$album->cover_id = null;

View file

@ -20,6 +20,7 @@
namespace Poniverse\Ponyfm\Commands;
use Gate;
use Poniverse\Ponyfm\Models\Album;
use Auth;
@ -42,9 +43,7 @@ class DeleteAlbumCommand extends CommandBase
*/
public function authorize()
{
$user = Auth::user();
return $this->_album && $user != null && $this->_album->user_id == $user->id;
return Gate::allows('delete', $this->_album);
}
/**

View file

@ -20,18 +20,22 @@
namespace Poniverse\Ponyfm\Commands;
use Auth;
use Carbon\Carbon;
use Config;
use Gate;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Input;
use Poniverse\Ponyfm\Models\Track;
use AudioCache;
use Poniverse\Ponyfm\Models\User;
use Validator;
class UploadTrackCommand extends CommandBase
{
use DispatchesJobs;
private $_artist;
private $_allowLossy;
private $_allowShortTrack;
private $_customTrackSource;
@ -45,8 +49,18 @@ class UploadTrackCommand extends CommandBase
* @param string|null $customTrackSource value to set in the track's "source" field; if left blank, "direct_upload" is used
* @param bool $autoPublishByDefault
*/
public function __construct(bool $allowLossy = false, bool $allowShortTrack = false, string $customTrackSource = null, bool $autoPublishByDefault = false)
{
public function __construct(
bool $allowLossy = false,
bool $allowShortTrack = false,
string $customTrackSource = null,
bool $autoPublishByDefault = false
) {
$userSlug = Input::get('user_slug', null);
$this->_artist =
$userSlug !== null
? User::where('slug', $userSlug)->first()
: Auth::user();
$this->_allowLossy = $allowLossy;
$this->_allowShortTrack = $allowShortTrack;
$this->_customTrackSource = $customTrackSource;
@ -58,7 +72,7 @@ class UploadTrackCommand extends CommandBase
*/
public function authorize()
{
return \Auth::user() != null;
return Gate::allows('create-track', $this->_artist);
}
/**
@ -67,7 +81,6 @@ class UploadTrackCommand extends CommandBase
*/
public function execute()
{
$user = \Auth::user();
$trackFile = Input::file('track', null);
$coverFile = Input::file('cover', null);
@ -78,7 +91,7 @@ class UploadTrackCommand extends CommandBase
$audio = \AudioCache::get($trackFile->getPathname());
$track = new Track();
$track->user_id = $user->id;
$track->user_id = $this->_artist->id;
// The title set here is a placeholder; it'll be replaced by ParseTrackTagsCommand
// if the file contains a title tag.
$track->title = Input::get('title', pathinfo($trackFile->getClientOriginalName(), PATHINFO_FILENAME));

View file

@ -32,6 +32,7 @@ use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\ResourceLogItem;
use Auth;
use Input;
use Poniverse\Ponyfm\Models\User;
use Response;
use Poniverse\Ponyfm\Models\Track;
@ -180,11 +181,11 @@ class PlaylistsController extends ApiControllerBase
return Response::json($playlists, 200);
}
public function getOwned()
public function getOwned(User $user)
{
$query = Playlist::summary()
->with('pins', 'tracks', 'tracks.cover')
->where('user_id', Auth::user()->id)
->where('user_id', $user->id)
->orderBy('title', 'asc')
->get();

View file

@ -32,6 +32,7 @@ use Poniverse\Ponyfm\Models\TrackFile;
use Poniverse\Ponyfm\Models\Track;
use Auth;
use Input;
use Poniverse\Ponyfm\Models\User;
use Response;
class TracksController extends ApiControllerBase
@ -180,9 +181,9 @@ class TracksController extends ApiControllerBase
return $this->getIndex(true);
}
public function getOwned()
public function getOwned(User $user)
{
$query = Track::summary()->where('user_id', \Auth::user()->id)->orderBy('created_at', 'desc');
$query = Track::summary()->where('user_id', $user->id)->orderBy('created_at', 'desc');
$tracks = [];
foreach ($query->get() as $track) {

View file

@ -137,16 +137,24 @@ Route::group(['prefix' => 'api/web'], function() {
Route::get('/notifications', 'Api\Web\NotificationsController@getNotifications');
Route::put('/notifications/mark-as-read', 'Api\Web\NotificationsController@putMarkAsRead');
Route::get('/tracks/owned', 'Api\Web\TracksController@getOwned');
Route::get('/tracks/edit/{id}', 'Api\Web\TracksController@getEdit');
Route::get('/users/{userId}', 'Api\Web\AccountController@getUser')->where('userId', '\d+');
Route::get('/users/{userId}/albums', 'Api\Web\AlbumsController@getOwned')->where('id', '\d+');
Route::get('/users/{userId}/images', 'Api\Web\ImagesController@getOwned')->where('id', '\d+');
Route::get('/users/{userId}/tracks', 'Api\Web\TracksController@getOwned')->where('userId', '\d+');
Route::get('/users/{userSlug}/tracks', 'Api\Web\TracksController@getOwned');
Route::get('/users/{userId}/albums', 'Api\Web\AlbumsController@getOwned')->where('userId', '\d+');
Route::get('/users/{userSlug}/albums', 'Api\Web\AlbumsController@getOwned');
Route::get('/users/{userId}/images', 'Api\Web\ImagesController@getOwned')->where('userId', '\d+');
Route::get('/users/{userSlug}/images', 'Api\Web\ImagesController@getOwned');
Route::get('/users/{userId}/playlists', 'Api\Web\PlaylistsController@getOwned')->where('userId', '\d+');
Route::get('/users/{userSlug}/playlists', 'Api\Web\PlaylistsController@getOwned');
Route::get('/albums/edit/{id}', 'Api\Web\AlbumsController@getEdit');
Route::get('/playlists/owned', 'Api\Web\PlaylistsController@getOwned');
Route::get('/playlists/pinned', 'Api\Web\PlaylistsController@getPinned');
Route::get('/favourites/tracks', 'Api\Web\FavouritesController@getTracks');

View file

@ -24,6 +24,14 @@ use Poniverse\Ponyfm\Models\User;
class UserPolicy
{
public function createAlbum(User $userToAuthorize, User $user) {
return $userToAuthorize->id === $user->id || $userToAuthorize->hasRole('admin');
}
public function createTrack(User $userToAuthorize, User $user) {
return $userToAuthorize->id === $user->id || $userToAuthorize->hasRole('admin');
}
public function getAlbums(User $userToAuthorize, User $user) {
return $userToAuthorize->id === $user->id || $userToAuthorize->hasRole('admin');
}

View file

@ -46,6 +46,9 @@ class RouteServiceProvider extends ServiceProvider
parent::boot($router);
$router->model('userId', User::class);
$router->bind('userSlug', function ($value) {
return User::where('slug', $value)->first();
});
}
/**

View file

@ -1,5 +1,5 @@
<div class="uploader">
<div class="dropzone" uploader>
<div class="dropzone" uploader="userSlug">
<p>Drop files here to begin your upload!</p>
</div>
@ -28,7 +28,7 @@
</span>
<span ng-show="upload.success">
<a ui-sref="content.artist.account.tracks.edit({slug: auth.user.slug, track_id: upload.trackId})" class="btn btn-sm btn-primary">
<a ui-sref="content.artist.account.tracks.edit({slug: userSlug, track_id: upload.trackId})" class="btn btn-sm btn-primary">
Publish
</a>
{{upload.name}}

View file

@ -14,16 +14,6 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
window.pfm.preloaders['account-albums-edit'] = [
'account-tracks', 'account-albums', '$state'
(tracks, albums, $state) ->
defs = [tracks.refresh()]
if $state.params.album_id
defs.push albums.getEdit($state.params.album_id, true)
$.when.all defs
]
module.exports = angular.module('ponyfm').controller "account-albums-edit", [
'$scope', '$state', '$modal', 'account-albums', 'auth'
($scope, $state, $modal, albums, auth) ->
@ -107,6 +97,7 @@ module.exports = angular.module('ponyfm').controller "account-albums-edit", [
formData.append name, value
formData.append 'track_ids', _.map($scope.tracks, (t) -> t.id).join()
formData.append 'user_id', $scope.artist.id
xhr.open 'POST', url, true
xhr.setRequestHeader 'X-XSRF-TOKEN', $.cookie('XSRF-TOKEN')

View file

@ -14,16 +14,9 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
window.pfm.preloaders['account-albums'] = [
'account-tracks'
(tracks) ->
tracks.refresh('published=true&in_album=false', true)
]
module.exports = angular.module('ponyfm').controller "account-albums", [
'$scope', '$state', 'account-albums', 'account-tracks'
($scope, $state, albums, tracks) ->
$scope.albums = []
$scope.data =
isEditorOpen: false
@ -36,7 +29,7 @@ module.exports = angular.module('ponyfm').controller "account-albums", [
$scope.data.tracksDb.length = 0
$scope.data.tracksDb.push track for track in tracks
tracks.refresh('published=true&in_album=false').done updateTracks
tracks.refresh('published=true&in_album=false', false, $state.params.slug).done updateTracks
albumsDb = {}
@ -51,7 +44,7 @@ module.exports = angular.module('ponyfm').controller "account-albums", [
if $state.params.album_id
selectAlbum albumsDb[$state.params.album_id]
albums.refresh().done updateAlbums
albums.refresh(false, $state.params.slug).done updateAlbums
$scope.$on '$stateChangeSuccess', () ->
if $state.params.album_id
@ -59,7 +52,7 @@ module.exports = angular.module('ponyfm').controller "account-albums", [
else
selectAlbum null
$scope.$on 'album-created', () -> albums.refresh(true).done(updateAlbums)
$scope.$on 'album-deleted', () -> albums.refresh(true).done(updateAlbums)
$scope.$on 'album-updated', () -> tracks.refresh('published=true&in_album=false', true).done updateTracks
$scope.$on 'album-created', () -> albums.refresh(true, $state.params.slug).done(updateAlbums)
$scope.$on 'album-deleted', () -> albums.refresh(true, $state.params.slug).done(updateAlbums)
$scope.$on 'album-updated', () -> tracks.refresh('published=true&in_album=false', true, $state.params.slug).done(updateTracks)
]

View file

@ -14,20 +14,15 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
window.pfm.preloaders['account-playlists'] = [
'playlists'
(playlists) -> playlists.refreshOwned true
]
module.exports = angular.module('ponyfm').controller "account-playlists", [
'$scope', 'auth', '$modal', 'playlists'
($scope, auth, $modal, playlists) ->
'$scope', '$state', 'auth', '$modal', 'playlists'
($scope, $state, auth, $modal, playlistService) ->
$scope.playlists = []
loadPlaylists = (playlists) ->
$scope.playlists.push playlist for playlist in playlists
playlists.refreshOwned().done loadPlaylists
playlistService.refreshOwned(true, $state.params.slug).done loadPlaylists
$scope.editPlaylist = (playlist) ->
$modal
@ -40,14 +35,14 @@ module.exports = angular.module('ponyfm').controller "account-playlists", [
$scope.togglePlaylistPin = (playlist) ->
playlist.is_pinned = !playlist.is_pinned;
playlists.editPlaylist playlist
playlistService.editPlaylist playlist
$scope.deletePlaylist = (playlist) ->
$scope.playlistToDelete = playlist
$modal({scope: $scope, templateUrl: 'templates/partials/delete-playlist-dialog.html', show: true})
$scope.confirmDeletePlaylist = () ->
playlists.deletePlaylist($scope.playlistToDelete).done ->
playlistService.deletePlaylist($scope.playlistToDelete).done ->
$scope.playlists.splice _.indexOf($scope.playlists, (p) -> p.id == $scope.playlistToDelete.id), 1
$scope.$on 'playlist-updated', (e, playlist) ->

View file

@ -42,21 +42,20 @@ module.exports = angular.module('ponyfm').controller "account-tracks", [
$scope.selectTrack = (track) ->
$scope.data.selectedTrack = track
tracks.refresh('created_at,desc', false, $state.params.slug).done setTracks
tracks.refresh().done setTracks
$scope.$on '$stateChangeSuccess', () ->
$scope.$on '$stateChangeSuccess', ->
if $state.params.track_id
$scope.selectTrack tracksDb[$state.params.track_id]
else
$scope.selectTrack null
$scope.$on 'track-deleted', () ->
$scope.$on 'track-deleted', ->
$state.transitionTo 'content.artist.account.tracks', slug: $state.params.slug
tracks.clearCache()
tracks.refresh(null, true).done setTracks
tracks.refresh(null, true, $state.params.slug).done setTracks
$scope.$on 'track-updated', () ->
$scope.$on 'track-updated', ->
tracks.clearCache()
tracks.refresh(null, true).done setTracks
tracks.refresh(null, true, $state.params.slug).done setTracks
]

View file

@ -18,8 +18,9 @@ module.exports = angular.module('ponyfm').controller "uploader", [
'$scope', 'auth', 'upload', '$state'
($scope, auth, upload, $state) ->
$scope.data = upload
$scope.userSlug = $state.params.slug
$scope.fileChanged = (e) ->
files = e.files
$scope.$apply -> upload.upload files
$scope.$apply -> upload.upload(files, $scope.userSlug)
]

View file

@ -55,7 +55,7 @@ module.exports = angular.module('ponyfm').directive 'pfmImageUpload', () ->
$scope.$watch 'userId', (val)->
return unless val?
images.refresh(false, $scope.userId).done (images) -> $scope.images = images
images.refresh(true, $scope.userId).done (images) -> $scope.images = images
$scope.previewImage = () ->
return if !$scope.isImageLoaded

View file

@ -14,11 +14,18 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
module.exports = angular.module('ponyfm').directive 'uploader', [
'upload'
(upload) -> (scope, element) ->
$dropzone = $(element)
module.exports = angular.module('ponyfm').directive 'uploader', ()->
$dropzone = null
compile: (element)->
$dropzone = element
scope:
userSlug: '=uploader'
controller: [
'$scope', 'upload'
($scope, upload) ->
$dropzone[0].addEventListener 'dragover', (e) ->
e.preventDefault()
$dropzone.addClass 'file-over'
@ -32,5 +39,5 @@ module.exports = angular.module('ponyfm').directive 'uploader', [
$dropzone.removeClass 'file-over'
files = e.target.files || e.dataTransfer.files
scope.$apply -> upload.upload files
]
$scope.$apply -> upload.upload(files, $scope.userSlug)
]

View file

@ -34,12 +34,12 @@ module.exports = angular.module('ponyfm').factory('account-albums', [
$http.get(url).success (album) -> editDef.resolve album
editDef.promise()
refresh: (force = false, user_id = window.pfm.auth.user.id) ->
return def if !force && def && user_id == currentlyLoadedUserId
refresh: (force = false, userId = window.pfm.auth.user.slug) ->
return def if !force && def && userId == currentlyLoadedUserId
def = new $.Deferred()
$http.get("/api/web/users/#{user_id}/albums").success (ownedAlbums) ->
currentlyLoadedUserId = user_id
$http.get("/api/web/users/#{userId}/albums").success (ownedAlbums) ->
currentlyLoadedUserId = userId
def.resolve(ownedAlbums)
def.promise()

View file

@ -32,10 +32,8 @@ module.exports = angular.module('ponyfm').factory('account-tracks', [
$http.get(url).success (track) -> def.resolve track
def.promise()
refresh: (query, force) ->
query = query || 'created_at,desc'
url = '/api/web/tracks/owned?' + query
force = force || false
refresh: (query = 'created_at,desc', force = false, userId = window.pfm.auth.user.slug) ->
url = "/api/web/users/#{userId}/tracks?" + query
return cache[url] if !force && cache[url]
def = new $.Deferred()

View file

@ -39,6 +39,5 @@ module.exports = angular.module('ponyfm').factory('images', [
return def
self.refresh()
return self
])

View file

@ -182,14 +182,13 @@ module.exports = angular.module('ponyfm').factory('playlists', [
isPlaylistPinned: (id) ->
_.find(self.pinnedPlaylists, (p) -> `p.id == id`) != undefined
refreshOwned: (force) ->
force = force || false
refreshOwned: (force = false, slug = window.pfm.auth.user.slug) ->
return playlistDef if !force && playlistDef
playlistDef = new $.Deferred()
if auth.data.isLogged
$http.get('/api/web/playlists/owned').success (playlists) ->
$http.get("/api/web/users/#{slug}/playlists").success (playlists) ->
playlistDef.resolve playlists
else
playlistDef.resolve []

View file

@ -48,7 +48,7 @@ module.exports = angular.module('ponyfm').factory('upload', [
upload: (files) ->
upload: (files, userSlug) ->
_.each files, (file) ->
upload =
name: file.name
@ -86,7 +86,7 @@ module.exports = angular.module('ponyfm').factory('upload', [
else
error =
if xhr.getResponseHeader('content-type') == 'application/json'
$.parseJSON(xhr.responseText).errors.track.join ', '
'Error: ' + $.parseJSON(xhr.responseText)?.errors?.track?.join ', '
else
'There was an unknown error!'
@ -98,8 +98,9 @@ module.exports = angular.module('ponyfm').factory('upload', [
.done($rootScope.$broadcast('upload-finished', upload))
# send the track to the server
formData = new FormData();
formData.append('track', file);
formData = new FormData()
formData.append('track', file)
formData.append('user_slug', userSlug)
xhr.open 'POST', '/api/web/tracks/upload', true
xhr.setRequestHeader 'X-XSRF-TOKEN', $.cookie('XSRF-TOKEN')