Skip to content

Commit aca0fec

Browse files
authored
Merge pull request #7 from Authing/feature/new_login_methods
Feature/new login methods
2 parents 0184abf + 915c0a7 commit aca0fec

File tree

3 files changed

+108
-66
lines changed

3 files changed

+108
-66
lines changed

authing/authing.py

Lines changed: 89 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
from sgqlc.endpoint.http import HTTPEndpoint
2-
import json
32
import urllib
43
import rsa
54
import base64
5+
import json
66

77
LOGIN_METHOD_USING_EMAIL = "EMAIL"
88
LOGIN_METHOD_USING_PHONE = "PHONE"
@@ -143,7 +143,7 @@ def __init__(self, clientId, secret, options=None):
143143

144144
self.userToken = options["userToken"]
145145

146-
self.servies = {
146+
self.services = {
147147
"oauth": options["oauth"],
148148
"users": options["users"]
149149
}
@@ -156,7 +156,7 @@ def __init__(self, clientId, secret, options=None):
156156

157157
def auth(self):
158158
if 'authService' not in self.__dict__:
159-
self.authService = self._initService(self.servies['users'])
159+
self.authService = self._initService(self.services['users'])
160160

161161
authQuery = '''
162162
query getAccessTokenByAppSecret($secret: String!, $clientId: String!){
@@ -184,7 +184,7 @@ def auth(self):
184184
"Authorization": 'Bearer {}'.format(self.userToken or self.accessToken)
185185
})
186186

187-
self.authService = self._initService(self.servies['users'], headers={
187+
self.authService = self._initService(self.services['users'], headers={
188188
"Authorization": 'Bearer {}'.format(self.userToken or self.accessToken)
189189
})
190190

@@ -197,89 +197,103 @@ def _initService(self, url, headers={}):
197197
return AuthingEndPoint(url, headers)
198198

199199
def _initOAuth(self, headers={}):
200-
self.oauth = self._initService(self.servies['oauth'], headers=headers)
200+
self.oauth = self._initService(self.services['oauth'], headers=headers)
201201
return self.oauth
202202

203203
def _initUsers(self, headers={}):
204-
self.users = self._initService(self.servies['users'], headers=headers)
204+
self.users = self._initService(self.services['users'], headers=headers)
205205
return self.users
206206

207-
def login(self, email: str = None, password: str = None,
208-
verifyCode: str = None, username: str = None,
209-
phone: str = None, phoneCode: int = None
210-
):
207+
def login(self, email=None, username: str = None, password=None, verifyCode=None):
211208

212-
def detect_login_method():
213-
if email and password:
214-
return LOGIN_METHOD_USING_EMAIL
215-
elif phone and phoneCode:
216-
return LOGIN_METHOD_USING_PHONE
217-
elif username and password:
218-
return LOGIN_METHOD_USING_USERNAME
209+
if not email and not username:
210+
raise Exception('请提供邮箱 email 或用户名 username')
219211

220-
login_method = detect_login_method()
221-
if login_method is None:
222-
raise Exception("登陆信息不全,查看文档 https://learn.authing.cn/authing/sdk/sdk-for-python 了解 Authing 支持的不同登陆方式。")
212+
if not password:
213+
raise Exception('请提供密码:password')
223214

224215
loginQuery = """
225-
mutation login(
226-
$email: String
227-
$password: String
228-
$lastIP: String
229-
$registerInClient: String!
230-
$verifyCode: String
231-
$phone: String
232-
$username: String
233-
$browser: String
234-
$phoneCode: Int
235-
) {
236-
login(
237-
email: $email
238-
password: $password
239-
lastIP: $lastIP
240-
registerInClient: $registerInClient
241-
verifyCode: $verifyCode
242-
phone: $phone
243-
phoneCode: $phoneCode
244-
username: $username
245-
browser: $browser
246-
) {
216+
mutation login($unionid: String, $email: String, $password: String, $lastIP: String, $registerInClient: String!, $verifyCode: String) {
217+
login(unionid: $unionid, email: $email, password: $password, lastIP: $lastIP, registerInClient: $registerInClient, verifyCode: $verifyCode) {
218+
_id
219+
email
220+
emailVerified
221+
username
222+
nickname
223+
company
224+
photo
225+
browser
226+
token
227+
tokenExpiredAt
228+
loginsCount
229+
lastLogin
230+
lastIP
231+
signedUp
232+
blocked
233+
isDeleted
234+
}
235+
}
236+
"""
237+
238+
_password = self.encrypt(password)
239+
240+
variables = {
241+
"password": _password,
242+
"registerInClient": self.clientId,
243+
"verifyCode": verifyCode
244+
}
245+
if email:
246+
variables['email'] = email
247+
elif username:
248+
variables['username'] = username
249+
250+
loginResult = self.users(loginQuery, variables)
251+
252+
if not loginResult.get('errors'):
253+
self.users = self._initUsers({
254+
"Authorization": 'Bearer {}'.format(loginResult['data']['login']['token'])
255+
})
256+
return loginResult['data']['login']
257+
else:
258+
return loginResult
259+
260+
def loginByPhoneCode(self, phone: str, phoneCode: int):
261+
262+
if not isinstance(phoneCode, int):
263+
raise Exception("phoneCode 必须为 int 类型")
264+
265+
loginQuery = """
266+
mutation login($phone: String, $phoneCode: Int, $registerInClient: String!, $browser: String) {
267+
login(phone: $phone, phoneCode: $phoneCode, registerInClient: $registerInClient, browser: $browser) {
247268
_id
248269
email
270+
unionid
271+
openid
249272
emailVerified
250273
username
251274
nickname
275+
phone
252276
company
253277
photo
254278
browser
255-
password
256279
token
280+
tokenExpiredAt
257281
loginsCount
258-
group {
259-
name
260-
}
282+
lastLogin
283+
lastIP
284+
signedUp
261285
blocked
286+
isDeleted
262287
}
263288
}
264289
"""
265-
266-
if password:
267-
password = self.encrypt(password)
268290
variables = {
269-
"registerInClient": self.clientId
291+
"registerInClient": self.clientId,
292+
'phone': phone,
293+
'phoneCode': phoneCode
270294
}
271-
if login_method == LOGIN_METHOD_USING_EMAIL:
272-
variables['email'] = email
273-
variables['password'] = password
274-
variables['verifyCode'] = verifyCode
275-
elif login_method == LOGIN_METHOD_USING_PHONE:
276-
variables['phone'] = phone
277-
variables['phoneCode'] = phoneCode
278-
elif login_method == LOGIN_METHOD_USING_USERNAME:
279-
variables['username'] = username
280-
variables['password'] = password
281-
loginResult = self.users(loginQuery, variables)
282295

296+
loginResult = self.users(loginQuery, variables)
283297
if not loginResult.get('errors'):
284298
self.users = self._initUsers({
285299
"Authorization": 'Bearer {}'.format(loginResult['data']['login']['token'])
@@ -288,6 +302,20 @@ def detect_login_method():
288302
else:
289303
return loginResult
290304

305+
def getVerificationCode(self, phone):
306+
send_sms_spi = "{}/send_smscode/{}/{}".format(
307+
self.services['users'].replace("/graphql", ''),
308+
phone,
309+
self.clientId
310+
)
311+
req = urllib.request.Request(send_sms_spi)
312+
resp = urllib.request.urlopen(req)
313+
data = json.loads(resp.read())
314+
code, msg = data['code'], data['message']
315+
if code != 200:
316+
raise Exception(msg)
317+
return data
318+
291319
def register(self, email=None, password=None):
292320

293321
if not email:

authing/test.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@
66

77
test_name = ''
88

9-
username = ""
10-
password = ""
11-
phone = ""
9+
10+
username = "dboehfoikjd"
11+
password = "123456"
12+
phone = "17670416754"
1213
phoneCode = 1234
1314

1415

@@ -35,6 +36,14 @@ def log_test_result(result):
3536
})
3637
log_test_result(authing.accessToken)
3738

39+
# ------- login test ---------- #
40+
log_tester_name("使用邮箱密码登陆")
41+
loginResult = authing.login(
42+
email=email,
43+
password=password
44+
)
45+
log_test_result(loginResult)
46+
3847
# ------- login test ---------- #
3948
log_tester_name("使用用户名密码登陆")
4049
loginResult = authing.login(
@@ -43,9 +52,14 @@ def log_test_result(result):
4352
)
4453
log_test_result(loginResult)
4554

55+
# ------- sms test ---------- #
56+
log_tester_name("发送验证码")
57+
verificationResult = authing.getVerificationCode(phone)
58+
log_test_result(verificationResult)
59+
4660
# ------- login test ---------- #
4761
log_tester_name("使用手机号登陆")
48-
loginResult = authing.login(
62+
loginResult = authing.loginByPhoneCode(
4963
phone=phone,
5064
phoneCode=phoneCode
5165
)

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
setup(
77
name='authing', # 名称
8-
version='0.14.0', # 版本
8+
version='0.15.0', # 版本
99
description="Authing SDK for Python", # 描述
1010
long_description=long_description,
1111
long_description_content_type="text/markdown",

0 commit comments

Comments
 (0)