def test_create(client, auth, app): with app.app_context(): db = get_mongoDB() db.posts.drop() auth.login() assert client.get('/create').status_code == 200 client.post('/create', data={ 'title': 'first post', 'body': 'a first posting' }) client.post('/create', data={ 'title': 'second post', 'body': 'second go at it' }) with app.app_context(): db = get_mongoDB() cursor = db.posts.find().sort([("post_id", -1)]).limit(1) count = 0 for item in cursor: count = item["post_id"] assert count == 2
def test_get_close_db(app): with app.app_context(): mongo = get_mongoDB() assert mongo is get_mongoDB() assert str(type(mongo)) == "<class 'pymongo.database.Database'>" with pytest.raises(Exception) as e: close_db() a = mongo.users.find_one({"username": '******'}) assert 'RuntimeError' in str(e)
def login(): """ basic login page """ if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_mongoDB() error = None # search database for the username provided user = db.users.find_one({"username": username}) if user is None: error = 'Incorrect username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: session.clear() # careful with the conversion type!!! # user["_id"] must be converted to serializable JSON type to be stored as session # converting back is tricky unless kept like this! session['user_id'] = str(user["_id"]) user_id = session.get('user_id') foundIt = db.users.find_one({"_id": ObjectId(user["_id"])}) return redirect(url_for('index')) flash(error) return render_template('auth/login.html')
def register(): """ basic registration page """ if request.method == 'POST': username = request.form['username'] password = request.form['password'] error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' # ensure the username is not taken else: db = get_mongoDB() result = db.users.find_one({"username": username}) if result is not None: error = 'User {} is already registered.'.format(username) # if error checks pass, insert 'name' and hashed 'password' into database if error is None: addOne = Users(username=username, password=generate_password_hash(password)) addOne.save() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def create(): """ renders create a new blog post """ if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_mongoDB() result = db.posts.find().sort([("post_id", -1)]).limit(1) max_post = 0 for item in result: max_post = item["post_id"] if(max_post == 0 | max_post is None): max_post == 1 else: max_post += 1 # # # create post data username = db.users.find_one({"_id": ObjectId(str(g.user))})["username"] post = Posts(post_id=max_post, username=username, author_id=ObjectId(g.user), title=title, body=body) post.save() return redirect(url_for('blog.index')) return render_template('blog/create.html')
def test_delete(client, auth, app): auth.login() response = client.post('/2/delete') assert response.headers['Location'] == 'http://localhost/' with app.app_context(): db = get_mongoDB() post = db.posts.find_one({"post_id": 2}) assert post is None
def delete(id): """ gives logged in user option to delete their post """ get_post(id) db = get_mongoDB() # delete existing post db.posts.delete_one({"post_id": id}) return redirect(url_for('blog.index'))
def test_login(client, auth): assert client.get('/auth/login').status_code == 200 response = auth.login() assert response.headers['Location'] == 'http://localhost/' with client: client.get('/') db = get_mongoDB() userId = db.users.find_one({"username": '******'})["_id"] assert g.user == str(userId)
def app(): database_configuration = os.getenv('APP_SETTINGS') app = create_app(test_config=database_configuration) with app.app_context(): from db import db db.init_app(app) from db.db import get_mongoDB mongo = get_mongoDB() yield app
def test_update(client, auth, app): auth.login() assert client.get('/1/update').status_code == 200 client.post('/1/update', data={ 'title': 'updated', 'body': 'changed the body' }) with app.app_context(): db = get_mongoDB() post = db.posts.find_one({"post_id": 1}) assert post['title'] == 'updated'
def get_post(id, check_author=True): """ get posts from the user and check for errors """ db = get_mongoDB() post = db.posts.find_one({"post_id": id}) if post is None: abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and str(post['author_id']) != g.user: abort(403) return post
def index(): """ home page that shows posts with ability to create/edit if logged in """ db = get_mongoDB() # get post data got this user query = db.posts.find() def f(item): item["_id"] = str(item["_id"]) item["author_id"] = str(item["author_id"]) return item posts = [f(item) for item in query] return render_template('blog/index.html', posts=posts)
def load_logged_in_user(): """ verifies from session if any user is logged in """ user_id = session.get('user_id') if user_id is None: g.user = None elif user_id is not None: try: # try to connect to database db = get_mongoDB() userId = db.users.find_one({"_id": ObjectId(str(user_id))})["username"] g.user = user_id # may just have old user id in browser cache, so clear it! if(userId is None): session.clear() except: session.clear()
def test_author_required(app, client, auth): # change the post author to another user with app.app_context(): db = get_mongoDB() adminId = db.users.find_one({"username": '******'})["_id"] user2Id = db.users.find_one({"username": '******'})["_id"] db.posts.update_one({"post_id": 1}, {"$set": { "author_id": str(user2Id) }}) auth.login() # current user can't modify other user's post assert client.post('/1/update').status_code == 403 assert client.post('/1/delete').status_code == 403 # current user doesn't see edit link assert b'href="/1/update"' not in client.get('/').data
def test_register(client, app): with app.app_context(): db = get_mongoDB() assert db.users.find_one({"username": '******'}) is None if (db.users.find_one({"username": '******'}) is not None): db.users.delete_one({"username": '******'}) assert client.get('/auth/register').status_code == 200 response = client.post('/auth/register', data={ 'username': '******', 'password': '******' }) print(vars(response.headers)) assert 'http://localhost/auth/login' == response.headers['Location'] assert db.users.find_one({"username": '******'}) is not None
def update(id): """ gives logged in user option to update their post""" post = get_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 not None: flash(error) else: db = get_mongoDB() # write to existing post db.posts.update_one({"post_id": id}, {"$set": {"body": body, "title": title}}) return redirect(url_for('blog.index')) return render_template('blog/update.html', post=post)