def get(self): assert self.current_user origin = self.get_argument("origin", None) session = model.Session() actions_param = self.get_argument("actions", None) where = [model.UserConsent.user_id==self.current_user] if origin is not None: where.append(model.UserConsent.origin==origin) if actions_param is not None: actions = actions_param.split(",") where.append(model.UserConsent.operation.in_(actions)) existing = session.query(model.UserConsent).filter( and_(*where)).all() result = {} for e in existing: origin_result = result.setdefault(e.origin, {}) origin_result[e.operation] = e.allowed # work out if we are trying to serve up the html ui or just the data. accepts = urllib2.parse_http_list(self.request.headers.get("Accept", "")) try: json_ndx = accepts.index("application/json") except ValueError: json_ndx = 10000 try: html_ndx = accepts.index("text/html") except ValueError: html_ndx = 10000 if html_ndx < json_ndx: self.render("consent.html", consent_items=result) else: self.write(result)
def ban_check(numip, name, subject, comment): '''This function raises an exception if the IP address is banned, or the post contains a forbidden (non-spam) string. It otherwise returns nothing.''' session = model.Session() table = model.admin # IP Banned? sql = table.select().where(and_(table.c.type == 'ipban', table.c.ival1.op('&')(table.c.ival2) \ == table.c.ival2.op('&')(numip))) ip_row = session.execute(sql).fetchone() if ip_row: raise WakaError('Address %s banned. Reason: %s' % \ (misc.dec_to_dot(numip), ip_row.comment)) # To determine possible string bans, first normalize input to lowercase. comment = comment.lower() subject = subject.lower() name = name.lower() sql = select([table.c.sval1], table.c.type == 'wordban') query = session.execute(sql) for row in query: bad_string = row.sval1.lower() if comment.count(bad_string) or subject.count(bad_string) or \ name.count(bad_string): raise WakaError(strings.STRREF)
def post(self): assert self.current_user session = model.Session() origin = self.get_argument("origin") for operation, values in self.request.arguments.iteritems(): if operation=="origin": # gross... continue print "HAVE OPERATION", operation, values if values[0]=='null': allowed = None else: allowed = values[0]=='true' try: existing = session.query(model.UserConsent).filter( and_(model.UserConsent.user_id==self.current_user, model.UserConsent.origin==origin, model.UserConsent.operation==operation )).one() except NoResultFound: if allowed is not None: uc = model.UserConsent(self.current_user, origin, operation, allowed) session.add(uc) else: if allowed is None: # request to 'unremember' session.delete(existing) else: existing.allowed = allowed session.commit() self.write("<html><body>permissions updated</body></html>")
def get(self, req_type): if req_type == "request": got = self.request_access() if got is not None: self.write(got) elif req_type == "verify": data = self.verify() identifier = data['profile']['identifier'] session = model.Session() # XXX - should update profile info? existing = model.identity(session, identifier) if not existing: # Must be a new user. user = model.User() session.add(user) dn = data['profile']['displayName'] provider = data['profile']['provider'] identity = model.Identity(identifier, user, dn, provider) session.add(identity) elif len(existing) == 1: identity = existing[0] else: raise AssertionError("more than one identity??") self.set_secure_cookie('uid', str(identity.user_id)) identity.verifiedNow() session.commit() req_return_to = self.get_secure_cookie('req_return_to') self.clear_cookie('req_return_to') if not req_return_to: req_return_to = "/" self.redirect(req_return_to) else: raise tornado.web.HTTPError(404)
def remove_old_backups(): session = model.Session() table = model.backup sql = table.select().where(table.c.timestampofarchival.op('+')\ (config.POST_BACKUP_EXPIRE) <= time.time()) query = session.execute(sql) for row in query: board_obj = board.Board(row['board_name']) backup_path = os.path.join(board_obj.path, board_obj.options['ARCHIVE_DIR'], board_obj.options['BACKUP_DIR'], '') if row.image: # Delete backup image; then, mark post for deletion. filename = os.path.join(backup_path, os.path.basename(row.image)) if os.path.exists(filename): os.unlink(filename) if row.thumbnail \ and re.match(board_obj.options['THUMB_DIR'], row.thumbnail): filename = os.path.join(backup_path, os.path.basename(row.thumbnail)) if os.path.exists(filename): os.unlink(filename) # Perform SQL DELETE sql = table.delete().where(table.c.timestampofarchival.op('+')\ (config.POST_BACKUP_EXPIRE) <= time.time()) session.execute(sql)
def doUpdates(): """ Function of the script to be ran every 30 minutes or every hour under lock protection. Open connection to the validator and obtain data. Count stats and run updates to the DB. """ # open RIPE validator connection apiep = RIPEValidatorConnector.RPKIValidatorAPI() # get current metadata bgpprev = apiep.getBGPPreview() totalCount, lastModified = apiep.decodeBGPPreviewMeta(bgpprev) # get current time currTime = int(time.time()) ts = datetime.datetime.fromtimestamp(currTime) w("Running update at %s (%d)" % (str(ts), currTime)) # test if metadata makes sense if lastModified > currTime: raise Exception("Validator returned last modified time in future: %d" % lastModified) w("Validator returned: lastModified=%d (%s) totalCount=%d" % (lastModified, str( datetime.datetime.fromtimestamp(lastModified)), totalCount)) # open DB connection sess = model.Session() # test if date point is linear in time if ts > getLastUpdate(sess): stats = defaultdict(lambda: 0) conflicts = {} # extract data from validator response data = apiep.extractBGPPreviewData(bgpprev) for dr in data: asn, pfx, val = apiep.decodeBGPPrevRow(dr) stats[val] += 1 if val >= RIPEValidatorConnector.RPKIValidatorAPI.RPKI_INVALID_ASN: conflicts[(asn, pfx)] = val # update conflict records updateRPKIRecords(sess, conflicts, ts) # update stats appendCurrentStats(sess, stats, ts) # finish sess.commit() sess.close() else: w("DB last datapoint in future. Skipping datapoint.") sess.close() endTime = time.time() w("Finished update at %s (%d)" % (str(datetime.datetime.fromtimestamp(endTime)), endTime))
def remove_admin_entry(task_data, num, override_log=False, no_redirect=False): session = model.Session() table = model.admin sql = table.select().where(table.c.num == num) row = session.execute(sql).fetchone() if not row: raise WakaError('Entry not found. Deleted?') ival1 = row['ival1'] ip = misc.dec_to_dot(ival1) if ival1 else '' string_val = row['sval1'] if row['total']: remove_htaccess_entry(ip) sql = table.delete().where(table.c.num == num) session.execute(sql) task_data.action = row['type'] + '_remove' if string_val: task_data.contents.append(row['sval1']) else: task_data.contents.append(ip + ' (' + misc.dec_to_dot(row['ival2']) \ + ')') board = local.environ['waka.board'] forward_url = misc.make_script_url(task='bans', board=board.name) return util.make_http_forward(forward_url, config.ALTERNATE_REDIRECT)
def addUser(): user = login.checkSession() login.checkIsAdmin() dbs = model.Session() renewPass = True if request.forms.id: userI = dbs.query(model.User).get(request.forms.id) if not request.forms.password: renewPass = False else: userI = model.User() salt = uuid.uuid4().hex hashed_password = hashlib.sha1(request.forms.password + salt).hexdigest() userI.Username = request.forms.name userI.Email = request.forms.email if renewPass: userI.Password = hashed_password userI.Hash = salt userI.Credit = request.forms.credits userI.IsAdmin = False dbs.add(userI) dbs.commit() dbs.close() redirect('/admin/users/ok')
def del_img(eid): logging.info('task.del_image:entry id->%s ' % (str(eid))) db = m.Session() target_dir_path = path.join(config.img_storage_path, str(eid)) if path.isdir(target_dir_path): rmtree(target_dir_path) db.close()
def editUser(userid): user = login.checkSession() login.checkIsAdmin() dbs = model.Session() user = dbs.query(model.User).get(userid) dbs.close() return template('admin_includes/addUser', user=user, text='Editar')
def cleanup(*args, **kwargs): '''Destroy the thread-local session and environ''' session = model.Session() session.commit() session.transaction = None # fix for a circular reference model.Session.remove() local.environ = {}
def reset_password(uid): db = m.Session() user = db.query(m.User).filter_by(id=uid).first() if user is None: logging.warning('try reset password for uid->%s but user not found' % (str(uid))) return old_request = db.query(m.Password).filter_by(uid=uid).first() if old_request is not None: db.delete(old_request) token = md5_hexdigest() password = m.Password(token=token, uid=user.id) db.add(password) template = tmp_env.get_template('email/reset_password.txt') subject = 'reset password token' content = template.render(username=user.name, token=token).encode('utf8') to_addr = user.email try: db.commit() except: db.rollback() raise finally: db.close() send_notice(subject, content, to_addr)
def test(): from model import Item session = model.Session() session.add(Item(name='alexey')) session.commit() print(session.query(Item).filter_by(name='alexey').all())
def staff_exists(): session = model.Session() table = model.account sql = select([func.count()], table) row = session.execute(sql).fetchone() return row[0] != 0
def make_admin_staff_panel(self): session = model.Session() table = model.account sql = table.select().order_by(table.c.account.asc(), table.c.username.asc()) query = session.execute(sql) users = [dict(row.items()) for row in query] rowtype = 1 for row in users: # Alternate between values 1 and 2. rowtype ^= 0x3 row['rowtype'] = rowtype # Get latest action from DB. action_table = model.activity action_grab_sql = action_table.select()\ .where(action_table.c.username == row['username'])\ .order_by(action_table.c.date.desc()) last_action = session.execute(action_grab_sql).fetchone() # Copy to row. if last_action: row['action'] = last_action['action'] row['actiondate'] = last_action['date'] else: row['action'] = None row['actiondate'] = None Template.__init__(self, 'staff_management', users=users)
def add_staff(username, pt_password, account, reign): if not username: raise WakaError('A username is necessary.') if not pt_password: raise WakaError('A password is necessary.') if len(pt_password) < 8: raise WakaError('Passwords should be eight characters minimum.') if len(reign) == 0 and account == MODERATOR: raise WakaError('Board reign not specified for moderator account.') # Check whether the user exists already. try: StaffMember.get(username) except LoginError: # User not found. Good. pass else: raise WakaError('Username exists.') session = model.Session() table = model.account password = misc.hide_critical_data(pt_password, config.SECRET) reign_str = ','.join(reign) sql = table.insert().values(username=username, password=password, account=account, reign=reign_str, disabled=0) session.execute(sql)
def _on_access_token(self, callback, response): if response.error: logging.warning("Could not fetch access token") callback(None) return uid = self.get_secure_cookie("uid") if not uid: logging.warn("No user session: redirecting to root") return self.redirect("/") # NOTE that we assume the user has only one GMail account here! # This may be okay given that Google is moving towards single-login/multiple-account # but it could be a problem. access_token = tornado.auth._oauth_parse_response(response.body) session = model.Session() user = model.user(session, uid) id = user.identity(session, model.OP_GOOGLE) if id: id.accessToken = access_token["key"] id.accessSecret = access_token["secret"] session.add(id) session.commit() else: # strange, we have no id for this user self.write( "Whoops - we don't have an authenticated Google login for you. That's weird." ) self.finish() return self.write( "Success. Saved access codes for Google. <a href='/fetch/google'>Take a look</a>" ) self.finish()
def log_in(): """Endpoint for logging in. Request: { 'username': <username>, 'password': <password> } Response: { 'status': <status>, 'msg': <msg> }""" credentials = json.loads(flask.request.data) user = model.User.query.filter( model.User.username == credentials['username']).first() # If user doesn't exist or password is invalid, throw error. if not user or \ not bcrypt.checkpw(credentials['password'].encode(), user.credentials.encode()): return unauthorized() # Create a session with a difficult-to-guess ID. session_id = uuid.uuid4().hex new_session = model.Session(session_id=session_id, user_id=user.user_id) model.db.session.add(new_session) model.db.session.commit() response = flask.jsonify({'status': 'OK', 'msg': 'Successfully logged in'}) response.set_cookie('session_id', value=session_id) return response
def edit_user(user_id): dbtransaction = model.Session() user_data = dbtransaction.query(model.User).get(user_id) dbtransaction.delete(user_data) dbtransaction.commit() dbtransaction.close() return redirect('/admin')
def deleteLead(uId): user = login.checkSession() login.checkIsAdmin() dbs = model.Session() User = dbs.query(model.User).get(uId) dbs.delete(User) dbs.commit() dbs.close() redirect('/admin/users')
def deleteLead(leadId): user = login.checkSession() login.checkIsAdmin() dbs = model.Session() Lead = dbs.query(model.Lead).get(leadId) dbs.delete(Lead) dbs.commit() dbs.close() redirect('/admin/leads')
def admin_section(): dbtransaction = model.Session() users = dbtransaction.query(model.user).all() dbtransaction.close() return template('views/admin/userlist', get_url=webApp.get_url, users=users)
def flush_db(self): session = model.Session() table = self._table if len(self._update_dict) > 0: db_update = table.update()\ .where(table.c.username == self.username)\ .values(**self._update_dict) session.execute(db_update)
def home(): dbs = model.Session() latestLeads = dbs.query(model.Lead).order_by(model.Lead.Date.desc())[0:5] ret = '' for l in latestLeads: firstword = str(l.Name).split(' ', 1) sol = l.Type or l.Brand ret += '<li>' + str(firstword[0]) + ' solicito un ' + sol + '</li>' return ret
def edit_user(user_id): dbtransaction = model.Session() user_data = dbtransaction.query(model.User).get(user_id) dbtransaction.close() return template('views/admin/user_form', get_url=webApp.get_url, user=user_data)
def make_admin_proxy_panel(self): session = model.Session() table = model.proxy query = table.select().order_by(table.c.timestamp.asc()) rows = session.execute(query) Template.__init__(self, 'proxy_panel_template', scanned=rows, now=time.time())
def get(self): uid = self.current_user session = model.Session() user = model.user(session, uid) result = {"status":"ok"} services = result["services"] = [] for anID in user.identities: services.append(anID.name()) self.write(result)
def remove_proxy_entry(task_data, num): session = model.Session() table = model.proxy query = table.delete().where(table.c.num == num) session.execute(query) board = local.environ['waka.board'] forward_url = misc.make_script_url(task='proxy', board=board.name) return util.make_http_forward(forward_url, config.ALTERNATE_REDIRECT)
def userList(status=None): user = login.checkSession() login.checkIsAdmin() dbs = model.Session() userList = dbs.query(model.User).filter(model.User.IsAdmin != True).all() dbs.close() return template('admin_includes/userList', content=userList, stats=status, user=user)
def removeUser(userid): user = login.checkSession() login.checkIsAdmin() dbs = model.Session() userI = dbs.query(model.User).get(userid) dbs.delete(userI) dbs.commit() dbs.close() payload = {} payload['success'] = True return payload