python-jejakmasjid 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/PKG-INFO +1 -1
  2. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/pyproject.toml +1 -1
  3. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/__init__.py +30 -2
  4. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/client.py +133 -1
  5. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/constants.py +9 -1
  6. python_jejakmasjid-0.3.0/src/jejakmasjid/exceptions.py +14 -0
  7. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/PKG-INFO +1 -1
  8. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/SOURCES.txt +1 -0
  9. python_jejakmasjid-0.3.0/tests/test_auth.py +158 -0
  10. python_jejakmasjid-0.2.0/src/jejakmasjid/exceptions.py +0 -6
  11. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/LICENSE +0 -0
  12. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/README.md +0 -0
  13. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/setup.cfg +0 -0
  14. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/__main__.py +0 -0
  15. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/cli.py +0 -0
  16. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/geo.py +0 -0
  17. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/models.py +0 -0
  18. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/dependency_links.txt +0 -0
  19. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/entry_points.txt +0 -0
  20. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/requires.txt +0 -0
  21. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/top_level.txt +0 -0
  22. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/tests/test_cli.py +0 -0
  23. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/tests/test_client.py +0 -0
  24. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/tests/test_geo.py +0 -0
  25. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.0}/tests/test_models.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-jejakmasjid
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Asynchronous Python client for the Jejak Masjid API
5
5
  Author: Zubir Jamal
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-jejakmasjid"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Asynchronous Python client for the Jejak Masjid API"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -1,9 +1,20 @@
1
1
  """Asynchronous Python client for Jejak Masjid."""
2
2
  from __future__ import annotations
3
3
 
