1919
2020namespace FacturaScripts \Core \Model ;
2121
22+ use FacturaScripts \Core \Base \DataBase \DataBaseWhere ;
2223use FacturaScripts \Core \Tools ;
24+ use FacturaScripts \Dinamic \Model \ApiAccess ;
2325
2426/**
2527 * ApiKey model to manage the connection tokens through the api
@@ -53,6 +55,38 @@ class ApiKey extends Base\ModelClass
5355 /** @var string */
5456 public $ nick ;
5557
58+ /**
59+ * Adds a new API access entry for the given resource with the specified permissions.
60+ *
61+ * If the resource already exists for this API key, no changes are made.
62+ *
63+ * @param string $resource Resource name to grant access to.
64+ * @param bool $state Initial permission state (applied to all methods).
65+ *
66+ * @return bool True if created or already exists, false on failure.
67+ */
68+ public function addResourceAccess (string $ resource , bool $ state = false ): bool
69+ {
70+ if (false !== $ this ->getResourceAccess ($ resource )) {
71+ return true ; // already exists
72+ }
73+
74+ $ apiAccess = new ApiAccess ();
75+
76+ $ apiAccess ->idapikey = $ this ->id ;
77+ $ apiAccess ->resource = $ resource ;
78+ $ apiAccess ->allowdelete = $ state ;
79+ $ apiAccess ->allowget = $ state ;
80+ $ apiAccess ->allowpost = $ state ;
81+ $ apiAccess ->allowput = $ state ;
82+
83+ if (false === $ apiAccess ->save ()) {
84+ return false ;
85+ }
86+
87+ return true ;
88+ }
89+
5690 public function clear ()
5791 {
5892 parent ::clear ();
@@ -62,6 +96,31 @@ public function clear()
6296 $ this ->fullaccess = false ;
6397 }
6498
99+ /**
100+ * Retrieves the API access entry for the specified resource.
101+ *
102+ * Use addResourceAccess() first if the resource does not exist.
103+ *
104+ * @param string $resource Resource name to look up.
105+ *
106+ * @return ApiAccess|bool The ApiAccess object if found, false otherwise.
107+ */
108+ public function getResourceAccess (string $ resource ): ApiAccess |bool
109+ {
110+ $ apiAccess = new ApiAccess ();
111+
112+ $ where = [
113+ new DataBaseWhere ('idapikey ' , $ this ->id ),
114+ new DataBaseWhere ('resource ' , $ resource )
115+ ];
116+
117+ if ($ apiAccess ->loadFromCode ('' , $ where )) {
118+ return $ apiAccess ;
119+ } else {
120+ return false ;
121+ }
122+ }
123+
65124 public static function primaryColumn (): string
66125 {
67126 return 'id ' ;
0 commit comments