Skip to content

Commit 00aafa3

Browse files
authored
feat: add new APIs: get_user_by_email, get_user_by_phone, get_user_by_user_id, etc. (#105)
1 parent e2cdcea commit 00aafa3

File tree

2 files changed

+183
-23
lines changed

2 files changed

+183
-23
lines changed

src/casdoor/user.py

Lines changed: 130 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414

1515
import json
16-
from typing import Dict, List
16+
from typing import Dict, List, Optional
1717

1818
import requests
1919

@@ -54,16 +54,18 @@ def __init__(self):
5454
self.invitationCode = ""
5555

5656
@classmethod
57-
def new(cls, owner, name, created_time, display_name):
57+
def new(cls, owner, name, created_time, display_name, email="", phone=""):
5858
self = cls()
5959
self.name = name
6060
self.owner = owner
6161
self.createdTime = created_time
6262
self.displayName = display_name
63+
self.email = email
64+
self.phone = phone
6365
return self
6466

6567
@classmethod
66-
def from_dict(cls, data: dict):
68+
def from_dict(cls, data: dict) -> Optional["User"]:
6769
if data is None:
6870
return None
6971

@@ -79,9 +81,52 @@ def __str__(self):
7981
def to_dict(self) -> dict:
8082
return self.__dict__
8183

84+
def get_id(self) -> str:
85+
return f"{self.owner}/{self.name}"
86+
8287

8388
class _UserSDK:
84-
def get_users(self) -> List[Dict]:
89+
def get_global_users(self) -> List[User]:
90+
""" """
91+
url = self.endpoint + "/api/get-global-users"
92+
params = {
93+
"clientId": self.client_id,
94+
"clientSecret": self.client_secret,
95+
}
96+
r = requests.get(url, params)
97+
response = r.json()
98+
if response["status"] != "ok":
99+
raise Exception(response["msg"])
100+
users = []
101+
for user in response["data"]:
102+
users.append(User.from_dict(user))
103+
return users
104+
105+
def get_sorted_users(self, sorter: str, limit: str) -> List[User]:
106+
"""
107+
Get the sorted users from Casdoor.
108+
109+
:param sroter: the DB column name to sort by, e.g., created_time
110+
:param limiter: the count of users to return, e.g., 25
111+
"""
112+
url = self.endpoint + "/api/get-sorted-users"
113+
params = {
114+
"owner": self.org_name,
115+
"sorter": sorter,
116+
"limit": limit,
117+
"clientId": self.client_id,
118+
"clientSecret": self.client_secret,
119+
}
120+
r = requests.get(url, params)
121+
response = r.json()
122+
if response["status"] != "ok":
123+
raise Exception(response["msg"])
124+
users = []
125+
for user in response["data"]:
126+
users.append(User.from_dict(user))
127+
return users
128+
129+
def get_users(self) -> List[User]:
85130
"""
86131
Get the users from Casdoor.
87132
@@ -102,16 +147,73 @@ def get_users(self) -> List[Dict]:
102147
users.append(User.from_dict(user))
103148
return users
104149

105-
def get_user(self, user_id: str) -> User:
150+
def get_user(self, name: str) -> User:
106151
"""
107-
Get the user from Casdoor providing the user_id.
152+
Get the user from Casdoor providing the name.
108153
109-
:param user_id: the id of the user
154+
:param name: the name of the user
110155
:return: a dict that contains user's info
111156
"""
112157
url = self.endpoint + "/api/get-user"
113158
params = {
114-
"id": f"{self.org_name}/{user_id}",
159+
"id": f"{self.org_name}/{name}",
160+
"clientId": self.client_id,
161+
"clientSecret": self.client_secret,
162+
}
163+
r = requests.get(url, params)
164+
response = r.json()
165+
if response["status"] != "ok":
166+
raise Exception(response["msg"])
167+
return User.from_dict(response["data"])
168+
169+
def get_user_by_email(self, email: str) -> User:
170+
"""
171+
Get the user from Casdoor providing the email.
172+
173+
:param email: the email of the user
174+
:return: a User object that contains user's info
175+
"""
176+
url = self.endpoint + "/api/get-user"
177+
params = {
178+
"email": email,
179+
"clientId": self.client_id,
180+
"clientSecret": self.client_secret,
181+
}
182+
r = requests.get(url, params)
183+
response = r.json()
184+
if response["status"] != "ok":
185+
raise Exception(response["msg"])
186+
return User.from_dict(response["data"])
187+
188+
def get_user_by_phone(self, phone: str) -> User:
189+
"""
190+
Get the user from Casdoor providing the phone number.
191+
192+
:param phone: the phone number of the user
193+
:return: a User object that contains user's info
194+
"""
195+
url = self.endpoint + "/api/get-user"
196+
params = {
197+
"phone": phone,
198+
"clientId": self.client_id,
199+
"clientSecret": self.client_secret,
200+
}
201+
r = requests.get(url, params)
202+
response = r.json()
203+
if response["status"] != "ok":
204+
raise Exception(response["msg"])
205+
return User.from_dict(response["data"])
206+
207+
def get_user_by_user_id(self, user_id: str) -> User:
208+
"""
209+
Get the user from Casdoor providing the user ID.
210+
211+
:param user_id: the user ID of the user
212+
:return: a User object that contains user's info
213+
"""
214+
url = self.endpoint + "/api/get-user"
215+
params = {
216+
"userId": user_id,
115217
"clientId": self.client_id,
116218
"clientSecret": self.client_secret,
117219
}
@@ -146,10 +248,25 @@ def get_user_count(self, is_online: bool = None) -> int:
146248
return count
147249

148250
def modify_user(self, method: str, user: User) -> Dict:
251+
"""
252+
modifyUser is an encapsulation of user CUD(Create, Update, Delete) operations.
253+
possible actions are `add-user`, `update-user`, `delete-user`,
254+
"""
255+
id = user.get_id()
256+
return self.modify_user_by_id(method, id, user)
257+
258+
def modify_user_by_id(self, method: str, id: str, user: User) -> Dict:
259+
"""
260+
Modify the user from Casdoor providing the ID.
261+
262+
:param id: the id ( owner/name ) of the user
263+
:param user: a User object that contains user's info
264+
"""
265+
149266
url = self.endpoint + f"/api/{method}"
150267
user.owner = self.org_name
151268
params = {
152-
"id": f"{user.owner}/{user.name}",
269+
"id": id,
153270
"clientId": self.client_id,
154271
"clientSecret": self.client_secret,
155272
}
@@ -168,6 +285,10 @@ def update_user(self, user: User) -> Dict:
168285
response = self.modify_user("update-user", user)
169286
return response
170287

288+
def update_user_by_id(self, id: str, user: User) -> Dict:
289+
response = self.modify_user_by_id("update-user", id, user)
290+
return response
291+
171292
def delete_user(self, user: User) -> Dict:
172293
response = self.modify_user("delete-user", user)
173294
return response

src/tests/test_user.py

Lines changed: 53 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,29 +15,40 @@
1515
import datetime
1616
import unittest
1717

18+
import src.tests.test_util as test_util
1819
from src.casdoor import CasdoorSDK
1920
from src.casdoor.user import User
20-
from src.tests.test_util import (
21-
TestApplication,
22-
TestClientId,
23-
TestClientSecret,
24-
TestEndpoint,
25-
TestJwtPublicKey,
26-
TestOrganization,
27-
get_random_name,
28-
)
2921

3022

3123
class UserTest(unittest.TestCase):
24+
@staticmethod
25+
def get_sdk():
26+
sdk = CasdoorSDK(
27+
endpoint=test_util.TestEndpoint,
28+
client_id=test_util.TestClientId,
29+
client_secret=test_util.TestClientSecret,
30+
certificate=test_util.TestJwtPublicKey,
31+
org_name=test_util.TestOrganization,
32+
application_name=test_util.TestApplication,
33+
)
34+
return sdk
35+
3236
def test_user(self):
33-
name = get_random_name("User")
37+
name = test_util.get_random_name("User")
38+
email = f"{name}@gmail.com"
39+
phone = test_util.get_random_code(11)
3440

3541
# Add a new object
36-
user = User.new(owner="admin", name=name, created_time=datetime.datetime.now().isoformat(), display_name=name)
37-
38-
sdk = CasdoorSDK(
39-
TestEndpoint, TestClientId, TestClientSecret, TestJwtPublicKey, TestOrganization, TestApplication
42+
user = User.new(
43+
owner="admin",
44+
name=name,
45+
created_time=datetime.datetime.now().isoformat(),
46+
display_name=name,
47+
email=email,
48+
phone=phone,
4049
)
50+
51+
sdk = UserTest.get_sdk()
4152
try:
4253
sdk.add_user(user=user)
4354
except Exception as e:
@@ -54,9 +65,16 @@ def test_user(self):
5465
# Get the object
5566
try:
5667
user = sdk.get_user(name)
68+
user_id = user.id
69+
user_by_email = sdk.get_user_by_email(email)
70+
user_by_phone = sdk.get_user_by_phone(phone)
71+
user_by_user_id = sdk.get_user_by_user_id(user_id)
5772
except Exception as e:
5873
self.fail(f"Failed to get object: {e}")
5974
self.assertEqual(user.name, name)
75+
self.assertEqual(user_by_email.name, name)
76+
self.assertEqual(user_by_phone.name, name)
77+
self.assertEqual(user_by_user_id.name, name)
6078

6179
# Update the object
6280
updated_display_name = "Updated Casdoor Website"
@@ -85,3 +103,24 @@ def test_user(self):
85103
except Exception as e:
86104
self.fail(f"Failed to get object: {e}")
87105
self.assertIsNone(deleted_user, "Failed to delete object, it's still retrievable")
106+
107+
def test_get_global_users(self):
108+
sdk = UserTest.get_sdk()
109+
try:
110+
users = sdk.get_global_users()
111+
except Exception as e:
112+
self.fail(f"Fail to get object:{e}")
113+
114+
self.assertIsInstance(users, list, "The returned result is not a list")
115+
for user in users:
116+
self.assertIsInstance(user, User, "There are non User type objects in the list")
117+
118+
def test_get_sort_users(self):
119+
sdk = UserTest.get_sdk()
120+
try:
121+
users = sdk.get_sorted_users("created_time", 25)
122+
except Exception as e:
123+
self.fail(f"Fail to get object:{e}")
124+
self.assertIsInstance(users, list, "The returned result is not a list")
125+
for user in users:
126+
self.assertIsInstance(user, User, "There are non User type objects in the list")

0 commit comments

Comments
 (0)