def comment(user_uuid, uuid): logger.info(f'Commenting {uuid}') try: getDB().postComment(uuid, user_uuid, request.form['content']) return redirect(f'/post/{uuid}') except PostNotFoundError: abort(404, f'post/{uuid}')
def vote(user_uuid, post_uuid, comment_uuid): logger.info(f'Replying {comment_uuid}') try: logger.info('VOTING ' + request.form['vote']) getDB().vote(user_uuid, comment_uuid, request.form['vote']) return redirect(f'/post/{post_uuid}') except PostNotFoundError: abort(404, f'post/{post_uuid}') except: abort(500, 'Error voting')
def reply(user_uuid, post_uuid, comment_uuid): logger.info(f'Replying {comment_uuid}') try: getDB().postComment(post_uuid, user_uuid, request.form['content'], replyTo=comment_uuid) return redirect(f'/post/{post_uuid}') except PostNotFoundError: abort(404, f'post/{post_uuid}')
def login(): data = json.loads( crypto.decrypt_RSA_from_sendable_bytes(request.data).decode('utf8')) try: if getDB().checkPassword(data['username'], data['password']): user_uuid = getDB().getUserUUID(data['username']) session['user'] = (getDB().addSession(user_uuid), user_uuid, getDB().getUserFromUUID(user_uuid)[0], getDB().getUserPerms(user_uuid)) return json.dumps({"ok": True}) else: return json.dumps({"error": "Invalid credentials"}) except UserNotFoundError: return json.dumps({"error": "User not found"})
def search_posts_paged(search, page, posts_per_page): posts = [] for post in getDB().searchPostsPaged(search, page, posts_per_page): date = post['date'] post['date'] = utils.formatPostDate(date) posts.append(post) return posts
def get_posts(): posts = [] for post in getDB().getPosts(): date = post['date'] post['date'] = utils.formatPostDate(date) posts.append(post) return posts
def wrapper(*args, **kwargs): user_id = session.get('user')[0] if user_id: try: uuid = getDB().getUserUUIDFromSession(user_id) # check if session id is valid perms = getDB().getUserPerms(uuid) # Success! if perms >= perms_level: return function_to_protect(uuid, *args, **kwargs) else: abort(403, f'Not enough permissions') except UserNotFoundError: session['user'] = None return redirect('/login'), 401 # Session is invalid, redirect to login else: return redirect('/login'), 401
def edit_post_page(_, post_uuid): logger.info(f'Loading post {post_uuid}') try: post = getDB().getPost(post_uuid) return render_template('create_post.html', title=post['title'], content=post['content'], editPost=post_uuid) except PostNotFoundError: abort(404, f'/post/{post_uuid}/edit')
def post(uuid): logger.info(f'Loading post {uuid}') try: useruuid = None if session.get('user'): useruuid = session.get('user')[1] res = make_response( render_template_string(b.getPostTemplate(uuid), post_uuid=uuid, comments=getDB().getComments( uuid, useruuid))) return res except PostNotFoundError: abort(404, f'post/{uuid}')
def getPostTemplate(uuid): post = getDB().getPost(uuid) # l.info((post['title'], post['author'], post['date'], post['content'])) # l.info('''[%s %s %s %s]''' % (post['title'], post['author'], post['date'], post['content'])) template = '''{%% extends "post.html" %%} {%% block title %%} %s {%% endblock %%} {%% block author %%} %s {%% endblock %%} {%% block date %%} %s {%% endblock %%} {%% block markdown %%} %s {%% endblock %%}''' % ( post['title'], post['author'], post['date'], post['content'] ) # The newline has to be there for a code element not to appear # l.info(template) return template
def signup(): data = json.loads( crypto.decrypt_RSA_from_sendable_bytes(request.data).decode('utf8')) try: getDB().addUser(data['username'], data['password'], 0) user_uuid = getDB().getUserUUID(data['username']) session['user'] = (getDB().addSession(user_uuid), user_uuid, getDB().getUserFromUUID(user_uuid)[0], getDB().getUserPerms(user_uuid)) return json.dumps({"ok": True}) except UserDuplicateError: return json.dumps({"error": "Username not available"})
def logout(): getDB().deleteSession(session['user'][0]) session['user'] = None return redirect('/blog')
def edit_post(_, post_uuid): getDB().editPost(post_uuid, request.form['title'], request.form['content']) return redirect('/post/' + post_uuid)
def delete_post(_, post_uuid): getDB().deletePost(post_uuid) return redirect('/blog')
def u_img(uuid): img = getDB().getUserImage(uuid) response = send_file(io.BytesIO(bytes(img)), mimetype='image/png') response.headers.add_header('Cache-Control', 'no-cache') return response
def create_post_POST(uuid): post_uuid = getDB().createPost(request.form['title'], uuid, request.form['content']) return redirect('/post/' + post_uuid)
def setup(): global config global settingUp global hasSetUp global rsa_pub global rsa_priv if not settingUp: start_time = time.time() settingUp = True delete_users = False logger.setup() log = logger.get('Setup') log.info('setup called') if not os.path.lexists('web/post'): os.mkdir('web/post') # Config loading / writing exiting = False try: with open('config.json') as f: log.info('Loading config') try: fixed_json = json.load(f) if 'salt' in fixed_json: fixed_json['salt'] = b64decode(fixed_json['salt'].encode()) # Decode bytes object if len(fixed_json['salt']) == len(config['salt']): log.info('Saving salt') config['salt'] = fixed_json['salt'] else: log.warning('Changing salt, old passwords WON\'T WORK') delete_users = True if 'version' not in fixed_json: log.warning('No config version') raise OldConfigError() elif fixed_json['version'] != config['version']: log.warning('Old config') raise OldConfigError() # print('version' in fixed_json['version']) if 'db' not in fixed_json: log.critical('Wrong config') exiting = True elif 'version' not in fixed_json['db']: log.critical('No DB version') exiting = True elif fixed_json['db']['version'] != config['db']['version']: log.critical('Wrong DB version') exiting = True if not exiting: config = fixed_json except json.decoder.JSONDecodeError: raise OldConfigError() except FileNotFoundError: with open('config.json', 'x') as f: newConfig(f, log) except OldConfigError: with open('config.json', 'w') as f: newConfig(f, log) if exiting: with open('config.json', 'w') as f: newConfig(f, log) log.critical('Please re-setup the DB (cat setup.sql | mysql -uroot -p)') log.critical('Now end this process with ctrl-c') time.sleep(1000000) hasSetUp = True if delete_users: db.getDB().deleteUsers() log.info("Checking for RSA keys") Path("certificates").mkdir(exist_ok=True) try: with open('certificates/private.pem', 'rb') as f: log.info('Loading private key') b = f.read() rsa_priv = rsa.PrivateKey.load_pkcs1(b) # load certs with open('certificates/public.pem', 'rb') as f: log.info('Loading public key') b = f.read() rsa_pub = rsa.PublicKey.load_pkcs1(b) # load certs except FileNotFoundError: # both certs have to be generated at the same time log.info("RSA keys not found. Generating new ones") (pub_pem, priv_pem) = gen_keys() # gen keys automatically saves them to the global vars with open('certificates/private.pem', 'wb') as f: f.write(priv_pem) with open('certificates/public.pem', 'wb') as f: f.write(pub_pem) elapsed = round(time.time()-start_time,2) log.info(f'Setup done in {elapsed}s') logger.remove(log) else: while not hasSetUp: time.sleep(1) return config
from python.db import getDB username = input('Username: '******'UUID: ' + uuid) print('Permission level: ' + str(getDB().getUserPerms(uuid))) new_level = int(input('New permission level: ')) getDB().setUserPerms(uuid, new_level) print('Permission level set')
def update_img(uuid): getDB().setUserImage(uuid, request.form['image']) return redirect('/img')