def pdp_main(db_session, pdp_request): check_request(pdp_request) jwt_payload = get_jwt_payload(pdp_request['jwt']) user_id = jwt_payload['userid'] # try to retrieve the veredict from cache cached_veredict = cache.get_key(user_id, pdp_request['action'], pdp_request['resource']) # Return the cached answer if it exist if cached_veredict: LOGGER.info('user ' + str(user_id) + ' ' + cached_veredict + ' to ' + pdp_request['action'] + ' on ' + pdp_request['resource'] + ' from cache') return cached_veredict user_groups = [ g.group_id for g in UserGroup.query.filter_by(user_id=user_id).all() ] veredict = iterate_permissions(user_id, user_groups, pdp_request['action'], pdp_request['resource']) # Registry this veredict on cache cache.set_key(user_id, pdp_request['action'], pdp_request['resource'], veredict) LOGGER.info('user ' + str(user_id) + ' ' + veredict + ' to ' + pdp_request['action'] + ' on ' + pdp_request['resource'] + ' registered on cache') return veredict
def deleteUser(dbSession, user, requester): try: user = User.getByNameOrID(user) if user.id == requester['userid']: raise HTTPRequestError(400, "a user can't remove himself") dbSession.execute( UserPermission.__table__.delete(UserPermission.user_id == user.id) ) dbSession.execute( UserGroup.__table__.delete(UserGroup.user_id == user.id) ) cache.deleteKey(userid=user.id) # The user is not hardDeleted. # it should be copied to inactiveUser table inactiveTables.PasswdInactive.createInactiveFromUser(dbSession, user,) inactiveTables.UserInactive.createInactiveFromUser(dbSession, user, requester['userid']) passwd.expirePasswordResetRequests(dbSession, user.id) dbSession.delete(user) log().info('user ' + user.username + ' deleted by ' + requester['username'], user.safeDict()) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No user found with this ID")
def delete_perm(db_session, permission: str, requester): """ Removes a permission from the system :param db_session: The postgres session to be used. :param permission: String The permission to be removed (name or ID). :param requester: Who is creating this user. This is a dictionary with two keys: "userid" and "username". :return: :raises HTTPRequestError: Can't delete a system permission. """ try: perm = Permission.get_by_name_or_id(permission) if perm.type == PermissionTypeEnum.api: db_session.execute( UserPermission.__table__.delete( UserPermission.permission_id == perm.id)) db_session.execute( GroupPermission.__table__.delete( GroupPermission.permission_id == perm.id)) cache.delete_key(action=perm.method, resource=perm.path) LOGGER.info( f"permission {perm.name} deleted by {requester['username']}") LOGGER.info(perm.safe_dict()) db_session.delete(perm) db_session.commit() MVUserPermission.refresh() MVGroupPermission.refresh() else: raise HTTPRequestError(405, "Can't delete a system permission") except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID or name")
def add_user_group(db_session, user, group, requester): try: user = User.get_by_name_or_id(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, f"No user found with this ID or name: {user}") try: group = Group.get_by_name_or_id(group) except orm_exceptions.NoResultFound: raise HTTPRequestError( 404, f"No group found with this ID or name: {group}") if db_session.query(UserGroup).filter_by(user_id=user.id, group_id=group.id).one_or_none(): raise HTTPRequestError(409, "User is already a member of the group") r = UserGroup(user_id=user.id, group_id=group.id) db_session.add(r) cache.delete_key(userid=user.id) user.reset_token() db_session.add(user) log().info( f"user {user.username} added to group {group.name} by {requester['username']}" ) db_session.commit()
def delete_user(db_session, username: str, requester): """ Deletes an user from the system :param db_session: The postgres session to be used :param username: String The user to be removed :param requester: Who is creating this user. This is a dictionary with two keys: "userid" and "username" :return: The removed user :raises HTTPRequestError: If the user tries to remove itself. :raises HTTPRequestError: Can't delete the admin user. :raises HTTPRequestError: If the user is not in the database. """ try: user = User.get_by_name_or_id(username) if user.id == requester['userid']: raise HTTPRequestError(400, "a user can't remove himself") elif user.username == 'admin': raise HTTPRequestError(405, "Can't delete the admin user") db_session.execute( UserPermission.__table__.delete(UserPermission.user_id == user.id)) db_session.execute( UserGroup.__table__.delete(UserGroup.user_id == user.id)) cache.delete_key(userid=user.id) # The user is not hardDeleted. # it should be copied to inactiveUser table inactiveTables.PasswdInactive.createInactiveFromUser( db_session, user, ) inactiveTables.UserInactive.createInactiveFromUser( db_session, user, requester['userid']) password.expire_password_reset_requests(db_session, user.id) db_session.delete(user) LOGGER.info(f"user {user.username} deleted by {requester['username']}") LOGGER.info(user.safe_dict()) kongUtils.remove_from_kong(user.username) MVUserPermission.refresh() MVGroupPermission.refresh() db_session.commit() if count_tenant_users(db_session, user.service) == 0: LOGGER.info( f"will emit tenant lifecycle event {user.service} - DELETE") Publisher.send_notification({ "type": 'DELETE', 'tenant': user.service }) return user except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this ID")
def delete_group(db_session, group, requester): try: group = Group.getByNameOrID(group) db_session.execute( GroupPermission.__table__.delete( GroupPermission.group_id == group.id)) db_session.execute( UserGroup.__table__.delete(UserGroup.group_id == group.id)) cache.delete_key() log().info( 'group ' + group.name + ' deleted by ' + requester['username'], group.safeDict()) db_session.delete(group) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No group found with this ID")
def g(tl, text, professional=True, server_side=True): text = clean(text) m = md5.new() m.update('en') m.update(tl) m.update(text) m.update('y') m.update('y') if professional: m.update('speaklikeapi') md5hash = str(m.hexdigest()) t = Cache.getitem('/t/' + md5hash + '/text') if t is not None and len(t) > 1: return t else: speaklikeusername = Settings.get('speaklikeusername') speaklikepw = Settings.get('speaklikepw') speaklikelangs = ['pt', 'ru', 'nl', 'de', 'cs', 'fr', 'it', 'ar', 'ja', 'es', 'zh', 'pl', 'el', 'da'] if tl not in speaklikelangs: professional = False if professional: t = Translation.lucky('en', tl, text, lsp='speaklikeapi', lspusername=SPEAKLIKE_USERNAME, lsppw=SPEAKLIKE_PW, userip=userip) else: t = Translation.lucky('en', tl, text, userip=userip) return t
def delete_perm(db_session, permission, requester): try: perm = Permission.getByNameOrID(permission) db_session.execute( UserPermission.__table__.delete( UserPermission.permission_id == perm.id)) db_session.execute( GroupPermission.__table__.delete( GroupPermission.permission_id == perm.id)) cache.delete_key(action=perm.method, resource=perm.path) log().info( 'permission ' + str(perm.name) + ' deleted by ' + requester['username'], perm.safeDict()) db_session.delete(perm) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID or name")
def removeUserPermission(dbSession, user, permission, requester): try: user = User.getByNameOrID(user) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No user found with this ID or name") try: perm = Permission.getByNameOrID(permission) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID") try: relation = dbSession.query(UserPermission) \ .filter_by(user_id=user.id, permission_id=perm.id).one() dbSession.delete(relation) cache.deleteKey(userid=user.id, action=perm.method, resource=perm.path) log().info('user ' + user.username + ' removed permission ' + perm.name + ' by ' + requester['username']) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "User does not have this permission")
def removeUserGroup(dbSession, user, group, requester): try: user = User.getByNameOrID(user) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No user found with this ID or name") try: group = Group.getByNameOrID(group) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No group found with this ID or name") try: relation = dbSession.query(UserGroup) \ .filter_by(user_id=user.id, group_id=group.id).one() dbSession.delete(relation) cache.deleteKey(userid=user.id) log().info('user ' + user.username + ' removed from ' + group.name + ' by ' + requester['username']) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "User is not a member of the group")
def removeGroupPermission(dbSession, group, permission, requester): try: group = Group.getByNameOrID(group) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No group found with this ID or name") try: perm = Permission.getByNameOrID(permission) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID") try: relation = dbSession.query(GroupPermission) \ .filter_by(group_id=group.id, permission_id=perm.id).one() dbSession.delete(relation) cache.deleteKey(action=perm.method, resource=perm.path) log().info('permission ' + perm.name + ' removed from ' ' group ' + group.name + ' by ' + requester['username']) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "Group does not have this permission")
def remove_user_group(db_session, user, group, requester): try: user = User.get_by_name_or_id(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this ID or name") try: group = Group.get_by_name_or_id(group) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No group found with this ID or name") try: relation = db_session.query(UserGroup) \ .filter_by(user_id=user.id, group_id=group.id).one() db_session.delete(relation) cache.delete_key(userid=user.id) log().info(f"user {user.username} removed from {group.name} by {requester['username']}") db_session.commit() except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "User is not a member of the group")
def addUserGroup(dbSession, user, group, requester): try: user = User.getByNameOrID(user) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No user found with this ID or name") try: group = Group.getByNameOrID(group) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No group found with this ID or name") if dbSession.query(UserGroup).filter_by(user_id=user.id, group_id=group.id).one_or_none(): raise HTTPRequestError(409, "User is already a member of the group") r = UserGroup(user_id=user.id, group_id=group.id) dbSession.add(r) cache.deleteKey(userid=user.id) log().info('user ' + user.username + ' added to group ' + group.name + ' by ' + requester['username'])
def addGroupPermission(dbSession, group, permission, requester): try: group = Group.getByNameOrID(group) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No group found with this ID or name") try: perm = Permission.getByNameOrID(permission) except sqlalchemy.orm.exc.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID or name") if dbSession.query(GroupPermission) \ .filter_by(group_id=group.id, permission_id=perm.id).one_or_none(): raise HTTPRequestError(409, "Group already have this permission") r = GroupPermission(group_id=group.id, permission_id=perm.id) dbSession.add(r) cache.deleteKey(action=perm.method, resource=perm.path) log().info('permission ' + perm.name + ' added to group ' + group.name + ' by ' + requester['username'])
def remove_group_permission(db_session, group, permission, requester): try: group = Group.get_by_name_or_id(group) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No group found with this ID or name") try: perm = Permission.get_by_name_or_id(permission) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID") try: relation = db_session.query(GroupPermission) \ .filter_by(group_id=group.id, permission_id=perm.id).one() db_session.delete(relation) cache.delete_key(action=perm.method, resource=perm.path) log().info(f"permission {perm.name} removed from group {group.name} by {requester['username']}") MVGroupPermission.refresh() db_session.commit() except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "Group does not have this permission")
def remove_user_permission(db_session, user, permission, requester): try: user = User.get_by_name_or_id(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this ID or name") try: perm = Permission.get_by_name_or_id(permission) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID") try: relation = db_session.query(UserPermission) \ .filter_by(user_id=user.id, permission_id=perm.id).one() db_session.delete(relation) cache.delete_key(userid=user.id, action=perm.method, resource=perm.path) log().info(f"permission {perm.name} for user {user.username} was revoked by {requester['username']}") MVUserPermission.refresh() db_session.commit() except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "User does not have this permission")
def add_group_permission(db_session, group, permission, requester): try: group = Group.get_by_name_or_id(group) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No group found with this ID or name") try: perm = Permission.get_by_name_or_id(permission) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID or name") if db_session.query(GroupPermission) \ .filter_by(group_id=group.id, permission_id=perm.id).one_or_none(): raise HTTPRequestError(409, "Group already have this permission") r = GroupPermission(group_id=group.id, permission_id=perm.id) db_session.add(r) cache.delete_key(action=perm.method, resource=perm.path) log().info(f"permission {perm.name} added to group {group.name} by {requester['username']}") MVGroupPermission.refresh() db_session.commit()
def delete_group(db_session, group, requester): try: group = Group.get_by_name_or_id(group) if group.name == 'admin': raise HTTPRequestError(405, "Can't delete admin group") db_session.execute( GroupPermission.__table__.delete( GroupPermission.group_id == group.id)) db_session.execute( UserGroup.__table__.delete(UserGroup.group_id == group.id)) cache.delete_key() LOGGER.info( 'group ' + group.name + ' deleted by ' + requester['username'], group.safe_dict()) db_session.delete(group) MVGroupPermission.refresh() db_session.commit() except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No group found with this ID")
def add_user_permission(db_session, user, permission, requester): try: user = User.getByNameOrID(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this ID or name") try: perm = Permission.getByNameOrID(permission) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID") if db_session.query(UserPermission) \ .filter_by(user_id=user.id, permission_id=perm.id).one_or_none(): raise HTTPRequestError(409, "User already have this permission") r = UserPermission(user_id=user.id, permission_id=perm.id) db_session.add(r) cache.delete_key(userid=user.id, action=perm.method, resource=perm.path) log().info('user ' + user.username + ' received permission ' + perm.name + ' by ' + requester['username'])
def add_user_permission(db_session, user, permission, requester): try: user = User.get_by_name_or_id(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this ID or name") try: perm = Permission.get_by_name_or_id(permission) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID") if db_session.query(UserPermission) \ .filter_by(user_id=user.id, permission_id=perm.id).one_or_none(): raise HTTPRequestError(409, "User already have this permission") r = UserPermission(user_id=user.id, permission_id=perm.id) db_session.add(r) cache.delete_key(userid=user.id, action=perm.method, resource=perm.path) MVUserPermission.refresh() db_session.commit() log().info( f"user {user.username} received permission {perm.name} by {requester['username']}" )
def pdpMain(dbSession, pdpRequest): checkRequest(pdpRequest) jwtPayload = getJwtPayload(pdpRequest['jwt']) user_id = jwtPayload['userid'] # try to retrieve the veredict from cache cachedVeredict = cache.getKey(user_id, pdpRequest['action'], pdpRequest['resource']) # Return the cached answer if it exist if cachedVeredict: log().info('user ' + user_id + ' ' + cachedVeredict + ' to ' + pdpRequest['action'] + ' on ' + pdpRequest['resource']) return cachedVeredict veredict = iteratePermissions(user_id, jwtPayload['groups'], pdpRequest['action'], pdpRequest['resource']) # Registry this veredict on cache cache.setKey(user_id, pdpRequest['action'], pdpRequest['resource'], veredict) log.info('user ' + user_id + ' ' + veredict + ' to ' + pdpRequest['action'] + ' on ' + pdpRequest['resource']) return veredict
def pdp_main(db_session, pdp_request): check_request(pdp_request) jwt_payload = get_jwt_payload(pdp_request['jwt']) user_id = jwt_payload['userid'] # try to retrieve the veredict from cache cached_veredict = cache.get_key(user_id, pdp_request['action'], pdp_request['resource']) # Return the cached answer if it exist if cached_veredict: log().info('user ' + str(user_id) + ' ' + cached_veredict + ' to ' + pdp_request['action'] + ' on ' + pdp_request['resource']) return cached_veredict veredict = iterate_permissions(user_id, jwt_payload['groups'], pdp_request['action'], pdp_request['resource']) # Registry this veredict on cache cache.set_key(user_id, pdp_request['action'], pdp_request['resource'], veredict) log().info('user ' + str(user_id) + ' ' + veredict + ' to ' + pdp_request['action'] + ' on ' + pdp_request['resource']) return veredict
def dropCache(): cache.deleteKey() return formatResponse(200)
def drop_cache(): cache.delete_key() return format_response(200)
def get(self, p1='', p2='', p3=''): slu = Settings.get('speaklikeusername') slp = Settings.get('speaklikepw') try: locales = string.split(self.request.headers['Accept-Language'],',') except: locales = 'en-us' found_locale = False language = '' locale = '' for l in locales: langloc = string.split(l, '-') if len(language) < 1: language = langloc[0] if not found_locale: f = FBLocales() locale = f.lookup(langloc[0]) if locale is not None: if len(locale) > 1: found_locale=True if not found_locale: locale = 'en_US' if len(language) < 1: language = 'en' dmenus = '<ul><li><a href=http://www.worldwidelexicon.org>Worldwide Lexicon</a></li>\ <li><a href=http://www.worldwidelexicon.org>' + g(language,clean('Tools For Webmasters')) + '</a></li></ul>' if len(language) > 2: language = language[0:2] proxy_settings = '<meta name="allow_edit" content="y" />' lsp = '' lspusername = '' lsppw = '' userip = self.request.remote_addr headers = self.request.headers host = headers.get('host','') if p1 == 'blog': self.redirect('http://blog.worldwidelexicon.org') elif host == 'www.worldwidelexicon.org': self.redirect('http://www.worldwidelexicon.org/home') elif p1 == 's': self.error(404) self.response.out.write('<h2>Page Not Found</h2>') else: w = web() w.get(template) w.replace(template,'[social_translation]', clean(g(language,'Social Translation'))) t = '' t = t + clean(g(language, 'Machine translation is great, but we all know it often produces inaccurate (and sometimes funny) translations. ')) t = t + clean(g(language, 'Der Mundo is the worldwide web, translated by people. We use machine translation (from Google Translate and Apertium) to produce a rough draft. ')) t = t + clean(g(language, 'Then users take over to edit the translations, score translations from other users, and make them better.<p>')) w.replace(template, '[introduction]', t) t = '<p><table><form action=/translate/project method=get>' t = t + '</select></td></tr>' t = t + '<tr><td>URL</td><td><input type=text size=40 name=u value="http://www.aljazeera.net"></td></tr>' # t = t + '<tr><td>Require encryption</td><td><input type=checkbox value=y name=secure></td></tr>' t = t + '<tr><td colspan=2>' + g(language, 'Optional professional translation by <a href=http://www.speaklike.com>SpeakLike</a>') + '</td></tr>' t = t + '<tr><td>SpeakLike username</td><td><input type=text name=lspusername></td></tr>' t = t + '<tr><td>SpeakLike password</td><td><input type=password name=lsppw></td></tr>' t = t + '<tr><td></td><td>' t = t + ' ' + g(language,'Professional translations are usually completed within 24 hours.') t = t + ' ' + g(language,'We will provide a temporary machine translation until then.') t = t + ' ' + g(language,'When completed, professional translations will be visible to other users.') t = t + '</td></tr>' t = t + '<tr><td colspan=2><input type=submit value="' + g(language, 'Translate!', server_side=True) + '"></td></tr>' t = t + '</form></table><p>' w.replace(template,'[start_form]',t) w.replace(template,'[google_analytics]',google_analytics_header) w.replace(template,'[title]','Der Mundo : ' + g(language,'Translate the world with your friends', server_side=True)) w.replace(template,'[meta]', sharethis_header + snapshot_code) w.replace(template,'[copyright]',standard_footer) w.replace(template,'[menu]',dmenus) w.replace(template,'[about]', g(language,'About')) w.replace(template,'[tagline]', g(language, 'Translate the world with your friends')) w.replace(template,'[share_this_page]', g(language, 'Share This Page')) w.replace(template,'[share_this_button]', sharethis_button) w.replace(template,'[instructions]', g(language, 'Instructions')) w.replace(template,'[instructions_prompt]', g(language, instructions)) w.replace(template,'[language]', language) w.replace(template,'[wordpress]', g(language, wordpress)) w.replace(template,'[wordpress_prompt]', g(language, wordpress_prompt)) w.replace(template,'[firefox]', g(language, firefox)) w.replace(template,'[firefox_prompt]', g(language,firefox_prompt)) text = """<div id="fb-root"></div> <script src="http://connect.facebook.net/""" + locale + """/all.js"></script> <script> FB.init({ appId : '140342715320', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); </script> <fb:login-button autologoutlink="true" width="200">Login with Facebook</fb:login-button>""" user = FBUser.lookup(self.request.cookies, self.request.remote_addr) #if user is not None: # text = text + '<p><a href=' + user.get('profile_url','') + '><img src=http://graph.facebook.com/' + user.get('id ','')+ '/picture?type=square/></a></p>' text = text + """ """ w.replace(template,'[facebook_login]',text) text = '<fb:like show_faces="true" width="450"></fb:like><br>' w.replace(template,'[facebook_like]',text) Cache.setitem('/dermundo/cache/' + language, w.out(template), 600) self.response.out.write(w.out(template))