Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refresh token #7

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
CREATE TABLE IF NOT EXISTS tokens_new (
id INTEGER PRIMARY KEY,
cif TEXT NOT NULL UNIQUE,
access_token TEXT,
refresh_token TEXT,
expires_in TEXT,
expiration_date TEXT,
_updated TEXT,
FOREIGN KEY (cif) REFERENCES company(cif)
) STRICT;
--;;
INSERT INTO tokens_new (id, cif, access_token, refresh_token, expires_in, expiration_date, _updated)
SELECT id, cif, access_token, refresh_token, expires_in, expiration_date, _updated FROM tokens;
--;;
alter table tokens rename to tokens_backup;
--;;
alter table tokens_new rename to tokens;
--;;
drop table tokens_backup;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
alter table tokens add column retries_count INTEGER DEFAULT 0;
21 changes: 21 additions & 0 deletions src/efactura_mea/db/db_ops.clj
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,20 @@
(let [offset-num (* (dec page) per-page)]
(f/select-apeluri-api-anaf db {:cif cif :limit per-page :offset offset-num})))

(defn fetch-company-refresh-token [db cif]
(:refresh_token (first (f/select-company-token-data db {:cif cif}))))

(defn fetch-company-token-data [db cif]
(first (f/select-company-token-data db {:cif cif})))

(defn fetch-mesaje [db cif page per-page]
(let [offset-num (* (dec page) per-page)]
(f/select-facturi-descarcate db {:cif cif :limit per-page :offset offset-num})))

(defn update-retries-counter!
[ds cif retries_count]
(f/update-token-retries-counter ds {:cif cif :retries_count retries_count}))

(defn count-lista-mesaje
[db cif]
(let [qr (first (f/count-lista-mesaje-descarcate db {:cif cif}))]
Expand Down Expand Up @@ -152,6 +162,17 @@
total-facturi-in-date-range (:total select-total)]
total-facturi-in-date-range))

(defn save-refreshed-token-data!
[ds opts]
(let [{:keys [cif access_token refresh_token expiration_date expires_in _updated]} opts]
(f/refresh-token-data-update
ds {:cif cif
:access_token access_token
:refresh_token refresh_token
:expiration_date expiration_date
:expires_in expires_in
:_updated _updated})))

(comment

(require '[efactura-mea.db.ds :refer [ds]])
Expand Down
23 changes: 22 additions & 1 deletion src/efactura_mea/db/facturi.sql
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@ where company.cif = :cif;
-- :result :raw
select access_token from tokens where cif = :cif

-- :name select-company-token-data
-- :command :execute
-- :result :raw
select * from tokens where cif = :cif

-- :name select-acc-token-exp-date :? :1
-- :command :execute
-- :result :raw
Expand Down Expand Up @@ -202,4 +207,20 @@ WHERE cif = :cif AND data_emitere >= :start-date AND data_emitere <= :end-date |
-- :result :raw
SELECT count(*) as total
FROM detalii_facturi_anaf
WHERE cif = :cif AND data_emitere >= :start-date AND data_emitere <= :end-date || '2359';
WHERE cif = :cif AND data_emitere >= :start-date AND data_emitere <= :end-date || '2359';

-- :name refresh-token-data-update
-- :command :execute
UPDATE tokens
SET access_token = :access_token,
refresh_token = :refresh_token,
expiration_date = :expiration_date,
expires_in = :expires_in,
_updated = :_updated
WHERE cif = :cif;

-- :name update-token-retries-counter
-- :command :execute
UPDATE tokens
SET retries_count = :retries_count
WHERE cif = :cif;
42 changes: 30 additions & 12 deletions src/efactura_mea/util.clj
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@
[java-time.api :as jt])
(:import
(java.util.zip ZipFile)
(java.time.format DateTimeFormatter)))
(java.time.format DateTimeFormatter)
(java.time Duration)))

