Project 4: Movie Watchlist: Showing only the logged in user's movies (+25, -1)

routes.py (+25, -1)

From: curriculum/section14/lectures/17_showing_only_user_movies/start/movie_library/routes.py

To: curriculum/section14/lectures/17_showing_only_user_movies/end/movie_library/routes.py

            
            index d615007..90e18df 100644
--- a/curriculum/section14/lectures/17_showing_only_user_movies/start/movie_library/routes.py
+++ b/curriculum/section14/lectures/17_showing_only_user_movies/end/movie_library/routes.py
@@ -1,3 +1,4 @@
+import functools
 import uuid
 import datetime
 from dataclasses import asdict
@@ -22,9 +23,24 @@ pages = Blueprint(
 )
 
 
+def login_required(route):
+    @functools.wraps(route)
+    def route_wrapper(*args, **kwargs):
+        if session.get("email") is None:
+            return redirect(url_for(".login"))
+
+        return route(*args, **kwargs)
+
+    return route_wrapper
+
+
 @pages.route("/")
+@login_required
 def index():
-    movie_data = current_app.db.movie.find({})
+    user_data = current_app.db.user.find_one({"email": session["email"]})
+    user = User(**user_data)
+
+    movie_data = current_app.db.movie.find({"_id": {"$in": user.movies}})
     movies = [Movie(**movie) for movie in movie_data]
 
     return render_template(
@@ -85,6 +101,7 @@ def login():
 
 
 @pages.route("/add", methods=["GET", "POST"])
+@login_required
 def add_movie():
     form = MovieForm()
 
@@ -98,6 +115,10 @@ def add_movie():
 
         current_app.db.movie.insert_one(asdict(movie))
 
+        current_app.db.user.update_one(
+            {"_id": session["user_id"]}, {"$push": {"movies": movie._id}}
+        )
+
         return redirect(url_for(".movie", _id=movie._id))
 
     return render_template(
@@ -112,6 +133,7 @@ def movie(_id: str):
 
 
 @pages.route("/edit/<string:_id>", methods=["GET", "POST"])
+@login_required
 def edit_movie(_id: str):
     movie = Movie(**current_app.db.movie.find_one({"_id": _id}))
     form = ExtendedMovieForm(obj=movie)
@@ -131,6 +153,7 @@ def edit_movie(_id: str):
 
 
 @pages.get("/movie/<string:_id>/watch")
+@login_required
 def watch_today(_id):
     current_app.db.movie.update_one(
         {"_id": _id}, {"$set": {"last_watched": datetime.datetime.today()}}
@@ -140,6 +163,7 @@ def watch_today(_id):
 
 
 @pages.get("/movie/<string:_id>/rate")
+@login_required
 def rate_movie(_id):
     rating = int(request.args.get("rating"))
     current_app.db.movie.update_one({"_id": _id}, {"$set": {"rating": rating}})