mirror of
https://github.com/evennia/evennia.git
synced 2026-03-30 12:37:16 +02:00
OBS: You'll need to resync/rebuild your database!
- This implements an updated, clearer and more robust access system. The policy is now to lock that which is not explicitly left open. - Permission strings -> Lock strings. Separating permissions and locks makes more sense security-wise - No more permissiongroup table; permissions instead use a simple tuple PERMISSIONS_HIERARCHY to define an access hierarchy - Cleaner lock-definition syntax, all based on function calls. - New objects/players/channels get a default security policy during creation (set through typeclass) As part of rebuilding and testing the new lock/permission system I got into testing and debugging several other systems, fixing some outstanding issues: - @reload now fully updates the database asynchronously. No need to reboot server when changing cmdsets - Dozens of new test suites added for about 30 commands so far - Help for channels made more clever and informative.
This commit is contained in:
parent
c2030c2c0c
commit
08b3de9e5e
49 changed files with 1714 additions and 1877 deletions
0
src/locks/__init__.py
Normal file
0
src/locks/__init__.py
Normal file
303
src/locks/lockfuncs.py
Normal file
303
src/locks/lockfuncs.py
Normal file
|
|
@ -0,0 +1,303 @@
|
|||
"""
|
||||
This module provides a set of permission lock functions for use
|
||||
with Evennia's permissions system.
|
||||
|
||||
To call these locks, make sure this module is included in the
|
||||
settings tuple PERMISSION_FUNC_MODULES then define a lock on the form
|
||||
'<access_type>:func(args)' and add it to the object's lockhandler.
|
||||
Run the check method of the handler to execute the lock check.
|
||||
|
||||
Note that accessing_obj and accessed_obj can be any object type
|
||||
with a lock variable/field, so be careful to not expect
|
||||
a certain object type.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
MUX locks
|
||||
|
||||
Below is a list nicked from the MUX docs on the locks available
|
||||
in MUX. These are not all necessarily relevant to an Evennia game
|
||||
but to show they are all possible with Evennia, each entry is a
|
||||
suggestion on how one could implement similar functionality in Evennia.
|
||||
|
||||
Name: Affects: Effect:
|
||||
-------------------------------------------------------------------------
|
||||
DefaultLock: Exits: controls who may traverse the exit to
|
||||
its destination.
|
||||
Evennia: specialized permission key
|
||||
'traverse' checked in move method
|
||||
Rooms: controls whether the player sees the SUCC
|
||||
or FAIL message for the room following the
|
||||
room description when looking at the room.
|
||||
Evennia: This is better done by implementing
|
||||
a clever room class ...
|
||||
Players/Things: controls who may GET the object.
|
||||
Evennia: specialized permission key 'get'
|
||||
defined on object, checked by get command
|
||||
EnterLock: Players/Things: controls who may ENTER the object
|
||||
Evennia: specialized permission key 'enter'
|
||||
defined on object, checked by move command
|
||||
GetFromLock: All but Exits: controls who may gets things from a given
|
||||
location.
|
||||
Evennia: Probably done best with a lock function
|
||||
that searches the database for permitted users
|
||||
GiveLock: Players/Things: controls who may give the object.
|
||||
Evennia: specialized permission key 'give'
|
||||
checked by the give command
|
||||
LeaveLock: Players/Things: controls who may LEAVE the object.
|
||||
Evennia: specialized permission key 'leave'
|
||||
checked by move command
|
||||
LinkLock: All but Exits: controls who may link to the location if the
|
||||
location is LINK_OK (for linking exits or
|
||||
setting drop-tos) or ABODE (for setting
|
||||
homes)
|
||||
Evennia: specialized permission key 'link'
|
||||
set on obj and checked by link command
|
||||
MailLock: Players: controls who may @mail the player.
|
||||
Evennia: Lock function that pulls the
|
||||
config from the player to see if the
|
||||
calling player is on the blacklist/whitelist
|
||||
OpenLock: All but Exits: controls who may open an exit.
|
||||
Evennia: specialized permission key 'open'
|
||||
set on exit, checked by open command
|
||||
PageLock: Players: controls who may page the player.
|
||||
Evennia: see Maillock
|
||||
ParentLock: All: controls who may make @parent links to the
|
||||
object.
|
||||
Evennia: This is handled with typeclasses
|
||||
and typeclass switching instead.
|
||||
ReceiveLock: Players/Things: controls who may give things to the object.
|
||||
Evennia: See GiveLock
|
||||
SpeechLock: All but Exits: controls who may speak in that location
|
||||
Evennia: Lock function checking if there
|
||||
is some special restrictions on the room
|
||||
(game dependent)
|
||||
TeloutLock: All but Exits: controls who may teleport out of the
|
||||
location.
|
||||
Evennia: See LeaveLock
|
||||
TportLock: Rooms/Things: controls who may teleport there
|
||||
Evennia: See EnterLock
|
||||
UseLock: All but Exits: controls who may USE the object, GIVE the
|
||||
object money and have the PAY attributes
|
||||
run, have their messages heard and possibly
|
||||
acted on by LISTEN and AxHEAR, and invoke
|
||||
$-commands stored on the object.
|
||||
Evennia: Implemented per game
|
||||
DropLock: All but rooms: controls who may drop that object.
|
||||
Evennia: specialized permission key 'drop'
|
||||
set on room, checked by drop command.
|
||||
VisibleLock: All: Controls object visibility when the object
|
||||
is not dark and the looker passes the lock.
|
||||
In DARK locations, the object must also be
|
||||
set LIGHT and the viewer must pass the
|
||||
VisibleLock.
|
||||
Evennia: Better done with Scripts implementing
|
||||
a dark state/cmdset. For a single object,
|
||||
use a specialized permission key 'visible'
|
||||
set on object and checked by look command.
|
||||
|
||||
"""
|
||||
|
||||
from django.conf import settings
|
||||
from src.utils import search
|
||||
|
||||
PERMISSION_HIERARCHY = [p.lower() for p in settings.PERMISSION_HIERARCHY]
|
||||
|
||||
def true(*args, **kwargs):
|
||||
"Always returns True."
|
||||
return True
|
||||
def all(*args, **kwargs):
|
||||
return True
|
||||
def false(*args, **kwargs):
|
||||
"Always returns False"
|
||||
return False
|
||||
def none(*args, **kwargs):
|
||||
return False
|
||||
|
||||
def perm(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"""
|
||||
The basic permission-checker. Ignores case.
|
||||
|
||||
Usage:
|
||||
perm(<permission>)
|
||||
|
||||
where <permission> is the permission accessing_obj must
|
||||
have in order to pass the lock. If the given permission
|
||||
is part of PERMISSION_HIERARCHY, permission is also granted
|
||||
to all ranks higher up in the hierarchy.
|
||||
"""
|
||||
if not args:
|
||||
return False
|
||||
perm = args[0].lower()
|
||||
if hasattr(accessing_obj, 'permissions'):
|
||||
if perm in [p.lower() for p in accessing_obj.permissions]:
|
||||
# simplest case - we have a direct match
|
||||
return True
|
||||
if perm in PERMISSION_HIERARCHY:
|
||||
# check if we have a higher hierarchy position
|
||||
ppos = PERMISSION_HIERARCHY.index(perm)
|
||||
return any(True for hpos, hperm in enumerate(PERMISSION_HIERARCHY)
|
||||
if hperm in [p.lower() for p in accessing_obj.permissions] and hpos > ppos)
|
||||
return False
|
||||
|
||||
def perm_above(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"""
|
||||
Only allow objects with a permission *higher* in the permission
|
||||
hierarchy than the one given. If there is no such higher rank,
|
||||
it's assumed we refer to superuser. If no hierarchy is defined,
|
||||
this function has no meaning and returns False.
|
||||
"""
|
||||
if args and args[0].lower() in PERMISSION_HIERARCHY:
|
||||
ppos = PERMISSION_HIERARCHY.index(args[0].lower())
|
||||
return any(True for hpos, hperm in enumerate(PERMISSION_HIERARCHY)
|
||||
if hperm in [p.lower() for p in accessing_obj.permissions] and hpos > ppos)
|
||||
|
||||
def dbref(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"""
|
||||
Usage:
|
||||
dbref(3)
|
||||
|
||||
This lock type checks if the checking object
|
||||
has a particular dbref. Note that this only
|
||||
works for checking objects that are stored
|
||||
in the database (e.g. not for commands)
|
||||
"""
|
||||
if not args:
|
||||
return False
|
||||
try:
|
||||
dbref = int(args[0].strip().strip('#'))
|
||||
except ValueError:
|
||||
return False
|
||||
if hasattr(accessing_obj, 'id'):
|
||||
return dbref == accessing_obj.id
|
||||
return False
|
||||
|
||||
def id(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"Alias to dbref"
|
||||
return dbref(accessing_obj, accessed_obj, *args, **kwargs)
|
||||
|
||||
def attr(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"""
|
||||
Usage:
|
||||
has_attr(attrname)
|
||||
has_attr(attrname, value)
|
||||
has_attr(attrname, value, compare=type)
|
||||
|
||||
where compare's type is one of (eq,gt,lt,ge,le,ne) and signifies
|
||||
how the value should be compared with one on accessing_obj (so
|
||||
compare=gt means the accessing_obj must have a value greater than
|
||||
the one given).
|
||||
|
||||
Searches attributes *and* properties stored on the checking
|
||||
object. The first form works like a flag - if the attribute/property
|
||||
exists on the object, it returns True. The second form also requires
|
||||
that the value of the attribute/property matches. Note that all
|
||||
retrieved values will be converted to strings before doing the comparison.
|
||||
"""
|
||||
# deal with arguments
|
||||
if not args:
|
||||
return False
|
||||
attrname = args[0].strip()
|
||||
value = None
|
||||
if len(args) > 1:
|
||||
value = args[1].strip()
|
||||
compare = 'eq'
|
||||
if kwargs:
|
||||
compare = kwargs.get('compare', 'eq')
|
||||
|
||||
def valcompare(val1, val2, typ='eq'):
|
||||
"compare based on type"
|
||||
try:
|
||||
if typ == 'eq':
|
||||
return val1 == val2 or int(val1) == int(val2)
|
||||
elif typ == 'gt':
|
||||
return int(val1) > int(val2)
|
||||
elif typ == 'lt':
|
||||
return int(val1) < int(val2)
|
||||
elif typ == 'ge':
|
||||
return int(val1) >= int(val2)
|
||||
elif typ == 'le':
|
||||
return int(val1) <= int(val2)
|
||||
elif typ == 'ne':
|
||||
return int(val1) != int(val2)
|
||||
else:
|
||||
return False
|
||||
except Exception, e:
|
||||
print e
|
||||
# this might happen if we try to compare two things that cannot be compared
|
||||
return False
|
||||
|
||||
# first, look for normal properties on the object trying to gain access
|
||||
if hasattr(accessing_obj, attrname):
|
||||
if value:
|
||||
return valcompare(str(getattr(accessing_obj, attrname)), value, compare)
|
||||
return True
|
||||
# check attributes, if they exist
|
||||
if (hasattr(accessing_obj, 'has_attribute')
|
||||
and accessing_obj.has_attribute(attrname)):
|
||||
if value:
|
||||
return (hasattr(accessing_obj, 'get_attribute')
|
||||
and valcompare(accessing_obj.get_attribute(attrname), value, compare))
|
||||
return True
|
||||
return False
|
||||
|
||||
def attr_eq(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"""
|
||||
Usage:
|
||||
attr_gt(attrname, 54)
|
||||
"""
|
||||
return attr(accessing_obj, accessed_obj, *args, **kwargs)
|
||||
|
||||
def attr_gt(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"""
|
||||
Usage:
|
||||
attr_gt(attrname, 54)
|
||||
|
||||
Only true if access_obj's attribute > the value given.
|
||||
"""
|
||||
return attr(accessing_obj, accessed_obj, *args, **{'compare':'gt'})
|
||||
def attr_ge(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"""
|
||||
Usage:
|
||||
attr_gt(attrname, 54)
|
||||
|
||||
Only true if access_obj's attribute >= the value given.
|
||||
"""
|
||||
return attr(accessing_obj, accessed_obj, *args, **{'compare':'ge'})
|
||||
def attr_lt(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"""
|
||||
Usage:
|
||||
attr_gt(attrname, 54)
|
||||
|
||||
Only true if access_obj's attribute < the value given.
|
||||
"""
|
||||
return attr(accessing_obj, accessed_obj, *args, **{'compare':'lt'})
|
||||
def attr_le(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"""
|
||||
Usage:
|
||||
attr_gt(attrname, 54)
|
||||
|
||||
Only true if access_obj's attribute <= the value given.
|
||||
"""
|
||||
return attr(accessing_obj, accessed_obj, *args, **{'compare':'le'})
|
||||
def attr_ne(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"""
|
||||
Usage:
|
||||
attr_gt(attrname, 54)
|
||||
|
||||
Only true if access_obj's attribute != the value given.
|
||||
"""
|
||||
return attr(accessing_obj, accessed_obj, *args, **{'compare':'ne'})
|
||||
|
||||
def superuser(*args, **kwargs):
|
||||
"""
|
||||
Only accepts an accesing_obj that is superuser (e.g. user #1)
|
||||
|
||||
Since a superuser would not ever reach this check (superusers
|
||||
bypass the lock entirely), any user who gets this far cannot be a
|
||||
superuser, hence we just return False. :)
|
||||
"""
|
||||
return False
|
||||
|
||||
367
src/locks/lockhandler.py
Normal file
367
src/locks/lockhandler.py
Normal file
|
|
@ -0,0 +1,367 @@
|
|||
"""
|
||||
Locks
|
||||
|
||||
A lock defines access to a particular subsystem or property of
|
||||
Evennia. For example, the "owner" property can be impmemented as a
|
||||
lock. Or the disability to lift an object or to ban users.
|
||||
|
||||
A lock consists of two three parts:
|
||||
|
||||
- access_type - this defines what kind of access this lock regulates. This
|
||||
just a string.
|
||||
- function call - this is one or many calls to functions that will determine
|
||||
if the lock is passed or not.
|
||||
- lock function(s). These are regular python functions with a special
|
||||
set of allowed arguments. They should always return a boolean depending
|
||||
on if they allow access or not.
|
||||
|
||||
# Lock function
|
||||
|
||||
A lock function is defined by existing in one of the modules
|
||||
listed by settings.LOCK_FUNC_MODULES. It should also always
|
||||
take four arguments looking like this:
|
||||
|
||||
funcname(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
[...]
|
||||
|
||||
The accessing object is the object wanting to gain access.
|
||||
The accessed object is the object this lock resides on
|
||||
args and kwargs will hold optional arguments and/or keyword arguments
|
||||
to the function as a list and a dictionary respectively.
|
||||
|
||||
Example:
|
||||
|
||||
perm(accessing_obj, accessed_obj, *args, **kwargs):
|
||||
"Checking if the object has a particular, desired permission"
|
||||
if args:
|
||||
desired_perm = args[0]
|
||||
return desired_perm in accessing_obj.permissions
|
||||
return False
|
||||
|
||||
Lock functions should most often be pretty general and ideally possible to
|
||||
re-use and combine in various ways to build clever locks.
|
||||
|
||||
|
||||
# Lock definition
|
||||
|
||||
A lock definition is a string with a special syntax. It is added to
|
||||
each object's lockhandler, making that lock available from then on.
|
||||
|
||||
The lock definition looks like this:
|
||||
|
||||
'access_type:[NOT] func1(args)[ AND|OR][NOT] func2() ...'
|
||||
|
||||
That is, the access_type, a colon followed by calls to lock functions
|
||||
combined with AND or OR. NOT negates the result of the following call.
|
||||
|
||||
Example:
|
||||
|
||||
We want to limit who may edit a particular object (let's call this access_type
|
||||
for 'edit', it depends on what the command is looking for). We want this to
|
||||
only work for those with the Permission 'Builder'. So we use our lock
|
||||
function above and call it like this:
|
||||
|
||||
'edit:perm(Builder)'
|
||||
|
||||
Here, the lock-function perm() will be called (accessing_obj and accessed_obj are added
|
||||
automatically, you only need to add the args/kwargs, if any).
|
||||
|
||||
If we wanted to make sure the accessing object was BOTH a Builder and a GoodGuy, we
|
||||
could use AND:
|
||||
|
||||
'edit:perm(Builder) AND perm(GoodGuy)'
|
||||
|
||||
To allow EITHER Builders and GoodGuys, we replace AND with OR. perm() is just one example,
|
||||
the lock function can do anything and compare any properties of the calling object to
|
||||
decide if the lock is passed or not.
|
||||
|
||||
'lift:attrib(very_strong) AND NOT attrib(bad_back)'
|
||||
|
||||
To make these work, add the string to the lockhandler of the object you want
|
||||
to apply the lock to:
|
||||
|
||||
obj.lockhandler.add('edit:perm(Builder)')
|
||||
|
||||
From then on, a command that wants to check for 'edit' access on this
|
||||
object would do something like this:
|
||||
|
||||
if not target_obj.lockhandler.has_perm(caller, 'edit'):
|
||||
caller.msg("Sorry you cannot edit that.")
|
||||
|
||||
|
||||
# Permissions
|
||||
|
||||
Permissions are just text strings stored in a comma-separated list on
|
||||
typeclassed objects. The default perm() lock function uses them,
|
||||
taking into account settings.PERMISSION_HIERARCHY. Also, the
|
||||
restricted @perm command sets them, but otherwise they are identical
|
||||
to any other identifier you can use.
|
||||
|
||||
"""
|
||||
|
||||
import re, inspect
|
||||
from django.conf import settings
|
||||
from src.utils import logger, utils
|
||||
|
||||
#
|
||||
# Cached lock functions
|
||||
#
|
||||
|
||||
LOCKFUNCS = {}
|
||||
def cache_lockfuncs():
|
||||
"Updates the cache."
|
||||
global LOCKFUNCS
|
||||
LOCKFUNCS = {}
|
||||
for modulepath in settings.LOCK_FUNC_MODULES:
|
||||
modulepath = utils.pypath_to_realpath(modulepath)
|
||||
mod = utils.mod_import(modulepath)
|
||||
if mod:
|
||||
for tup in (tup for tup in inspect.getmembers(mod) if callable(tup[1])):
|
||||
LOCKFUNCS[tup[0]] = tup[1]
|
||||
else:
|
||||
logger.log_errmsg("Couldn't load %s from PERMISSION_FUNC_MODULES." % modulepath)
|
||||
|
||||
#
|
||||
# pre-compiled regular expressions
|
||||
#
|
||||
|
||||
RE_FUNCS = re.compile(r"\w+\([^)]*\)")
|
||||
RE_SEPS = re.compile(r"(?<=[ )])AND(?=\s)|(?<=[ )])OR(?=\s)|(?<=[ )])NOT(?=\s)")
|
||||
RE_OK = re.compile(r"%s|and|or|not")
|
||||
|
||||
|
||||
#
|
||||
#
|
||||
# Lock handler
|
||||
#
|
||||
#
|
||||
|
||||
class LockHandler(object):
|
||||
"""
|
||||
This handler should be attached to all objects implementing
|
||||
permission checks, under the property 'lockhandler'.
|
||||
"""
|
||||
|
||||
def __init__(self, obj):
|
||||
"""
|
||||
Loads and pre-caches all relevant locks and their
|
||||
functions.
|
||||
"""
|
||||
if not LOCKFUNCS:
|
||||
cache_lockfuncs()
|
||||
self.obj = obj
|
||||
self.locks = {}
|
||||
self.log_obj = None
|
||||
self.no_errors = True
|
||||
self.reset_flag = False
|
||||
|
||||
self._cache_locks(self.obj.lock_storage)
|
||||
|
||||
|
||||
|
||||
def __str__(self):
|
||||
return ";".join(self.locks[key][2] for key in sorted(self.locks))
|
||||
|
||||
def _log_error(self, message):
|
||||
"Try to log errors back to object"
|
||||
if self.log_obj and hasattr(self.log_obj, 'msg'):
|
||||
self.log_obj.msg(message)
|
||||
elif hasattr(self.obj, 'msg'):
|
||||
self.obj.msg(message)
|
||||
else:
|
||||
logger.log_trace("%s: %s" % (self.obj, message))
|
||||
|
||||
def _parse_lockstring(self, storage_lockstring):
|
||||
"""
|
||||
Helper function.
|
||||
locks are stored as a string 'atype:[NOT] lock()[[ AND|OR [NOT] lock() [...]];atype...
|
||||
"""
|
||||
locks = {}
|
||||
if not storage_lockstring:
|
||||
return locks
|
||||
nlocks = storage_lockstring.count(';') + 1
|
||||
duplicates = 0
|
||||
elist = []
|
||||
for raw_lockstring in storage_lockstring.split(';'):
|
||||
lock_funcs = []
|
||||
access_type, rhs = (part.strip() for part in raw_lockstring.split(':', 1))
|
||||
|
||||
# parse the lock functions and separators
|
||||
funclist = RE_FUNCS.findall(rhs)
|
||||
evalstring = rhs.replace('AND','and').replace('OR','or').replace('NOT','not')
|
||||
nfuncs = len(funclist)
|
||||
for funcstring in funclist:
|
||||
funcname, rest = [part.strip().strip(')') for part in funcstring.split('(', 1)]
|
||||
func = LOCKFUNCS.get(funcname, None)
|
||||
if not callable(func):
|
||||
elist.append("Lock: function '%s' is not available." % funcstring)
|
||||
continue
|
||||
args = [arg.strip() for arg in rest.split(',') if not '=' in arg]
|
||||
kwargs = dict([arg.split('=', 1) for arg in rest.split(',') if '=' in arg])
|
||||
lock_funcs.append((func, args, kwargs))
|
||||
evalstring = evalstring.replace(funcstring, '%s')
|
||||
if len(lock_funcs) < nfuncs:
|
||||
continue
|
||||
try:
|
||||
# purge the eval string of any superfluos items, then test it
|
||||
evalstring = " ".join(RE_OK.findall(evalstring))
|
||||
eval(evalstring % tuple(True for func in funclist))
|
||||
except Exception:
|
||||
elist.append("Lock: definition '%s' has syntax errors." % raw_lockstring)
|
||||
continue
|
||||
if access_type in locks:
|
||||
duplicates += 1
|
||||
elist.append("Lock: access type '%s' changed from '%s' to '%s' " % \
|
||||
(access_type, locks[access_type][2], raw_lockstring))
|
||||
locks[access_type] = (evalstring, tuple(lock_funcs), raw_lockstring)
|
||||
if elist:
|
||||
self._log_error("\n".join(elist))
|
||||
self.no_errors = False
|
||||
|
||||
return locks
|
||||
|
||||
def _cache_locks(self, storage_lockstring):
|
||||
"""Store data"""
|
||||
self.locks = self._parse_lockstring(storage_lockstring)
|
||||
|
||||
def _save_locks(self):
|
||||
"Store locks to obj"
|
||||
self.obj.lock_storage = ";".join([tup[2] for tup in self.locks.values()])
|
||||
|
||||
def add(self, lockstring, log_obj=None):
|
||||
"""
|
||||
Add a new, single lockstring on the form '<access_type>:<functions>'
|
||||
|
||||
If log_obj is given, it will be fed error information.
|
||||
"""
|
||||
if log_obj:
|
||||
self.log_obj = log_obj
|
||||
self.no_errors = True
|
||||
# sanity checks
|
||||
for lockdef in lockstring.split(';'):
|
||||
if not ':' in lockstring:
|
||||
self._log_error("Lock: '%s' contains no colon (:)." % lockdef)
|
||||
return False
|
||||
access_type, rhs = [part.strip() for part in lockdef.split(':', 1)]
|
||||
if not access_type:
|
||||
self._log_error("Lock: '%s' has no access_type (left-side of colon is empty)." % lockdef)
|
||||
return False
|
||||
if rhs.count('(') != rhs.count(')'):
|
||||
self._log_error("Lock: '%s' has mismatched parentheses." % lockdef)
|
||||
return False
|
||||
if not RE_FUNCS.findall(rhs):
|
||||
self._log_error("Lock: '%s' has no valid lock functions." % lockdef)
|
||||
return False
|
||||
# get the lock string
|
||||
storage_lockstring = self.obj.lock_storage
|
||||
if storage_lockstring:
|
||||
storage_lockstring = storage_lockstring + ";" + lockstring
|
||||
else:
|
||||
storage_lockstring = lockstring
|
||||
# cache the locks will get rid of eventual doublets
|
||||
self._cache_locks(storage_lockstring)
|
||||
self._save_locks()
|
||||
self.log_obj = None
|
||||
return self.no_errors
|
||||
|
||||
def get(self, access_type):
|
||||
"get the lockstring of a particular type"
|
||||
return self.locks.get(access_type, None)
|
||||
|
||||
def delete(self, access_type):
|
||||
"Remove a lock from the handler"
|
||||
if access_type in self.locks:
|
||||
del self.locks[access_type]
|
||||
self._save_locks()
|
||||
return True
|
||||
return False
|
||||
|
||||
def clear(self):
|
||||
"Remove all locks"
|
||||
self.locks = {}
|
||||
self.lock_storage = ""
|
||||
def reset(self):
|
||||
"""
|
||||
Set the reset flag, so the the lock will be re-cached at next checking.
|
||||
This is usually set by @reload.
|
||||
"""
|
||||
self.reset_flag = True
|
||||
|
||||
def check(self, accessing_obj, access_type, default=False):
|
||||
"""
|
||||
Checks a lock of the correct type by passing execution
|
||||
off to the lock function(s).
|
||||
|
||||
accessing_obj - the object seeking access
|
||||
access_type - the type of access wanted
|
||||
default - if no suitable lock type is found, use this
|
||||
"""
|
||||
if self.reset_flag:
|
||||
# rebuild cache
|
||||
self._cache_locks(self.obj.lock_storage)
|
||||
self.reset_flag = False
|
||||
|
||||
if (hasattr(accessing_obj, 'player') and hasattr(accessing_obj.player, 'is_superuser') and accessing_obj.player.is_superuser) \
|
||||
or (hasattr(accessing_obj, 'get_player') and (accessing_obj.get_player()==None or accessing_obj.get_player().is_superuser)):
|
||||
# we grant access to superusers and also to protocol instances that not yet has any player assigned to them (the
|
||||
# latter is a safety feature since superuser cannot be authenticated at some point during the connection).
|
||||
return True
|
||||
if access_type in self.locks:
|
||||
# we have a lock, test it.
|
||||
evalstring, func_tup, raw_string = self.locks[access_type]
|
||||
# we have previously stored the function object and all the args/kwargs as list/dict,
|
||||
# now we just execute them all in sequence. The result will be a list of True/False
|
||||
# statements. Note that there is no eval here, these are normal command calls!
|
||||
true_false = (tup[0](accessing_obj, self.obj, *tup[1], **tup[2]) for tup in func_tup)
|
||||
# we now input these True/False list into the evalstring, which combines them with
|
||||
# AND/OR/NOT in order to get the final result
|
||||
return eval(evalstring % tuple(true_false))
|
||||
else:
|
||||
return default
|
||||
|
||||
def check_lockstring(self, accessing_obj, accessed_obj, lockstring):
|
||||
"""
|
||||
Do a direct check against a lockstring ('atype:func()..'), without any
|
||||
intermediary storage on the accessed object (this can be left
|
||||
to None if the lock functions called don't access it). atype can also be
|
||||
put to a dummy value since no lock selection is made.
|
||||
"""
|
||||
if (hasattr(accessing_obj, 'player') and hasattr(accessing_obj.player, 'user')
|
||||
and hasattr(accessing_obj.player.user, 'is_superuser')
|
||||
and accessing_obj.player.user.is_superuser):
|
||||
return True # always grant access to the superuser.
|
||||
locks = self. _parse_lockstring(lockstring)
|
||||
for access_type in locks:
|
||||
evalstring, func_tup, raw_string = locks[access_type]
|
||||
true_false = (tup[0](accessing_obj, self.obj, *tup[1], **tup[2]) for tup in func_tup)
|
||||
return eval(evalstring % tuple(true_false))
|
||||
|
||||
|
||||
|
||||
def test():
|
||||
# testing
|
||||
|
||||
class TestObj(object):
|
||||
pass
|
||||
|
||||
import pdb
|
||||
obj1 = TestObj()
|
||||
obj2 = TestObj()
|
||||
|
||||
obj1.lock_storage = "owner:dbref(#4);edit:dbref(#5) or perm(Wizards);examine:perm(Builders);delete:perm(Wizards);get:all()"
|
||||
#obj1.lock_storage = "cmd:all();admin:id(1);listen:all();send:all()"
|
||||
|
||||
pdb.set_trace()
|
||||
obj1.locks = LockHandler(obj1)
|
||||
obj2.permissions = ["Wizards"]
|
||||
obj2.id = 4
|
||||
|
||||
#obj1.locks.add("edit:attr(test)")
|
||||
|
||||
print "comparing obj2.permissions (%s) vs obj1.locks (%s)" % (obj2.permissions, obj1.locks)
|
||||
print obj1.locks.check(obj2, 'owner')
|
||||
print obj1.locks.check(obj2, 'edit')
|
||||
print obj1.locks.check(obj2, 'examine')
|
||||
print obj1.locks.check(obj2, 'delete')
|
||||
print obj1.locks.check(obj2, 'get')
|
||||
print obj1.locks.check(obj2, 'listen')
|
||||
63
src/locks/tests.py
Normal file
63
src/locks/tests.py
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
This is part of Evennia's unittest framework, for testing
|
||||
the stability and integrrity of the codebase during updates.
|
||||
|
||||
This module tests the lock functionality of Evennia.
|
||||
|
||||
"""
|
||||
|
||||
try:
|
||||
# this is a special optimized Django version, only available in current Django devel
|
||||
from django.utils.unittest import TestCase
|
||||
except ImportError:
|
||||
from django.test import TestCase
|
||||
|
||||
from django.conf import settings
|
||||
from src.locks import lockhandler, lockfuncs
|
||||
from src.utils import create
|
||||
|
||||
#------------------------------------------------------------
|
||||
#
|
||||
# Lock testing
|
||||
#
|
||||
#------------------------------------------------------------
|
||||
|
||||
class LockTest(TestCase):
|
||||
"Defines the lock test base"
|
||||
def setUp(self):
|
||||
"sets up the testing environment"
|
||||
|
||||
self.obj1 = create.create_object(settings.BASE_OBJECT_TYPECLASS, key="obj1")
|
||||
self.obj2 = create.create_object(settings.BASE_OBJECT_TYPECLASS, key="obj2")
|
||||
|
||||
class TestLockCheck(LockTest):
|
||||
def testrun(self):
|
||||
dbref = self.obj2.dbref
|
||||
self.obj1.locks.add("owner:dbref(%s);edit:dbref(%s) or perm(Wizards);examine:perm(Builders) and id(%s);delete:perm(Wizards);get:all()" % (dbref, dbref, dbref))
|
||||
self.obj2.permissions = ['Wizards']
|
||||
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'owner'))
|
||||
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'edit'))
|
||||
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'examine'))
|
||||
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'delete'))
|
||||
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'get'))
|
||||
self.obj1.locks.add("get:false()")
|
||||
self.assertEquals(False, self.obj1.locks.check(self.obj2, 'get'))
|
||||
self.assertEquals(True, self.obj1.locks.check(self.obj2, 'not_exist', default=True))
|
||||
class TestLockfuncs(LockTest):
|
||||
def testrun(self):
|
||||
self.obj2.permissions = ['Wizards']
|
||||
self.assertEquals(True, lockfuncs.true(self.obj2, self.obj1))
|
||||
self.assertEquals(False, lockfuncs.false(self.obj2, self.obj1))
|
||||
self.assertEquals(True, lockfuncs.perm(self.obj2, self.obj1, 'Wizards'))
|
||||
self.assertEquals(True, lockfuncs.perm_above(self.obj2, self.obj1, 'Builders'))
|
||||
dbref = self.obj2.dbref
|
||||
self.assertEquals(True, lockfuncs.dbref(self.obj2, self.obj1, '%s' % dbref))
|
||||
self.obj2.db.testattr = 45
|
||||
self.assertEquals(True, lockfuncs.attr(self.obj2, self.obj1, 'testattr', '45'))
|
||||
self.assertEquals(False, lockfuncs.attr_gt(self.obj2, self.obj1, 'testattr', '45'))
|
||||
self.assertEquals(True, lockfuncs.attr_ge(self.obj2, self.obj1, 'testattr', '45'))
|
||||
self.assertEquals(False, lockfuncs.attr_lt(self.obj2, self.obj1, 'testattr', '45'))
|
||||
self.assertEquals(True, lockfuncs.attr_le(self.obj2, self.obj1, 'testattr', '45'))
|
||||
self.assertEquals(False, lockfuncs.attr_ne(self.obj2, self.obj1, 'testattr', '45'))
|
||||
Loading…
Add table
Add a link
Reference in a new issue