(defn back-to-string-formatter
[date]
(let [formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd")]
(.format date formatter)))

(defn format-utc-date
[utc-date]
(try
(let [formatter "yyyy-MM-dd HH:mm:ss"
zoned-time (jt/zoned-date-time utc-date)]
(jt/format formatter zoned-time))
(catch Exception _ "invalid utc date format")))

(defn file-in-dir? [dir file-name]
(let [dir-file (io/file dir)]
(some #(= (.getName %) file-name) (file-seq dir-file))))
Expand All @@ -33,10 +42,19 @@
[inst-now]
(jt/format :iso-date-time inst-now))

(defn expiration-date
(defn expiration-date
[zdate secs]
(jt/plus zdate (jt/seconds secs)))

(defn seconds->days
[seconds]
(try
(let [s (case seconds "" 0 (parse-long seconds))
duration (Duration/ofSeconds s)]
(.toDays duration))
(catch Exception _ "Failed converting token expiry period")))

(type 7776000)
^:rct/test
(comment

Expand All @@ -47,7 +65,6 @@
(date-time->iso-str
(expiration-date (jt/zoned-date-time 2024 01 01 10) 3600))
;;=> "2024-01-01T11:00:00+02:00[Europe/Bucharest]"

)

(defn date-now
Expand Down Expand Up @@ -148,12 +165,13 @@
(throw (Exception. (str "File " file-name-inside-zip " not found in " zip-file-path)))))))

#_(defn extract-query-params [url]
(try (let [uri (java.net.URI. url)
query (.getQuery uri)
params (when query
(->> (s/split query #"&")
(map #(s/split % #"="))
(map (fn [[k v]] [(keyword k) (Integer/parseInt v)]))
(into {})))]
params)
(catch Exception _ {:page nil :per-page nil})))
(try (let [uri (java.net.URI. url)
query (.getQuery uri)
params (when query
(->> (s/split query #"&")
(map #(s/split % #"="))
(map (fn [[k v]] [(keyword k) (Integer/parseInt v)]))
(into {})))]
params)
(catch Exception _ {:page nil :per-page nil})))

113 changes: 105 additions & 8 deletions src/efactura_mea/web/anaf_integrare.clj
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,22 @@
"
(:require
[clojure.tools.logging :as log]
[babashka.http-client :as http]
[efactura-mea.db.facturi :as fdb]
[efactura-mea.db.db-ops :as db-ops]
[efactura-mea.util :as u]
[efactura-mea.web.json :as wj]
[jsonista.core :as json]
[efactura-mea.web.layout :as layout]
[efactura-mea.web.anaf.oauth2 :as o2a]
[efactura-mea.web.ui.componente :as ui]
[hiccup2.core :as h]
[muuntaja.core :as m]
[reitit.core :as r]
[ring.util.response :as rur]))
[ring.util.response :as rur]
[java-time.api :as jt])
(:import
[java.time.temporal ChronoUnit]))

;; todo:
;; - funcționalitate de revocare a tokenului - în caz de compromitere
Expand Down Expand Up @@ -133,6 +139,92 @@
(log/info e (str "Exception" (ex-cause e)))
(throw e))))))


(defn save-refreshed-token
[ds opts]
(println "incep cu functia SAVE_REFRESHED_TOKEN")
(let [{:keys [body cif]} opts
b (json/read-value body)
access-token (get b "access_token")
refresh-token (get b "refresh_token")
expires-in (get b "expires_in")
now (u/date-time-now-utc)
expiration-date (u/expiration-date now expires-in)
save-opts {:cif cif
:access_token access-token
:refresh_token refresh-token
:expiration_date expiration-date
:expires_in expires-in
:_updated now}
_ (db-ops/save-refreshed-token-data! ds save-opts)]
{:status 200
:body "Token refreshed"
:headers {"content-type" "text/html"}}))


(defn handler-refresh-token
[client-id client-secret]
(fn [req]
(let [{:keys [path-params ds uri]} req
{:keys [cif]} path-params
token-data (db-ops/fetch-company-token-data ds cif)
{:keys [refresh_token retries_count]} token-data
refresh-token-anaf-uri "https://logincert.anaf.ro/anaf-oauth2/v1/token"
opts {:basic-auth [client-id client-secret]
:form-params {:grant_type "refresh_token"
:refresh_token refresh_token}}]
(try
(loop [retries retries_count]
(if (<= retries 5)
(let [response (http/post refresh-token-anaf-uri opts)
{:keys [status body]} response
opts {:body body :cif cif :uri uri}]
(if (= 200 status)
(do
(log/info "Refresh token reușit!")
(db-ops/update-retries-counter! ds cif 0)
(log/info "test dupa db action :"))
(do
(log/info "Eroare obtinere refresh-token, încerc din nou...")
(db-ops/update-retries-counter! ds cif retries)
(recur (inc retries)))))
(log/info "Am atins limita maximă de încercări!")))
(catch Exception e
(log/info e (str "Exception" (ex-cause e)))
(throw e)))
{:status 200
:body "refreshed token"
:headers {"Content-type" "text/html"}})))



(defn handler-revoke!-token
[client-id client-secret]
(fn [req]
(let [{:keys [path-params ds]} req
{:keys [cif]} path-params
revoke-token (db-ops/fetch-company-refresh-token ds cif)
revoke-token-anaf-uri "https://logincert.anaf.ro/anaf-oauth2/v1/revoke"
opts {:basic-auth [client-id client-secret]
:form-params {:token revoke-token}}]
(try
(let [response (http/post revoke-token-anaf-uri opts)
{:keys [status]} response]
(if (= 200 status)
;; TODO: de implementat mesaj de informare
(log/info "Tokenul a fost revocat cu succes!")
(throw (ex-info "Failed to refresh token" {:status status
:response response}))))
(catch Exception e
(log/info e (str "Exception" (ex-cause e)))
(throw e))))))