4
- from .client import JejakMasjidClient, async_fetch_nearby, parse_places
4
+ from .client import (
5
+ JejakMasjidClient,
6
+ async_fetch_nearby,
7
+ async_fetch_user_profile,
8
+ async_send_email_otp,
9
+ async_verify_email_otp,
10
+ parse_places,
11
+ )
5
12
  from .constants import (
6
13
  API_BASE,
14
+ AUTH_SEND_OTP_PATH,
15
+ AUTH_SEND_OTP_URL,
16
+ AUTH_VERIFY_OTP_PATH,
17
+ AUTH_VERIFY_OTP_URL,
7
18
  DEFAULT_TIMEOUT_SECONDS,
8
19
  DEFAULT_USER_AGENT,
9
20
  FALLBACK_NEARBY_URL,
@@ -14,8 +25,14 @@ from .constants import (
14
25
  NEARBY_URL,
15
26
  PLACE_TYPES,
16
27
  PRIMARY_NEARBY_URL,
28
+ USER_PROFILE_PATH,
29
+ USER_PROFILE_URL,
30
+ )
31
+ from .exceptions import (
32
+ JejakMasjidAuthError,
33
+ JejakMasjidConnectionError,
34
+ JejakMasjidError,
17
35
  )
18
- from .exceptions import JejakMasjidError
19
36
  from .geo import (
20
37
  DIRECTIONS,
21
38
  haversine_km,
@@ -28,13 +45,19 @@ from .models import Place
28
45
 
29
46
  __all__ = [
30
47
  "API_BASE",
48
+ "AUTH_SEND_OTP_PATH",
49
+ "AUTH_SEND_OTP_URL",
50
+ "AUTH_VERIFY_OTP_PATH",
51
+ "AUTH_VERIFY_OTP_URL",
31
52
  "DEFAULT_TIMEOUT_SECONDS",
32
53
  "DEFAULT_USER_AGENT",
33
54
  "DIRECTIONS",
34
55
  "FALLBACK_NEARBY_URL",
35
56
  "HA_V1_NEARBY_PATH",
36
57
  "HEALTH_URL",
58
+ "JejakMasjidAuthError",
37
59
  "JejakMasjidClient",
60
+ "JejakMasjidConnectionError",
38
61
  "JejakMasjidError",
39
62
  "LEGACY_NEARBY_PATH",
40
63
  "NEARBY_PATH",
@@ -42,7 +65,12 @@ __all__ = [
42
65
  "PLACE_TYPES",
43
66
  "PRIMARY_NEARBY_URL",
44
67
  "Place",
68
+ "USER_PROFILE_PATH",
69
+ "USER_PROFILE_URL",
45
70
  "async_fetch_nearby",
71
+ "async_fetch_user_profile",
72
+ "async_send_email_otp",
73
+ "async_verify_email_otp",
46
74
  "haversine_km",
47
75
  "parse_places",
48
76
  "place_type",
@@ -7,12 +7,15 @@ from typing import Any
7
7
  import aiohttp
8
8
 
9
9
  from .constants import (
10
+ AUTH_SEND_OTP_URL,
11
+ AUTH_VERIFY_OTP_URL,
10
12
  DEFAULT_TIMEOUT_SECONDS,
11
13
  DEFAULT_USER_AGENT,
12
14
  FALLBACK_NEARBY_URL,
13
15
  PRIMARY_NEARBY_URL,
16
+ USER_PROFILE_URL,
14
17
  )
15
- from .exceptions import JejakMasjidError
18
+ from .exceptions import JejakMasjidAuthError, JejakMasjidConnectionError, JejakMasjidError
16
19
  from .geo import place_type, project_coordinates, type_from_payload
17
20
 
18
21
  _LOGGER = logging.getLogger(__name__)
@@ -236,3 +239,132 @@ class JejakMasjidClient:
236
239
  user_agent=self._user_agent,
237
240
  headers=headers,
238
241
  )
242
+
243
+ async def send_email_otp(self, email: str) -> dict[str, Any]:
244
+ """Request email OTP verification for user login."""
245
+ return await async_send_email_otp(
246
+ self._session,
247
+ email,
248
+ user_agent=self._user_agent,
249
+ )
250
+
251
+ async def verify_email_otp(self, email: str, otp: str) -> str:
252
+ """Verify emailed OTP and save session token."""
253
+ _data, token = await async_verify_email_otp(
254
+ self._session,
255
+ email,
256
+ otp,
257
+ user_agent=self._user_agent,
258
+ )
259
+ self._api_key = token
260
+ return token
261
+
262
+ async def fetch_user_profile(self, token: str | None = None) -> dict[str, Any]:
263
+ """Fetch user profile and journey statistics."""
264
+ auth_token = token or self._api_key
265
+ if not auth_token:
266
+ raise JejakMasjidAuthError("No authentication token provided or configured")
267
+ return await async_fetch_user_profile(
268
+ self._session,
269
+ auth_token,
270
+ user_agent=self._user_agent,
271
+ )
272
+
273
+
274
+ async def async_send_email_otp(
275
+ session: aiohttp.ClientSession,
276
+ email: str,
277
+ *,
278
+ endpoint_url: str = AUTH_SEND_OTP_URL,
279
+ user_agent: str = DEFAULT_USER_AGENT,
280
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
281
+ ) -> dict[str, Any]:
282
+ """Request an email verification code for user authentication."""
283
+ headers = {"User-Agent": user_agent}
284
+ payload = {"email": email.strip().lower(), "type": "sign-in"}
285
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
286
+
287
+ try:
288
+ async with session.post(endpoint_url, json=payload, headers=headers, timeout=timeout) as resp:
289
+ data = await resp.json(content_type=None) or {}
290
+ if resp.status >= 400:
291
+ raise JejakMasjidAuthError(
292
+ f"Send OTP failed with HTTP {resp.status}: {data.get('message') or data.get('code') or resp.status}"
293
+ )
294
+ return data
295
+ except aiohttp.ClientError as err:
296
+ raise JejakMasjidConnectionError(f"Cannot reach Jejak Masjid auth service: {err}") from err
297
+ except TimeoutError as err:
298
+ raise JejakMasjidConnectionError(f"Timeout reaching Jejak Masjid auth service: {err}") from err
299
+ except ValueError as err:
300
+ raise JejakMasjidError(f"Invalid JSON response from Jejak Masjid: {err}") from err
301
+
302
+
303
+ async def async_verify_email_otp(
304
+ session: aiohttp.ClientSession,
305
+ email: str,
306
+ otp: str,
307
+ *,
308
+ endpoint_url: str = AUTH_VERIFY_OTP_URL,
309
+ user_agent: str = DEFAULT_USER_AGENT,
310
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
311
+ ) -> tuple[dict[str, Any], str]:
312
+ """Exchange emailed OTP for a user session token.
313
+
314
+ Returns tuple of (response_json, token_string).
315
+ """
316
+ headers = {"User-Agent": user_agent}
317
+ payload = {"email": email.strip().lower(), "otp": otp.strip()}
318
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
319
+
320
+ try:
321
+ async with session.post(endpoint_url, json=payload, headers=headers, timeout=timeout) as resp:
322
+ data = await resp.json(content_type=None) or {}
323
+ if resp.status >= 400:
324
+ raise JejakMasjidAuthError(
325
+ f"Invalid OTP or authentication refused (HTTP {resp.status}): {data.get('message') or data.get('code') or resp.status}"
326
+ )
327
+ header_token = resp.headers.get("set-auth-token")
328
+ token = header_token or data.get("token")
329
+ if not token:
330
+ raise JejakMasjidAuthError("No authentication token returned by Jejak Masjid")
331
+ return data, token
332
+ except aiohttp.ClientError as err:
333
+ raise JejakMasjidConnectionError(f"Cannot reach Jejak Masjid auth service: {err}") from err
334
+ except TimeoutError as err:
335
+ raise JejakMasjidConnectionError(f"Timeout reaching Jejak Masjid auth service: {err}") from err
336
+ except ValueError as err:
337
+ raise JejakMasjidError(f"Invalid JSON response from Jejak Masjid: {err}") from err
338
+
339
+
340
+ async def async_fetch_user_profile(
341
+ session: aiohttp.ClientSession,
342
+ token: str,
343
+ *,
344
+ endpoint_url: str = USER_PROFILE_URL,
345
+ user_agent: str = DEFAULT_USER_AGENT,
346
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
347
+ ) -> dict[str, Any]:
348
+ """Fetch user profile, journey statistics, streaks, and achievements."""
349
+ headers = {
350
+ "User-Agent": user_agent,
351
+ "Authorization": f"Bearer {token.strip()}",
352
+ }
353
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
354
+
355
+ try:
356
+ async with session.get(endpoint_url, headers=headers, timeout=timeout) as resp:
357
+ if resp.status == 401:
358
+ raise JejakMasjidAuthError("Jejak Masjid session token expired or revoked (HTTP 401)")
359
+ data = await resp.json(content_type=None) or {}
360
+ if resp.status >= 400:
361
+ raise JejakMasjidError(
362
+ f"Profile request answered HTTP {resp.status}: {data.get('message') or data.get('code') or resp.status}"
363
+ )
364
+ return data
365
+ except aiohttp.ClientError as err:
366
+ raise JejakMasjidConnectionError(f"Cannot reach Jejak Masjid profile service: {err}") from err
367
+ except TimeoutError as err:
368
+ raise JejakMasjidConnectionError(f"Timeout reaching Jejak Masjid profile service: {err}") from err
369
+ except ValueError as err:
370
+ raise JejakMasjidError(f"Invalid JSON response from Jejak Masjid: {err}") from err
@@ -12,6 +12,14 @@ NEARBY_URL = PRIMARY_NEARBY_URL
12
12
  HEALTH_URL = f"{API_BASE}/"
13
13
 
14
14
  DEFAULT_TIMEOUT_SECONDS = 20
15
- DEFAULT_USER_AGENT = "python-jejakmasjid/0.2.0 (+https://github.com/zubirjamal/python-jejakmasjid)"
15
+ DEFAULT_USER_AGENT = "python-jejakmasjid/0.3.0 (+https://github.com/zubirjamal/python-jejakmasjid)"
16
+
17
+ AUTH_SEND_OTP_PATH = "/api/auth/email-otp/send-verification-otp"
18
+ AUTH_VERIFY_OTP_PATH = "/api/auth/sign-in/email-otp"
19
+ USER_PROFILE_PATH = "/api/user/profile"
20
+
21
+ AUTH_SEND_OTP_URL = f"{API_BASE}{AUTH_SEND_OTP_PATH}"
22
+ AUTH_VERIFY_OTP_URL = f"{API_BASE}{AUTH_VERIFY_OTP_PATH}"
23
+ USER_PROFILE_URL = f"{API_BASE}{USER_PROFILE_PATH}"
16
24
 
17
25
  PLACE_TYPES = ["masjid", "surau", "madrasah", "other"]
@@ -0,0 +1,14 @@
1
+ """Exceptions for the Jejak Masjid client library."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class JejakMasjidError(Exception):
6
+ """The API could not be reached or answered with something unexpected."""
7
+
8
+
9
+ class JejakMasjidAuthError(JejakMasjidError):
10
+ """Authentication failed or session token expired/invalid."""
11
+
12
+
13
+ class JejakMasjidConnectionError(JejakMasjidError):
14
+ """Network connection or timeout failure."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-jejakmasjid
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Asynchronous Python client for the Jejak Masjid API
5
5
  Author: Zubir Jamal
6
6
  License: MIT
@@ -15,6 +15,7 @@ src/python_jejakmasjid.egg-info/dependency_links.txt
15
15
  src/python_jejakmasjid.egg-info/entry_points.txt
16
16
  src/python_jejakmasjid.egg-info/requires.txt
17
17
  src/python_jejakmasjid.egg-info/top_level.txt
18
+ tests/test_auth.py
18
19
  tests/test_cli.py
19
20
  tests/test_client.py
20
21
  tests/test_geo.py
@@ -0,0 +1,158 @@
1
+ """Unit tests for Jejak Masjid email OTP authentication and user profile retrieval."""
2
+ from __future__ import annotations
3
+
4
+ from unittest.mock import AsyncMock, MagicMock
5
+
6
+ import aiohttp
7
+ import pytest
8
+
9
+ from jejakmasjid import (
10
+ JejakMasjidAuthError,
11
+ JejakMasjidClient,
12
+ JejakMasjidConnectionError,
13
+ async_fetch_user_profile,
14
+ async_send_email_otp,
15
+ async_verify_email_otp,
16
+ )
17
+
18
+
19
+ @pytest.fixture
20
+ def mock_session():
21
+ """Mock aiohttp.ClientSession."""
22
+ session = MagicMock(spec=aiohttp.ClientSession)
23
+ return session
24
+
25
+
26
+ async def test_send_email_otp_success(mock_session):
27
+ """Test successful email OTP request."""
28
+ mock_resp = MagicMock()
29
+ mock_resp.status = 200
30
+ mock_resp.json = AsyncMock(return_value={"status": "ok", "message": "OTP sent"})
31
+
32
+ mock_session.post.return_value.__aenter__.return_value = mock_resp
33
+
34
+ res = await async_send_email_otp(mock_session, "user@example.com")
35
+ assert res["status"] == "ok"
36
+ mock_session.post.assert_called_once()
37
+ _call_args, call_kwargs = mock_session.post.call_args
38
+ assert call_kwargs["json"] == {"email": "user@example.com", "type": "sign-in"}
39
+
40
+
41
+ async def test_send_email_otp_failure(mock_session):
42
+ """Test OTP request refusal raises JejakMasjidAuthError."""
43
+ mock_resp = MagicMock()
44
+ mock_resp.status = 400
45
+ mock_resp.json = AsyncMock(return_value={"code": "INVALID_EMAIL", "message": "Email rejected"})
46
+
47
+ mock_session.post.return_value.__aenter__.return_value = mock_resp
48
+
49
+ with pytest.raises(JejakMasjidAuthError, match="Send OTP failed"):
50
+ await async_send_email_otp(mock_session, "invalid-email")
51
+
52
+
53
+ async def test_verify_email_otp_header_token(mock_session):
54
+ """Test verifying OTP when token is returned in response header."""
55
+ mock_resp = MagicMock()
56
+ mock_resp.status = 200
57
+ mock_resp.headers = {"set-auth-token": "jwt-token-from-header"}
58
+ mock_resp.json = AsyncMock(return_value={"user": {"id": "123"}})
59
+
60
+ mock_session.post.return_value.__aenter__.return_value = mock_resp
61
+
62
+ data, token = await async_verify_email_otp(mock_session, "user@example.com", "123456")
63
+ assert token == "jwt-token-from-header"
64
+ assert data["user"]["id"] == "123"
65
+
66
+
67
+ async def test_verify_email_otp_body_token(mock_session):
68
+ """Test verifying OTP when token is returned in JSON body."""
69
+ mock_resp = MagicMock()
70
+ mock_resp.status = 200
71
+ mock_resp.headers = {}
72
+ mock_resp.json = AsyncMock(return_value={"token": "jwt-token-from-body"})
73
+
74
+ mock_session.post.return_value.__aenter__.return_value = mock_resp
75
+
76
+ _data, token = await async_verify_email_otp(mock_session, "user@example.com", "123456")
77
+ assert token == "jwt-token-from-body"
78
+
79
+
80
+ async def test_verify_email_otp_invalid(mock_session):
81
+ """Test invalid OTP raises JejakMasjidAuthError."""
82
+ mock_resp = MagicMock()
83
+ mock_resp.status = 400
84
+ mock_resp.json = AsyncMock(return_value={"code": "INVALID_OTP"})
85
+
86
+ mock_session.post.return_value.__aenter__.return_value = mock_resp
87
+
88
+ with pytest.raises(JejakMasjidAuthError, match="Invalid OTP"):
89
+ await async_verify_email_otp(mock_session, "user@example.com", "wrong")
90
+
91
+
92
+ async def test_fetch_user_profile_success(mock_session):
93
+ """Test fetching user profile with valid Bearer token."""
94
+ mock_resp = MagicMock()
95
+ mock_resp.status = 200
96
+ profile_data = {
97
+ "profile": {
98
+ "totalCheckIns": 12,
99
+ "uniqueMasjidsVisited": 8,
100
+ "currentStreak": 5,
101
+ "totalPoints": 420,
102
+ },
103
+ "rank": {"globalRank": 150},
104
+ }
105
+ mock_resp.json = AsyncMock(return_value=profile_data)
106
+
107
+ mock_session.get.return_value.__aenter__.return_value = mock_resp
108
+
109
+ res = await async_fetch_user_profile(mock_session, "valid-token")
110
+ assert res["profile"]["totalCheckIns"] == 12
111
+ assert res["rank"]["globalRank"] == 150
112
+
113
+ _call_args, call_kwargs = mock_session.get.call_args
114
+ assert call_kwargs["headers"]["Authorization"] == "Bearer valid-token"
115
+
116
+
117
+ async def test_fetch_user_profile_unauthorized(mock_session):
118
+ """Test expired token (401) raises JejakMasjidAuthError."""
119
+ mock_resp = MagicMock()
120
+ mock_resp.status = 401
121
+ mock_resp.json = AsyncMock(return_value={"error": "Unauthorized"})
122
+
123
+ mock_session.get.return_value.__aenter__.return_value = mock_resp
124
+
125
+ with pytest.raises(JejakMasjidAuthError, match="token expired"):
126
+ await async_fetch_user_profile(mock_session, "expired-token")
127
+
128
+
129
+ async def test_client_class_auth_flow(mock_session):
130
+ """Test high-level JejakMasjidClient auth methods."""
131
+ client = JejakMasjidClient(mock_session)
132
+
133
+ # 1. Send OTP
134
+ mock_post_resp = MagicMock()
135
+ mock_post_resp.status = 200
136
+ mock_post_resp.json = AsyncMock(return_value={"status": "ok"})
137
+ mock_session.post.return_value.__aenter__.return_value = mock_post_resp
138
+
139
+ await client.send_email_otp("user@example.com")
140
+
141
+ # 2. Verify OTP
142
+ mock_verify_resp = MagicMock()
143
+ mock_verify_resp.status = 200
144
+ mock_verify_resp.headers = {}
145
+ mock_verify_resp.json = AsyncMock(return_value={"token": "client-saved-token"})
146
+ mock_session.post.return_value.__aenter__.return_value = mock_verify_resp
147
+
148
+ token = await client.verify_email_otp("user@example.com", "999999")
149
+ assert token == "client-saved-token"
150
+
151
+ # 3. Fetch profile with automatically saved token
152
+ mock_get_resp = MagicMock()
153
+ mock_get_resp.status = 200
154
+ mock_get_resp.json = AsyncMock(return_value={"profile": {"totalPoints": 999}})
155
+ mock_session.get.return_value.__aenter__.return_value = mock_get_resp
156
+
157
+ profile = await client.fetch_user_profile()
158
+ assert profile["profile"]["totalPoints"] == 999
@@ -1,6 +0,0 @@
1
- """Exceptions for the Jejak Masjid client library."""
2
- from __future__ import annotations
3
-
4
-
5
- class JejakMasjidError(Exception):
6
- """The API could not be reached or answered with something unexpected."""