@@ -14,6 +14,8 @@ public function initialize()
1414
1515 $ this ->loadComponent ('Flash ' ); // Include the FlashComponent
1616 $ this ->loadComponent ('Paginator ' ); // Include the FlashComponent
17+
18+ $ this ->Auth ->allow (['tags ' ]);
1719 }
1820
1921 public function index ()
@@ -33,18 +35,16 @@ public function add()
3335 $ article = $ this ->Articles ->newEntity ();
3436 if ($ this ->request ->is ('post ' )) {
3537 $ article = $ this ->Articles ->patchEntity ($ article , $ this ->request ->getData ());
38+
39+ // Added: Set the user_id from the session.
40+ $ article ->user_id = $ this ->Auth ->user ('id ' );
41+
3642 if ($ this ->Articles ->save ($ article )) {
3743 $ this ->Flash ->success (__ ('Your article has been saved. ' ));
3844 return $ this ->redirect (['action ' => 'index ' ]);
3945 }
4046 $ this ->Flash ->error (__ ('Unable to add your article. ' ));
4147 }
42- // Get a list of tags.
43- $ tags = $ this ->Articles ->Tags ->find ('list ' );
44-
45- // Set tags to the view context
46- $ this ->set ('tags ' , $ tags );
47-
4848 $ this ->set ('article ' , $ article );
4949 }
5050
@@ -54,8 +54,12 @@ public function edit($slug)
5454 ->findBySlug ($ slug )
5555 ->contain ('Tags ' ) // load associated Tags
5656 ->firstOrFail ();
57+
5758 if ($ this ->request ->is (['post ' , 'put ' ])) {
58- $ this ->Articles ->patchEntity ($ article , $ this ->request ->getData ());
59+ $ this ->Articles ->patchEntity ($ article , $ this ->request ->getData (), [
60+ // Added: Disable modification of user_id.
61+ 'accessibleFields ' => ['user_id ' => false ]
62+ ]);
5963 if ($ this ->Articles ->save ($ article )) {
6064 $ this ->Flash ->success (__ ('Your article has been updated. ' ));
6165 return $ this ->redirect (['action ' => 'index ' ]);
@@ -66,9 +70,8 @@ public function edit($slug)
6670 // Get a list of tags.
6771 $ tags = $ this ->Articles ->Tags ->find ('list ' );
6872
69- // Set tags to the view context
73+ // Set article & tags to the view context
7074 $ this ->set ('tags ' , $ tags );
71-
7275 $ this ->set ('article ' , $ article );
7376 }
7477
@@ -100,4 +103,24 @@ public function tags()
100103 'tags ' => $ tags
101104 ]);
102105 }
106+
107+ public function isAuthorized ($ user )
108+ {
109+ $ action = $ this ->request ->getParam ('action ' );
110+ // The add and tags actions are always allowed to logged in users.
111+ if (in_array ($ action , ['add ' , 'tags ' ])) {
112+ return true ;
113+ }
114+
115+ // All other actions require a slug.
116+ $ slug = $ this ->request ->getParam ('pass.0 ' );
117+ if (!$ slug ) {
118+ return false ;
119+ }
120+
121+ // Check that the article belongs to the current user.
122+ $ article = $ this ->Articles ->findBySlug ($ slug )->first ();
123+
124+ return $ article ->user_id === $ user ['id ' ];
125+ }
103126}
0 commit comments