(defn days-until-expiration [expiration-str]
(let [now (jt/local-date-time)
expiration (jt/zoned-date-time expiration-str)
days-difference (.between ChronoUnit/DAYS now expiration)]
days-difference))

(defn routes
[anaf-conf]
[["/login-anaf" (o2a/make-anaf-login-handler
Expand All @@ -141,20 +233,25 @@
["/integrare/:cif" {:name ::integrare
:get page-anaf-integrare}]
["/autorizeaza-acces/:cif" {:name ::autorizare
:get handler-autorizare}]])
:get handler-autorizare}]
["/refresh-access-token/:cif" (handler-refresh-token
(anaf-conf :client-id)
(anaf-conf :client-secret))]
["/revoke-token/:cif" (handler-revoke!-token
(anaf-conf :client-id)
(anaf-conf :client-secret))]])


(comment
(->
(comment

(->
(r/router (routes {}))
(r/match-by-name ::integrare {:cif "1234"})
(r/match-by-name ::integrare {:cif "1234"})
:path)
;;=> "/integrare/1234"

(-> (r/router (routes {}))
(r/match-by-name ::autorizare {:cif "123"})
:path)
:path)
;;=> "/autorizeaza-acces/123"

)
35 changes: 28 additions & 7 deletions src/efactura_mea/web/companii/profil.clj
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
(ns efactura-mea.web.companii.profil
(:require
[efactura-mea.web.ui.componente :as ui :refer [title details-table]]
[efactura-mea.db.db-ops :as db :refer [get-company-data]]
[efactura-mea.db.facturi :as facturi :refer [select-acc-token-exp-date]]
[hiccup2.core :as h]))
[efactura-mea.util :as u]
[efactura-mea.db.db-ops :as db
:refer [get-company-data fetch-company-token-data]]
[hiccup2.core :as h]
[java-time.api :as jt]))

(defn afisare-profil-companie
[req]
(let [{:keys [path-params ds]} req
{:keys [cif]} path-params
company (get-company-data ds cif)
token-expiration-date (select-acc-token-exp-date ds {:cif cif})
company (get-company-data ds cif)
token-data (fetch-company-token-data ds cif)
{:keys [expiration_date _updated expires_in]} token-data
milliseconds->days (u/seconds->days expires_in)
valability (or (str milliseconds->days " zile") "")
parse-exp-date (u/format-utc-date expiration_date)
parsed-token-updated-at (u/format-utc-date _updated)

{:keys [name website address desc_aut_status date_modified]} company
descarcare-automata-status (h/html [:span.has-text-weight-bold.is-uppercase desc_aut_status] " - " [:span.is-size-6 date_modified])
descarcare-automata-url (str "/descarcare-automata/" cif)
descarcare-automata-link [:a {:href descarcare-automata-url} [:span.icon [:i.fa.fa-pencil-square]]]]
descarcare-automata-link [:a {:href descarcare-automata-url} [:span.icon [:i.fa.fa-pencil-square]]]
refresh-token-anaf-uri (str "/anaf/refresh-access-token/" cif)
refresh-btn [:button.button.is-small.is-info
{:hx-get refresh-token-anaf-uri
:hx-swap "none"}
"Refresh token"]]
(h/html
(title "Pagina de profil a companiei")
[:div.columns.is-vcentered
Expand All @@ -27,4 +40,12 @@
[:a {:href website} website]]]]
[:div.columns
[:div.column
(details-table {"Companie:" name "CIF:" cif "Website:" website "Adresă:" address "Dată expirare access_token: " token-expiration-date "Descărcare automată:" [:div#das descarcare-automata-link descarcare-automata-status]})]])))
(details-table
{"Companie:" name "CIF:" cif "Website:" website "Adresă:" address "Descărcare automată:" [:div#das descarcare-automata-link descarcare-automata-status]})]
[:div#token-card.column
(details-table
{"Token" "" "Dată expirare: " [:div parse-exp-date [:div refresh-btn]] "Reînnoit la:" parsed-token-updated-at "Valabilitate: " valability})]])))

(comment
(jt/format (jt/zoned-date-time "2025-01-14T16:24:20.369794436Z[UTC]"))
0)
2 changes: 1 addition & 1 deletion src/efactura_mea/web/ui/componente.clj
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@
[details-map]
(h/html
[:div.column
[:table.table
[:table.table.is-fullwidth
[:tbody
(for [[k v] details-map]
[:tr
Expand Down