Last active
December 15, 2015 04:29
-
-
Save zolzaya/5202438 to your computer and use it in GitHub Desktop.
Single Page Application-д зориулсан хамгийн энгийн, хандан эрх шалгах класс
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Hooks | |
unless Array::unique | |
Array::unique = -> | |
output = {} | |
output[@[key]] = @[key] for key in [0...@length] | |
value for key, value of output | |
unless Array::contains_array | |
Array::contains_array = (arr)-> | |
@.every (val)-> | |
arr.indexOf(val) >= 0 | |
is_array = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]' | |
as_array = (items)-> | |
items = [items] unless is_array(items) | |
items | |
is_array_contains_array = (arr1, arr2)-> | |
arr2.every (val)-> | |
arr1.indexOf(val) >= 0 | |
## | |
# Ability | |
class Ability | |
_permissions: {} | |
can: (resource, actions)-> | |
Array::push.apply @.get_permissions(resource), as_array(actions) | |
@_permissions[resource].unique() | |
permit: (resource, actions)-> | |
is_array_contains_array(@.get_permissions(resource), as_array(actions)) | |
#@.get_permissions(resource).contains_array(as_array(actions)) | |
get_permissions: (resource)-> | |
@_permissions[resource] = [] unless is_array(@_permissions[resource]) | |
@_permissions[resource] | |
get_resources: -> | |
Object.keys(@_permissions) | |
ability= new Ability | |
ability.can('user', ['create', 'update']) | |
ability.can('user', 'destroy') | |
ability.can('post', 'destroy') | |
console.log ability.get_permissions('user') # ['create', 'update', 'destroy'] | |
console.log ability.get_permissions('post') # ['destroy'] | |
console.log ability.get_resources() # ['user', 'post'] | |
console.log ability.permit('user', 'destroy') # true | |
console.log ability.permit('user', ['destroy', 'update']) # true | |
console.log ability.permit('user', ['destroy', 'update', 'view']) # false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment