xn-auth 0.2.39__py3-none-any.whl → 0.2.41.dev1__py3-none-any.whl

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.
x_auth/controller.py CHANGED
@@ -1,6 +1,7 @@
1
1
  from datetime import timedelta
2
2
 
3
- from aiogram.utils.web_app import WebAppInitData, safe_parse_webapp_init_data
3
+ from aiogram.utils.auth_widget import check_signature
4
+ from aiogram.utils.web_app import WebAppInitData, safe_parse_webapp_init_data, WebAppUser
4
5
  from litestar import Response, post
5
6
  from litestar.connection import ASGIConnection
6
7
  from litestar.exceptions import NotAuthorizedException
@@ -8,7 +9,7 @@ from litestar.security.jwt import JWTCookieAuth
8
9
 
9
10
  from x_auth.middleware import JWTAuthMiddleware, Tok
10
11
  from x_auth.models import User
11
- from x_auth.types import AuthUser
12
+ from x_auth.types import AuthUser, TgUser
12
13
 
13
14
 
14
15
  async def retrieve_user_handler(token: Tok, _cn: ASGIConnection) -> AuthUser:
@@ -33,20 +34,32 @@ class Auth:
33
34
  exclude=["/schema", "/auth", "/public"] + (exc_paths or []),
34
35
  )
35
36
 
36
- @post("/auth/tma", tags=["Auth"], description="Gen JWToken from tg initData")
37
- async def tma(tid: str) -> Response[user_model.in_type(True)]:
38
- try:
39
- twaid: WebAppInitData = safe_parse_webapp_init_data(self.jwt.token_secret, tid)
40
- except ValueError:
41
- raise NotAuthorizedException(detail="Tg Initdata invalid")
42
- user_in = await user_model.tg2in(twaid.user)
37
+ async def user_proc(user: WebAppUser) -> Response[WebAppUser]:
38
+ user_in = await user_model.tg2in(user)
43
39
  db_user, cr = await user_model.update_or_create(**user_in.df_unq()) # on login: update user in db from tg
44
40
  res = self.jwt.login(
45
41
  identifier=str(db_user.id),
46
42
  token_extras={"role": db_user.role, "blocked": db_user.blocked},
47
- response_body=user_model.validate(dict(db_user)),
43
+ response_body=user,
48
44
  )
49
45
  res.cookies[0].httponly = False
50
46
  return res
51
47
 
52
- self.handler = tma
48
+ # login for api endpoint
49
+ @post("/auth/twa", tags=["Auth"], description="Gen JWToken from tg login widget")
50
+ async def twa(data: TgUser) -> Response[WebAppUser]: # widget
51
+ dct = data.dump()
52
+ if not check_signature(self.jwt.token_secret, dct.pop("hash"), **dct):
53
+ raise NotAuthorizedException("Tg login widget data invalid")
54
+ return await user_proc(WebAppUser(**dct))
55
+
56
+ @post("/auth/tma", tags=["Auth"], description="Gen JWToken from tg initData")
57
+ async def tma(tid: str) -> Response[WebAppUser]:
58
+ try:
59
+ twaid: WebAppInitData = safe_parse_webapp_init_data(self.jwt.token_secret, tid)
60
+ except ValueError as e:
61
+ raise NotAuthorizedException(detail=f"Tg Initdata invalid {e}")
62
+ return await user_proc(twaid.user)
63
+
64
+ self.tma_handler = tma
65
+ self.twa_handler = twa
x_auth/models.py CHANGED
@@ -49,6 +49,7 @@ class User(Model):
49
49
  username: OneToOneRelation[Username] = OneToOneField("models.Username", "user")
50
50
  username_id: int
51
51
  first_name: str | None = CharField(63)
52
+ pic: str | None = CharField(127, null=True)
52
53
  last_name: str | None = CharField(31, null=True)
53
54
  blocked: bool = BooleanField(default=False)
54
55
  lang: Lang | None = IntEnumField(Lang, default=Lang.ru, null=True)
@@ -65,6 +66,7 @@ class User(Model):
65
66
  "last_name": u.last_name,
66
67
  "username_id": un.id,
67
68
  "lang": u.language_code and Lang[u.language_code],
69
+ "pic": u.photo_url and u.photo_url.replace("https://t.me/i/userpic/320/", "")[:-4],
68
70
  }
69
71
  )
70
72
  if blocked is not None:
x_auth/types.py CHANGED
@@ -1,11 +1,25 @@
1
1
  from datetime import datetime
