def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] blog_db = get_db_client().blogger error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif blog_db.users.find_one({'username': username}) is not None: error = 'User {} already registered .'.format(username) if error is None: blog_db.users.insert_one({ 'username': username, 'password': generate_password_hash(password) }) return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def create(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is None: blog_db = get_db_client().blogger blog_db.articles.insert_one( { 'title': title, 'body': body, 'created_on': datetime.datetime.utcnow(), 'author_id': g.user['_id'], } ) return redirect(url_for('blog.index')) flash(error) return render_template('blog/create.html')
def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: blog_db = get_db_client().blogger g.user = blog_db.users.find_one({'_id': ObjectId(user_id)})
def get_post(post_id): blog_db = get_db_client().blogger post = blog_db.articles.find_one({'_id': ObjectId(post_id)}) if post is None: abort(404, "Post id {0} doesn't exist.".format(post_id)) if post['author_id'] != g.user['_id']: abort(403) return post
def index(): blog_db = get_db_client().blogger pipeline = [ { "$lookup": { "from": "users", "localField": "author_id", "foreignField": "_id", "as": "authors" } } ] posts = blog_db.articles.aggregate(pipeline=pipeline) return render_template('blog/index.html', posts=posts)
def update(post_id): post = get_post(post_id) if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is None: blog_db = get_db_client().blogger blog_db.articles.update_one( {'_id': post['_id']}, [ {'$set': {'title': title, 'body': body, 'lastModified': '$$NOW'}} ] ) return redirect(url_for('blog.index')) flash(error) return render_template('blog/update.html', post=post)
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] blog_db = get_db_client().blogger error = None user = json.loads(dumps(blog_db.users.find_one({'username': username}))) if user is None: error = 'Incorrect user name.' elif not check_password_hash(user.get('password'), password): error = 'Incorrect user password.' if error is None: session.clear() session['user_id'] = user['_id']['$oid'] return redirect(url_for('index')) flash(error) return render_template('auth/login.html')
def delete(post_id): post = get_post(post_id) blog_db = get_db_client().blogger blog_db.articles.delete_one({'_id': post['_id']}) return redirect(url_for('blog.index'))