def getBoxFromParentChain(db, path, parentBox): """ Given a path and a box to start with, the box identified by the path is returned, with all its permissions set along the way. """ subBoxDict = dbRetrieveRecordByKey( db, 'boxes', {'box_name': path[0], 'parent_id': parentBox.box_id}, dbTablesDesc=dbSchema, ) if subBoxDict is None: return None else: subPath = path[1:] subBox = Box(**subBoxDict) thisBoxPermissions = list(dbGetBoxRolePermissions(db, subBox.box_id)) subBox.updatePermissionData( fromBox=parentBox, lastPermissionLayer=thisBoxPermissions, ) if len(subPath) < 1: return subBox else: return getBoxFromParentChain(db, subPath, subBox)
def dbDeleteTicket(db, ticketId, user, mode, skipCommit=False): """ Remove a ticket from DB.""" ticketDict = dbRetrieveRecordByKey( db, 'tickets', {'ticket_id': ticketId}, dbTablesDesc=dbSchema, ) if (ticketDict is not None and ticketTargetTypeToModeNameMap[ticketDict['target_type']] == mode): ticket = Ticket(**ticketDict) if userIsAdmin(db, user) or user.username == ticket.username: # dbDeleteRecordsByKey( db, 'tickets', {'ticket_id': ticketId}, dbTablesDesc=dbSchema, ) if not skipCommit: db.commit() else: raise OstracionError('Insufficient permissions') else: raise OstracionWarning('Ticket unavailable')
def dbGetUser(db, username): """Retrieve a user given its username.""" userDict = dbRetrieveRecordByKey( db, 'users', {'username': username}, dbTablesDesc=dbSchema, ) return User(**userDict) if userDict is not None else None
def dbGetUserRoles(db, user, asDict=False): """ Retrieve roles associated to a user. Here we implement the automatic attribution of anonymous role to unauthenticated visitors. """ anonymousRole = dbRetrieveRecordByKey( db, 'roles', { 'role_id': 'anonymous', 'role_class': 'system' }, dbTablesDesc=dbSchema, ) # if user.is_authenticated: for userRole in (ur for urBlock in (dbRetrieveRecordsByKey( db, 'user_roles', {'username': user.username}, dbTablesDesc=dbSchema, ), (anonymousRole, )) for ur in urBlock): # role = dbRetrieveRecordByKey( db, 'roles', { 'role_class': userRole['role_class'], 'role_id': userRole['role_id'], }, dbTablesDesc=dbSchema, ) # if asDict: yield role else: yield Role(**role) else: if asDict: yield anonymousRole else: yield anonymousRole(**role)
def secondsToWaitBeforeLogin(db, ipAddress, doWrite, loginProtectionSeconds, hashSalt, skipCommit=False): """ Check at once if the record exists and if the login is attemptable. Moreover update/insert the attempted-login entry in all cases and finally (optionally) commit. """ # atLogin = AttemptedLogin( sender_hash=hashOfIpAddress(ipAddress, hashSalt=hashSalt), datetime=datetime.datetime.now(), ) # prevLoginDict = dbRetrieveRecordByKey( db, 'attempted_logins', {'sender_hash': atLogin.sender_hash}, dbTablesDesc=dbSchema, ) if prevLoginDict is not None: prevLogin = AttemptedLogin(**prevLoginDict) else: prevLogin = None # if (prevLogin is None or (datetime.datetime.now() - prevLogin.datetime).seconds >= loginProtectionSeconds): secondsToWait = 0 else: secondsToWait = loginProtectionSeconds - (datetime.datetime.now() - prevLogin.datetime).seconds # if doWrite and secondsToWait <= 0: if prevLogin is None: dbAddRecordToTable( db, 'attempted_logins', atLogin.asDict(), dbTablesDesc=dbSchema, ) else: dbUpdateRecordOnTable( db, 'attempted_logins', atLogin.asDict(), dbTablesDesc=dbSchema, ) if not skipCommit: db.commit() # return secondsToWait
def dbGetSetting(db, sgKlass, sgId, sId, user): """Load a given setting and return it as enriched.""" return _enrichSettingObject( Setting(**dbRetrieveRecordByKey( db, 'settings', { 'klass': sgKlass, 'group_id': sgId, 'id': sId, }, dbTablesDesc=dbSchema, )))
def _retrieveAncestorIds(db, bx, ids=[]): if bx.box_id == '': return ids + [bx.box_id] else: return _retrieveAncestorIds( db, Box(**dbRetrieveRecordByKey( db, 'boxes', {'box_id': bx.parent_id}, dbTablesDesc=dbSchema, )), ids=ids + [bx.box_id], )
def _retraceBoxPath(db, boxId, builtPath=[]): """ From a box ID rebuild the corresponding path (by retracing the parent boxes all the way up to root. The id of the box itself is included in the result. """ if boxId == '': return [''] + builtPath else: thisBox = dbRetrieveRecordByKey(db, 'boxes', {'box_id': boxId}, dbTablesDesc=dbSchema) return _retraceBoxPath( db, thisBox['parent_id'], [thisBox['box_name']] + builtPath, )
def getLinkFromParent( db, parentBox, linkName, user, accountDeletionInProgress=False): """ Given a box and the name of a link supposedly contained in it, return the link (or None). """ linkDict = dbRetrieveRecordByKey( db, 'links', {'name': linkName, 'box_id': parentBox.box_id}, dbTablesDesc=dbSchema, ) if linkDict is not None: return Link(**linkDict) else: return None
def getFileFromParent( db, parentBox, fileName, user, accountDeletionInProgress=False): """ Given a box and the name of a file supposedly contained in it, return the file (or None). """ fileDict = dbRetrieveRecordByKey( db, 'files', {'name': fileName, 'box_id': parentBox.box_id}, dbTablesDesc=dbSchema, ) if fileDict is not None: return File(**fileDict) else: return None
def getRootBox(db): """ Return the root box with permissions set. """ boxDict = dbRetrieveRecordByKey( db, 'boxes', {'box_id': ''}, dbTablesDesc=dbSchema, ) rootBoxPermissions = list(dbGetBoxRolePermissions(db, '')) # thisBox = Box(**boxDict) thisBox.setPermissionData( permissions=rootBoxPermissions, permissionHistory=[rootBoxPermissions], lastPermissionLayer=rootBoxPermissions, ) return thisBox
def dbGetRole(db, roleClass, roleId, user): """Retrieve a role from DB by ID.""" if userIsAdmin(db, user): roleDict = dbRetrieveRecordByKey( db, 'roles', { 'role_id': roleId, 'role_class': roleClass }, dbTablesDesc=dbSchema, ) if roleDict is not None: return Role(**roleDict) else: return None else: return None
def dbGetEnrichAndCheckTicket(db, mode, ticketId, securityCode, urlRoot): """ Check validity (proper codes, existence) of a ticket and return it enriched. """ ticketDict = dbRetrieveRecordByKey( db, 'tickets', {'ticket_id': ticketId}, dbTablesDesc=dbSchema, ) if ticketDict is None: return None else: ticket = Ticket(**ticketDict) if all([ ticketTargetTypeToModeNameMap[ticket.target_type] == mode, ticket.security_code == securityCode, ]): return enrichTicket(db, ticket, urlRoot) else: return None
def convertRoleRelatedRecord(db, legacySchema, srcTableName, inRecord): if srcTableName == 'roles': isSystem = inRecord['system'] != 0 outRecord = { 'role_id': inRecord['role_id'], 'role_class': determineRoleClass(inRecord), # 'system' DISAPPEARS 'description': inRecord['description'], 'can_box': ( 0 if isSystem and inRecord['role_id'] == 'ticketer' else 1 ), 'can_user': ( 0 if isSystem and inRecord['role_id'] == 'anonymous' else 1 ), 'can_delete': 0 if isSystem else 1, } return outRecord elif srcTableName in {'box_role_permissions', 'user_roles'}: referenceRole = dbRetrieveRecordByKey( db, 'roles', {'role_id': inRecord['role_id']}, dbTablesDesc=legacySchema, ) outRecord = recursivelyMergeDictionaries( {'role_class': determineRoleClass(referenceRole)}, defaultMap=inRecord, ) return outRecord else: raise NotImplementedError('Cannot translate records for table "%s"' % ( srcTableName, ))
def generalisedGetUserRoles(db, user): """ Look up the roles of the user taking into account the non-logged-in case. """ if user is not None: if hasattr(user, 'roles') and user.roles is not None: return user.roles else: # the user object can have been created e.g. # during an user deletion request and not via the login # flask handler (whereupon it would get roles as well) return list(dbGetUserRoles(db, user)) else: return [ Role(**dbRetrieveRecordByKey( db, 'roles', { 'role_class': 'system', 'role_id': 'anonymous' }, dbTablesDesc=dbSchema, )) ]
print(' * done.') else: # special handling of some tables if tName == 'settings': # here we add new settings and refresh some fields of the # existing ones (namely all but 'value') tcontents = initialDbValues.get(tName) print(' * Refreshing') for item in tcontents['values']: model = tcontents['model'](**item) print(' - %s : ' % model, end='') itemDictFound = dbRetrieveRecordByKey( db, tName, { 'group_id': item['group_id'], 'id': item['id'] }, dbTablesDesc=dbSchema, ) if itemDictFound is None: # new: insert print('inserting... ', end='') dbAddRecordToTable( db, tName, model.asDict(), dbTablesDesc=dbSchema, ) print('done ', end='') else: