Line data Source code
1 4 : (ns matchscore.api.auth-telegram
2 : "HTTP handlers for the Telegram Login OIDC flow (website auth)."
3 : (:require
4 : [cats.core :as cats.core]
5 : [cats.monad.either :as either]
6 : [clojure.string :as str]
7 : [matchscore.domain.session.repository.redis :as session-repo]
8 : [matchscore.domain.user.query :as user-query]
9 : [matchscore.domain.user.repository.postgres :as user-postgres-repo]
10 : [matchscore.utils.telegram-oidc :as telegram-oidc]
11 : [ring.util.http-status :as status]
12 : [schemas.api.core :as api-schemas]
13 : [taoensso.carmine :as car]
14 : [taoensso.telemere :as t]
15 : [telegrambot-lib.core :as tbot]))
16 :
17 :
18 4 : (defn- session-cookie-attrs
19 : [config max-age]
20 7 : (let [{:keys [cookie-name secure? same-site domain]} (get-in config [:auth :session])]
21 9 : {:cookie-name (or cookie-name "ms_session")
22 10 : :attrs (cond->
23 7 : {:path "/"
24 : :http-only true
25 1 : :max-age max-age
26 8 : :same-site (keyword (or same-site "lax"))}
27 4 : secure? (assoc :secure true)
28 5 : (not-empty domain) (assoc :domain domain))}))
29 :
30 :
31 4 : (defn- set-session-cookie
32 : [response config session-id]
33 9 : (let [ttl-seconds (get-in config [:auth :session :ttl-seconds] 2592000)
34 4 : {:keys [cookie-name attrs]} (session-cookie-attrs config ttl-seconds)]
35 11 : (assoc-in response [:cookies cookie-name] (assoc attrs :value session-id))))
36 :
37 :
38 4 : (defn- clear-session-cookie
39 : [response config]
40 5 : (let [{:keys [cookie-name attrs]} (session-cookie-attrs config 0)]
41 11 : (assoc-in response [:cookies cookie-name] (assoc attrs :value ""))))
42 :
43 :
44 4 : (defn- default-username
45 : [name]
46 12 : (when-not (str/blank? name) (str/replace (str/lower-case name) #"\s+" "_")))
47 :
48 :
49 4 : (defn- telegram-id-from-claims
50 : [claims]
51 11 : (let [raw-id (or (:id claims) (:sub claims))]
52 7 : (cond (integer? raw-id) raw-id
53 6 : (string? raw-id) (Long/parseLong raw-id)
54 5 : :else (throw (ex-info "Telegram ID missing from OIDC claims" {})))))
55 :
56 :
57 4 : (defn- oidc-claims->user-data
58 : [claims requested-bot-access?]
59 4 : (let [telegram-id (telegram-id-from-claims claims)
60 9 : display-name (or
61 5 : (not-empty (:name claims))
62 5 : (not-empty (:preferred_username claims))
63 2 : (str "Telegram user " telegram-id))]
64 8 : {:telegram-id telegram-id
65 1 : :name display-name
66 5 : :username (not-empty (:preferred_username claims))
67 3 : :photo-url (:picture claims)
68 4 : :telegram-bot-access-status (if requested-bot-access? "assumed" "unknown")
69 5 : :telegram-bot-access-updated-at (when requested-bot-access? (java.time.OffsetDateTime/now))}))
70 :
71 :
72 4 : (defn- find-existing-user
73 : [{:keys [repos]} telegram-id]
74 4 : (let [user-pg-repo (:user-postgres-repo repos)
75 3 : user-redis (:user-redis-repo repos)
76 5 : existing-uuid (user-query/find-uuid-by-telegram-id user-pg-repo user-redis telegram-id)]
77 7 : (when existing-uuid (user-postgres-repo/find-by-id user-pg-repo existing-uuid))))
78 :
79 :
80 5 : (defn- bot-access-check-message [] "Welcome to MatchScore!")
81 :
82 :
83 4 : (defn- mark-bot-access!
84 : [{:keys [repos]} user status]
85 6 : (let [updated (assoc user
86 1 : :telegram-bot-access-status status
87 2 : :telegram-bot-access-updated-at (java.time.OffsetDateTime/now))
88 6 : result (user-postgres-repo/save! (:user-postgres-repo repos) updated)]
89 4 : (if (either/right? result)
90 3 : (cats.core/extract result)
91 0 : (do
92 0 : (t/log!
93 : :warn
94 0 : {:message "Failed to persist Telegram bot access status"
95 0 : :status status
96 0 : :error (cats.core/extract result)})
97 0 : user))))
98 :
99 :
100 4 : (defn- claim-bot-access-check!
101 : "Atomically claims the right to send the bot access message for this user.
102 : Returns true if this instance should proceed, false if another pod beat it."
103 : [redis telegram-id]
104 0 : (let [lock-key (str "bot:welcome-lock:" telegram-id)
105 0 : result (car/wcar redis (car/set lock-key "1" :nx :ex 60))]
106 0 : (= "OK" result)))
107 :
108 :
109 4 : (defn- confirm-bot-access!
110 : "Verifies Telegram bot DM access by sending a one-time direct message.
111 : Login should not fail if this check cannot run or if Telegram rejects the DM."
112 : [{:keys [bot redis]
113 : :as request}
114 : user
115 : requested-bot-access?]
116 1 : (if
117 14 : (and
118 1 : requested-bot-access?
119 1 : bot
120 3 : (:telegram-id user)
121 6 : (not= "confirmed" (:telegram-bot-access-status user))
122 5 : (claim-bot-access-check! redis (:telegram-id user)))
123 1 : (try
124 3 : (let [response (tbot/send-message
125 1 : bot
126 6 : {:chat_id (:telegram-id user)
127 2 : :text (bot-access-check-message)})]
128 6 : (if (false? (:ok response))
129 0 : (do
130 0 : (t/log!
131 : :info
132 0 : {:message "Telegram bot access denied"
133 0 : :telegram-id (:telegram-id user)
134 0 : :response response})
135 0 : (mark-bot-access! request user "denied"))
136 5 : (mark-bot-access! request user "confirmed")))
137 : (catch Exception e
138 92 : (t/log!
139 : :info
140 5 : {:message "Telegram bot access check failed"
141 3 : :telegram-id (:telegram-id user)
142 1 : :exception e})
143 5 : (mark-bot-access! request user "denied")))
144 1 : user))
145 :
146 :
147 4 : (defn- validation-error-reason
148 : [e]
149 7 : (or (not-empty (.getMessage e)) "Telegram token validation failed"))
150 :
151 :
152 4 : (defn telegram-login-handler
153 : {:malli/schema [:=>
154 : [:cat api-schemas/RingRequest api-schemas/TelegramLoginRequestSchema]
155 : api-schemas/TelegramLoginResponseSchema]
156 : :authz {:public? true}
157 : :summary "Login with Telegram Login OIDC"
158 : :description
159 : "Verifies a Telegram Login OIDC ID token, finds or creates the user,
160 : creates a Redis-backed session, and sets an HttpOnly session cookie."}
161 : [{:keys [config ctx repos]
162 : :as request}
163 : login-data]
164 7 : (let [client-id (get-in config [:telegram :client-id])
165 3 : session-repo* (:session-redis-repo repos)
166 8 : ttl-seconds (get-in config [:auth :session :ttl-seconds] 2592000)]
167 4 : (if (str/blank? client-id)
168 4 : {:status status/bad-request
169 3 : :body {:message "Missing Telegram client id in backend config"}}
170 6 : (if (str/blank? (:id-token login-data))
171 4 : {:status status/bad-request
172 3 : :body {:message "Missing Telegram id token"}}
173 1 : (let [validation-result
174 1 : (try
175 7 : (let [claims (telegram-oidc/verify-id-token (:id-token login-data) client-id)]
176 8 : {:user-data (oidc-claims->user-data claims (:requested-bot-access login-data))})
177 : (catch Exception e
178 4 : (let [reason (validation-error-reason e)]
179 96 : (t/log! :info (str "Telegram Login OIDC: invalid id_token: " reason))
180 6 : {:response {:status status/unauthorized
181 4 : :body {:message "Invalid Telegram login token"
182 1 : :reason reason}}})))]
183 8 : (if-let [response (:response validation-result)]
184 1 : response
185 4 : (let [user-data (:user-data validation-result)
186 3 : telegram-id (:telegram-id user-data)
187 4 : existing (find-existing-user ctx telegram-id)]
188 2 : (if existing
189 : ;; Returning user — no profile update, just confirm bot access + session
190 3 : (let [user (confirm-bot-access!
191 1 : request
192 1 : existing
193 3 : (:requested-bot-access login-data))
194 2 : session-id (session-repo/create!
195 1 : session-repo*
196 3 : (:uuid user)
197 3 : (:telegram-id user)
198 1 : ttl-seconds)]
199 1 : (->
200 4 : {:status status/ok
201 6 : :body {:message "Login successful"
202 1 : :data user
203 : :is-new-user false}}
204 3 : (set-session-cookie config session-id)))
205 : ;; New user — pending session (nil UUID), return Telegram data as suggestions
206 1 : (let [username-suggestion
207 14 : (or (not-empty (:username user-data)) (default-username (:name user-data)))
208 6 : session-id (session-repo/create! session-repo* nil telegram-id ttl-seconds)]
209 1 : (->
210 4 : {:status status/ok
211 6 : :body {:message "Login successful"
212 : :is-new-user true
213 7 : :data {:name (:name user-data)
214 1 : :username username-suggestion
215 3 : :photo-url (:photo-url user-data)}}}
216 3 : (set-session-cookie config session-id)))))))))))
217 :
218 :
219 4 : (defn telegram-logout-handler
220 : {:malli/schema [:=> [:cat api-schemas/RingRequest] api-schemas/TelegramLogoutResponseSchema]
221 : :authz {:public? true}
222 : :summary "Logout (clear Telegram session cookie)"
223 : :description "Deletes the server-side session entry in Redis and expires the cookie."}
224 : [{:keys [config cookies repos]
225 : :as _request}]
226 9 : (let [cookie-name (get-in config [:auth :session :cookie-name] "ms_session")
227 6 : session-id (get-in cookies [cookie-name :value])
228 3 : session-repo* (:session-redis-repo repos)]
229 7 : (when session-id (session-repo/delete! session-repo* session-id))
230 1 : (->
231 5 : {:status status/no-content
232 : :body nil}
233 2 : (clear-session-cookie config))))
|