forked from firebase/firebase-admin-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_auth.py
More file actions
273 lines (237 loc) · 9.62 KB
/
test_auth.py
File metadata and controls
273 lines (237 loc) · 9.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Integration tests for firebase_admin.auth module."""
import random
import time
import uuid
import pytest
import requests
from firebase_admin import auth
_id_toolkit_url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken'
def _sign_in(custom_token, api_key):
body = {'token' : custom_token.decode(), 'returnSecureToken' : True}
params = {'key' : api_key}
resp = requests.request('post', _id_toolkit_url, params=params, json=body)
resp.raise_for_status()
return resp.json().get('idToken')
def _random_id():
random_id = str(uuid.uuid4()).lower().replace('-', '')
email = 'test{0}@example.{1}.com'.format(random_id[:12], random_id[12:])
return random_id, email
def _random_phone():
return '+1' + ''.join([str(random.randint(0, 9)) for _ in range(0, 10)])
def test_custom_token(api_key):
custom_token = auth.create_custom_token('user1')
id_token = _sign_in(custom_token, api_key)
claims = auth.verify_id_token(id_token)
assert claims['uid'] == 'user1'
def test_custom_token_with_claims(api_key):
dev_claims = {'premium' : True, 'subscription' : 'silver'}
custom_token = auth.create_custom_token('user2', dev_claims)
id_token = _sign_in(custom_token, api_key)
claims = auth.verify_id_token(id_token)
assert claims['uid'] == 'user2'
assert claims['premium'] is True
assert claims['subscription'] == 'silver'
def test_get_non_existing_user():
with pytest.raises(auth.AuthError) as excinfo:
auth.get_user('non.existing')
assert 'USER_NOT_FOUND_ERROR' in str(excinfo.value.code)
def test_get_non_existing_user_by_email():
with pytest.raises(auth.AuthError) as excinfo:
auth.get_user_by_email('non.existing@definitely.non.existing')
assert 'USER_NOT_FOUND_ERROR' in str(excinfo.value.code)
def test_update_non_existing_user():
with pytest.raises(auth.AuthError) as excinfo:
auth.update_user('non.existing')
assert 'USER_UPDATE_ERROR' in str(excinfo.value.code)
def test_delete_non_existing_user():
with pytest.raises(auth.AuthError) as excinfo:
auth.delete_user('non.existing')
assert 'USER_DELETE_ERROR' in str(excinfo.value.code)
@pytest.fixture
def new_user():
user = auth.create_user()
yield user
auth.delete_user(user.uid)
@pytest.fixture
def new_user_with_params():
random_id, email = _random_id()
phone = _random_phone()
user = auth.create_user(
uid=random_id,
email=email,
phone_number=phone,
display_name='Random User',
photo_url='https://example.com/photo.png',
email_verified=True,
password='secret',
)
yield user
auth.delete_user(user.uid)
@pytest.fixture
def new_user_list():
users = [
auth.create_user(password='password').uid,
auth.create_user(password='password').uid,
auth.create_user(password='password').uid,
]
yield users
for uid in users:
auth.delete_user(uid)
def test_get_user(new_user_with_params):
user = auth.get_user(new_user_with_params.uid)
assert user.uid == new_user_with_params.uid
assert user.display_name == 'Random User'
assert user.email == new_user_with_params.email
assert user.phone_number == new_user_with_params.phone_number
assert user.photo_url == 'https://example.com/photo.png'
assert user.email_verified is True
assert user.disabled is False
user = auth.get_user_by_email(new_user_with_params.email)
assert user.uid == new_user_with_params.uid
user = auth.get_user_by_phone_number(new_user_with_params.phone_number)
assert user.uid == new_user_with_params.uid
assert len(user.provider_data) == 2
provider_ids = sorted([provider.provider_id for provider in user.provider_data])
assert provider_ids == ['password', 'phone']
def test_list_users(new_user_list):
fetched = []
# Test exporting all user accounts.
page = auth.list_users()
while page:
for user in page.users:
assert isinstance(user, auth.ExportedUserRecord)
if user.uid in new_user_list:
fetched.append(user.uid)
assert user.password_hash is not None
assert user.password_salt is not None
page = page.get_next_page()
assert len(fetched) == len(new_user_list)
fetched = []
page = auth.list_users()
for user in page.iterate_all():
assert isinstance(user, auth.ExportedUserRecord)
if user.uid in new_user_list:
fetched.append(user.uid)
assert user.password_hash is not None
assert user.password_salt is not None
assert len(fetched) == len(new_user_list)
def test_create_user(new_user):
user = auth.get_user(new_user.uid)
assert user.uid == new_user.uid
assert user.display_name is None
assert user.email is None
assert user.phone_number is None
assert user.photo_url is None
assert user.email_verified is False
assert user.disabled is False
assert user.custom_claims is None
assert user.user_metadata.creation_timestamp > 0
assert user.user_metadata.last_sign_in_timestamp is None
assert len(user.provider_data) is 0
with pytest.raises(auth.AuthError) as excinfo:
auth.create_user(uid=new_user.uid)
assert excinfo.value.code == 'USER_CREATE_ERROR'
def test_update_user(new_user):
_, email = _random_id()
phone = _random_phone()
user = auth.update_user(
new_user.uid,
email=email,
phone_number=phone,
display_name='Updated Name',
photo_url='https://example.com/photo.png',
email_verified=True,
password='secret')
assert user.uid == new_user.uid
assert user.display_name == 'Updated Name'
assert user.email == email
assert user.phone_number == phone
assert user.photo_url == 'https://example.com/photo.png'
assert user.email_verified is True
assert user.disabled is False
assert user.custom_claims is None
assert len(user.provider_data) == 2
def test_set_custom_user_claims(new_user, api_key):
claims = {'admin' : True, 'package' : 'gold'}
auth.set_custom_user_claims(new_user.uid, claims)
user = auth.get_user(new_user.uid)
assert user.custom_claims == claims
custom_token = auth.create_custom_token(new_user.uid)
id_token = _sign_in(custom_token, api_key)
dev_claims = auth.verify_id_token(id_token)
for key, value in claims.items():
assert dev_claims[key] == value
def test_update_custom_user_claims(new_user):
assert new_user.custom_claims is None
claims = {'admin' : True, 'package' : 'gold'}
auth.set_custom_user_claims(new_user.uid, claims)
user = auth.get_user(new_user.uid)
assert user.custom_claims == claims
claims = {'admin' : False, 'subscription' : 'guest'}
auth.set_custom_user_claims(new_user.uid, claims)
user = auth.get_user(new_user.uid)
assert user.custom_claims == claims
auth.set_custom_user_claims(new_user.uid, None)
user = auth.get_user(new_user.uid)
assert user.custom_claims is None
def test_disable_user(new_user_with_params):
user = auth.update_user(
new_user_with_params.uid,
display_name=None,
photo_url=None,
phone_number=None,
disabled=True)
assert user.uid == new_user_with_params.uid
assert user.email == new_user_with_params.email
assert user.display_name is None
assert user.phone_number is None
assert user.photo_url is None
assert user.email_verified is True
assert user.disabled is True
assert len(user.provider_data) == 1
def test_delete_user():
user = auth.create_user()
auth.delete_user(user.uid)
with pytest.raises(auth.AuthError) as excinfo:
auth.get_user(user.uid)
assert excinfo.value.code == 'USER_NOT_FOUND_ERROR'
def test_revoke_refresh_tokens(new_user):
user = auth.get_user(new_user.uid)
old_valid_after = user.tokens_valid_after_timestamp
time.sleep(1)
auth.revoke_refresh_tokens(new_user.uid)
user = auth.get_user(new_user.uid)
new_valid_after = user.tokens_valid_after_timestamp
assert new_valid_after > old_valid_after
def test_verify_id_token_revoked(new_user, api_key):
custom_token = auth.create_custom_token(new_user.uid)
id_token = _sign_in(custom_token, api_key)
claims = auth.verify_id_token(id_token)
assert claims['iat'] * 1000 >= new_user.tokens_valid_after_timestamp
time.sleep(1)
auth.revoke_refresh_tokens(new_user.uid)
claims = auth.verify_id_token(id_token, check_revoked=False)
user = auth.get_user(new_user.uid)
# verify_id_token succeeded because it didn't check revoked.
assert claims['iat'] * 1000 < user.tokens_valid_after_timestamp
with pytest.raises(auth.AuthError) as excinfo:
claims = auth.verify_id_token(id_token, check_revoked=True)
assert excinfo.value.code == auth._ID_TOKEN_REVOKED
assert str(excinfo.value) == 'The Firebase ID token has been revoked.'
# Sign in again, verify works.
id_token = _sign_in(custom_token, api_key)
claims = auth.verify_id_token(id_token, check_revoked=True)
assert claims['iat'] * 1000 >= user.tokens_valid_after_timestamp