sso-nebus 0.1.1__tar.gz → 0.1.3__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sso-nebus
3
- Version: 0.1.1
3
+ Version: 0.1.3
4
4
  Summary: Python клиент для взаимодействия с MS Auth Service API
5
5
  License: LICENSE
6
6
  License-File: LICENSE
@@ -168,6 +168,54 @@ async def main():
168
168
  asyncio.run(main())
169
169
  ```
170
170
 
171
+ Пример для получения информации по пользвателю для подстановки в Depends
172
+ ```
173
+ from fastapi import FastAPI, Header, HTTPException
174
+ from typing import Optional
175
+
176
+ app = FastAPI()
177
+
178
+ sso_client = ServiceClient(
179
+ base_url="http://localhost:8000",
180
+ client_id="your_service_id",
181
+ client_secret="your_service_secret"
182
+ )
183
+
184
+ async def get_current_user(authorization: Optional[str] = Header(None)):
185
+ """
186
+ Dependency для получения текущего пользователя из токена
187
+ """
188
+ if not authorization:
189
+ raise HTTPException(status_code=401, detail="Токен не предоставлен")
190
+
191
+ # Извлекаем токен из заголовка "Bearer <token>"
192
+ try:
193
+ token = authorization.split(" ")[1]
194
+ except IndexError:
195
+ raise HTTPException(status_code=401, detail="Неверный формат токена")
196
+
197
+ try:
198
+ user_info = await sso_client.get_current_user(access_token=token)
199
+ return user_info
200
+ except AuthenticationError:
201
+ raise HTTPException(status_code=401, detail="Невалидный токен")
202
+ except Exception as e:
203
+ raise HTTPException(status_code=500, detail=f"Ошибка при проверке токена: {e}")
204
+
205
+ @app.get("/protected")
206
+ async def protected_endpoint(current_user = Depends(get_current_user)):
207
+ """
208
+ Защищенный endpoint, который требует валидный токен пользователя
209
+ """
210
+ return {
211
+ "message": f"Привет, {current_user.name} {current_user.surname}!",
212
+ "user_id": current_user.id,
213
+ "email": current_user.email,
214
+ "scopes": current_user.scopes
215
+ }
216
+
217
+ ```
218
+
171
219
  ## API Reference
172
220
 
173
221
  ### UserClient
@@ -150,6 +150,54 @@ async def main():
150
150
  asyncio.run(main())
151
151
  ```
152
152
 
153
+ Пример для получения информации по пользвателю для подстановки в Depends
154
+ ```
155
+ from fastapi import FastAPI, Header, HTTPException
156
+ from typing import Optional
157
+
158
+ app = FastAPI()
159
+
160
+ sso_client = ServiceClient(
161
+ base_url="http://localhost:8000",
162
+ client_id="your_service_id",
163
+ client_secret="your_service_secret"
164
+ )
165
+
166
+ async def get_current_user(authorization: Optional[str] = Header(None)):
167
+ """
168
+ Dependency для получения текущего пользователя из токена
169
+ """
170
+ if not authorization:
171
+ raise HTTPException(status_code=401, detail="Токен не предоставлен")
172
+
173
+ # Извлекаем токен из заголовка "Bearer <token>"
174
+ try:
175
+ token = authorization.split(" ")[1]
176
+ except IndexError:
177
+ raise HTTPException(status_code=401, detail="Неверный формат токена")
178
+
179
+ try:
180
+ user_info = await sso_client.get_current_user(access_token=token)
181
+ return user_info
182
+ except AuthenticationError:
183
+ raise HTTPException(status_code=401, detail="Невалидный токен")
184
+ except Exception as e:
185
+ raise HTTPException(status_code=500, detail=f"Ошибка при проверке токена: {e}")
186
+
187
+ @app.get("/protected")
188
+ async def protected_endpoint(current_user = Depends(get_current_user)):
189
+ """
190
+ Защищенный endpoint, который требует валидный токен пользователя
191
+ """
192
+ return {
193
+ "message": f"Привет, {current_user.name} {current_user.surname}!",
194
+ "user_id": current_user.id,
195
+ "email": current_user.email,
196
+ "scopes": current_user.scopes
197
+ }
198
+
199
+ ```
200
+
153
201
  ## API Reference