2
- from typing import Literal
2
+ from json import dumps
3
+ from typing import Literal, Self
3
4
 
4
- from msgspec import Struct
5
+ from msgspec import Struct, to_builtins, convert
5
6
 
6
7
  from x_auth.enums import Role
7
8
 
8
9
 
10
+ class Xs(Struct):
11
+ def dump(self, nones: bool = False) -> dict:
12
+ return {k: v for k, v in to_builtins(self).items() if nones or v is not None}
13
+
14
+ def json(self, nones: bool = False) -> str:
15
+ return dumps(self.dump())
16
+
17
+ @classmethod
18
+ def load(cls, obj, **kwargs) -> Self:
19
+ dct = dict(obj)
20
+ return convert({**dct, **kwargs}, cls) # , strict=False
21
+
22
+
9
23
  class AuthUser(Struct):
10
24
  id: int
11
25
  blocked: bool
@@ -35,3 +49,13 @@ class Replacement(Struct):
35
49
  proxy_port: int
36
50
  proxy_country_code: str
37
51
  created_at: datetime
52
+
53
+
54
+ class TgUser(Xs):
55
+ id: int
56
+ first_name: str
57
+ auth_date: int
58
+ hash: str
59
+ username: str | None = None
60
+ photo_url: str | None = None
61
+ last_name: str | None = None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xn-auth
3
- Version: 0.2.39
3
+ Version: 0.2.41.dev1
4
4
  Summary: Auth adapter for XN-Api framework
5
5
  Author-email: Artemiev <mixartemev@gmail.com>
6
6
  License: MIT
@@ -0,0 +1,10 @@
1
+ x_auth/controller.py,sha256=aW3iuzkDghxh6TTbPsg9YQcd-F5Yyek_KY2y9hRIKds,2867
2
+ x_auth/enums.py,sha256=l4NTYsA-h0gyOp4PUe40Lb8LKoA94zL6EDkCmoGmBL0,732
3
+ x_auth/exceptions.py,sha256=2B4okJxhPyNqTJXlSTfblJUQJ60bLGXdgJIu6ue7S6w,162
4
+ x_auth/middleware.py,sha256=JfssQomDv0J_69GfS2a_2_uyRzs26zSY6IW1Vk7m8K0,2900
5
+ x_auth/models.py,sha256=m_7ANZMcuxRAW56dgGt86r843Wdib436xV-_e4CBLZ0,8832
6
+ x_auth/types.py,sha256=zojizO58op_BUFvmxSaOtNoPB_liBCY3x3Ff80bgBMo,1310
7
+ xn_auth-0.2.41.dev1.dist-info/METADATA,sha256=GMaEX5wsydNjwcmqvVRF7Qxboc-FUleVni6XpawNyus,828
8
+ xn_auth-0.2.41.dev1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ xn_auth-0.2.41.dev1.dist-info/top_level.txt,sha256=ydMDkzxgQPtW-E_MNDfUAroAFZvWSqU-x_kZSA7NSFo,7
10
+ xn_auth-0.2.41.dev1.dist-info/RECORD,,
@@ -1,10 +0,0 @@
1
- x_auth/controller.py,sha256=0QhqmqXOqFaWIUTWHlJKITQNmJQ5kXZOkLg7wSUTh60,2240
2
- x_auth/enums.py,sha256=l4NTYsA-h0gyOp4PUe40Lb8LKoA94zL6EDkCmoGmBL0,732
3
- x_auth/exceptions.py,sha256=2B4okJxhPyNqTJXlSTfblJUQJ60bLGXdgJIu6ue7S6w,162
4
- x_auth/middleware.py,sha256=JfssQomDv0J_69GfS2a_2_uyRzs26zSY6IW1Vk7m8K0,2900
5
- x_auth/models.py,sha256=Srhu7he0cxEdQ7smQbqlHBE0ChCqAMcj4E_y-WPZlRI,8684
6
- x_auth/types.py,sha256=j3WGcyH24DmFEdTT6U7xzb_fEm1tFcBZsANKMy7bydo,689
7
- xn_auth-0.2.39.dist-info/METADATA,sha256=MPxvb7MeAhnRbKke04ahT5ZlSZKnkvvGToy7qyAVaQM,823
8
- xn_auth-0.2.39.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
- xn_auth-0.2.39.dist-info/top_level.txt,sha256=ydMDkzxgQPtW-E_MNDfUAroAFZvWSqU-x_kZSA7NSFo,7
10
- xn_auth-0.2.39.dist-info/RECORD,,