154
202
 
155
203
  ### UserClient
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sso-nebus"
3
- version = "0.1.1"
3
+ version = "0.1.3"
4
4
  description = "Python клиент для взаимодействия с MS Auth Service API"
5
5
  authors = [
6
6
  {name = "Артем Костюченко",email = "kostyuchenko.work@gmail.com"}
@@ -59,7 +59,7 @@ class ServiceClient(BaseClient):
59
59
  if scope:
60
60
  form_data["scope"] = scope
61
61
 
62
- data = await self.post("auth/token", form_data=form_data)
62
+ data = await self.post("token", form_data=form_data)
63
63
  token_response = TokenResponse(**data)
64
64
 
65
65
  # Сохраняем токен
@@ -83,7 +83,7 @@ class ServiceClient(BaseClient):
83
83
  raise TokenError(
84
84
  "Access token не найден. Вызовите get_access_token() сначала.")
85
85
 
86
- data = await self.get("auth/me", access_token=access_token)
86
+ data = await self.get("me", access_token=access_token)
87
87
  return UserInfo(**data)
88
88
 
89
89
  def set_access_token(self, access_token: str):
@@ -72,7 +72,7 @@ class UserClient(BaseClient):
72
72
  Returns:
73
73
  PKCEParams с code_verifier, code_challenge и state
74
74
  """
75
- data = await self.get("auth/pkce-params")
75
+ data = await self.get("pkce-params")
76
76
  self._pkce_params = PKCEParams(**data)
77
77
  return self._pkce_params
78
78
 
@@ -118,7 +118,7 @@ class UserClient(BaseClient):
118
118
  if scope:
119
119
  params["scope"] = scope
120
120
 
121
- data = await self.get("auth/authorize", params=params)
121
+ data = await self.get("authorize", params=params)
122
122
  return AuthorizeResponse(**data)
123
123
 
124
124
  async def login(
@@ -144,7 +144,7 @@ class UserClient(BaseClient):
144
144
  "password": password,
145
145
  }
146
146
 
147
- data = await self.post("auth/login", json_data=json_data)
147
+ data = await self.post("login", json_data=json_data)
148
148
  return LoginResponse(**data)
149
149
 
150
150
  async def exchange_code_for_tokens(
@@ -182,7 +182,7 @@ class UserClient(BaseClient):
182
182
  if redirect_uri:
183
183
  form_data["redirect_uri"] = redirect_uri
184
184
 
185
- data = await self.post("auth/token", form_data=form_data)
185
+ data = await self.post("token", form_data=form_data)
186
186
  token_response = TokenResponse(**data)
187
187
 
188
188
  # Сохраняем токены
@@ -213,7 +213,7 @@ class UserClient(BaseClient):
213
213
  "client_id": self.client_id,
214
214
  }
215
215
 
216
- data = await self.post("auth/token", form_data=form_data)
216
+ data = await self.post("token", form_data=form_data)
217
217
  token_response = TokenResponse(**data)
218
218
 
219
219
  # Обновляем токены
@@ -238,7 +238,7 @@ class UserClient(BaseClient):
238
238
  raise TokenError(
239
239
  "Access token не найден. Выполните авторизацию сначала.")
240
240
 
241
- data = await self.get("auth/me", access_token=access_token)
241
+ data = await self.get("me", access_token=access_token)
242
242
  return UserInfo(**data)
243
243
 
244
244
  async def logout(self, refresh_token: Optional[str] = None) -> dict:
@@ -258,7 +258,7 @@ class UserClient(BaseClient):
258
258
 
259
259
  form_data = {"refresh_token": refresh_token}
260
260
 
261
- data = await self.post("auth/logout", form_data=form_data)
261
+ data = await self.post("logout", form_data=form_data)
262
262
 
263
263
  # Очищаем токены
264
264
  self._access_token = None
@@ -274,7 +274,7 @@ class UserClient(BaseClient):
274
274
  Returns:
275
275
  ServicesList со списком активных микросервисов
276
276
  """
277
- data = await self.get("auth/services")
277
+ data = await self.get("services")
278
278
  return ServicesList(**data)
279
279
 
280
280
  def _get_access_token(self) -> Optional[str]:
File without changes
File without changes
File without changes