-
Notifications
You must be signed in to change notification settings - Fork 0
/
userMod.py
258 lines (212 loc) · 6.87 KB
/
userMod.py
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
# std:
import hashlib
import hmac
import re
import secrets
# pip-ext:
import pymongo
# pip-int:
import dotsi
import vf
# loc:
from constants import K
import mongo
import utils
import bu
import hashUp
import stdAdpBuilder
############################################################
# Assertions & prelims: #
############################################################
assert K.CURRENT_USER_V == 1
db = dotsi.fy({"userBox": mongo.db.userBox}) # Isolate
############################################################
# User building and validation: #
############################################################
def genVeriCode():
return secrets.token_urlsafe()
_validateUserFormat = vf.dictOf(
{
"_id": utils.isObjectId,
"_v": lambda x: x == K.CURRENT_USER_V,
#
## Intro'd in _v0:
"fname": vf.typeIs(str),
"lname": vf.typeIs(str),
"email": vf.allOf(
vf.patternIs(K.EMAIL_RE),
lambda x: x == x.lower(),
),
# -- "hpw": vf.typeIs(str), # Hashed PW, -- Removed in _v1
"createdAt": utils.isInty,
"isVerified": vf.typeIs(bool),
"hVeriCode": vf.typeIs(str),
"inviterId": lambda x: x == "" or utils.isObjectId(x),
"isDeactivated": vf.typeIs(bool),
# -- "hResetPw": vf.typeIs(str), # Hashed Reset-PW, -- Removed in _v1
# -- "resetPwExpiresAt": utils.isInty, -- Removed in _v1
"isAdmin": vf.typeIs(bool), # Flag for any admin
"isPrime": vf.typeIs(bool), # Flag for primary admin
#
## Intro'd in _v1: No new props.
},
extraKeysOk=True,
)
def validateUser(user):
assert _validateUserFormat(user)
if user.isPrime:
assert user.isAdmin
return True
def buildUser(
email,
fname,
lname="",
isPrime=False,
isVerified=False,
inviterId="",
veriCode=None,
isAdmin=False,
):
assert K.CURRENT_USER_V == 1
assert fname and email
assert type(fname) == type(email) == str and "@" in email
userId = utils.objectId()
veriCode = veriCode or genVeriCode()
return dotsi.fy(
{
"_id": userId,
"_v": K.CURRENT_USER_V,
#
## Intro'd in _v0:
"fname": fname,
"lname": lname,
"email": email,
# -- "hpw": hpw, -- Removed in _v1
"createdAt": utils.now(),
"isVerified": isVerified,
"hVeriCode": utils.hashPw(veriCode),
"inviterId": inviterId,
"isDeactivated": False,
# -- "hResetPw": "", -- Removed in _v1
# -- "resetPwExpiresAt": 0, -- Removed in _v1
"isAdmin": isAdmin,
"isPrime": isPrime,
#
## Intro'd in _v1: No new props.
}
)
def snipUser(user):
sensitiveKeyList = ["hVeriCode"]
# Note: Use utils.readKeyz(.) in case of multiple keys.
return utils.pick(user, lambda k: k not in sensitiveKeyList)
############################################################
# Adapting:
############################################################
userAdp = stdAdpBuilder.buildStdAdp(
str_fooBox="userBox",
str_CURRENT_FOO_V="CURRENT_USER_V",
int_CURRENT_FOO_V=K.CURRENT_USER_V,
func_validateFoo=validateUser,
)
@userAdp.addStepAdapter
def stepAdapterCore_from_0_to_1(userY): # NON-lambda func.
# user._v: 0 --> 1
# Removed:
# - foo, hResetPw, resetPwExpiresAt
for key in ["hpw", "hResetPw", "resetPwExpiresAt"]:
userY.pop(key)
# @userAdp.addStepAdapter
# def stepAdapterCore_from_X_to_Y(userY): # NON-lambda func.
# # user._v: X --> Y
# # Added:
# # + foo
# userY.update({
# "foo": "foobar",
# })
assert userAdp.getStepCount() == K.CURRENT_USER_V
# Adaptation Checklist:
# Assertions will help you.
# You'll need to look at:
# + constants.py
# + userMod.py
# + top (K) assertion
# + define stepAdapterCore_from_X_to_Y
# + modify builder/s as needed
# + modify validator/s as needed
# + modify snip/s if any, as needed
# + userCon.py and others:
# + modify funcs that call userMod's funcs.
############################################################
# Getting:
############################################################
def getUser(q, shouldUpdateDb=True):
"Query traditionally for a single user."
q = {"_id": q} if type(q) is str else q
assert type(q) is dict
user = db.userBox.find_one(q)
if user is None:
return None
return userAdp.adapt(user, shouldUpdateDb)
def getUserByEmail(email, shouldUpdateDb=True):
"Get a user by email."
return getUser({"email": email}, shouldUpdateDb)
def getUserList(q=None, shouldUpdateDb=True):
"Query traditionally. No special treatment for emails."
q = q or {}
assert type(q) is dict
adaptWrapper = lambda user: (
# ^-- A wrapper around `adapt`, aware of `shouldUpdateDb`.
userAdp.adapt(user, shouldUpdateDb) # , # NO COMMA
)
return utils.map(adaptWrapper, db.userBox.find(q))
def getUserCount(q=None):
return db.userBox.count_documents(q or {})
############################################################
# Inserting, Updating & Deleting:
############################################################
def insertUser(user):
"More or less blindly INSERTS user to db."
# Used primarily for inviting users.
assert validateUser(user)
# print("inserting user: ", user);
dbOut = db.userBox.insert_one(user)
assert dbOut.inserted_id == user._id
return dbOut
def replaceUser(user):
"More or less blindly REPLACES user in db."
# Used primarily for updating fname/password/etc of logged-in user.
assert validateUser(user)
dbOut = db.userBox.replace_one({"_id": user._id}, user)
assert dbOut.matched_count == 1 == dbOut.modified_count
return dbOut
def upsertUser(user):
"More or less blindly upserts user to db."
assert validateUser(user)
# print("upserting user: ", user);
dbOut = db.userBox.replace_one(
{"_id": user._id},
user,
upsert=True,
)
assert (
dbOut.upserted_id == user._id
or dbOut.matched_count == 1 == dbOut.modified_count # _OR_ # or
)
return dbOut
def deleteUser(user):
"Deletes an unverified, invited."
assert validateUser(user)
assert not user.isVerified # Assert not already verified.
dbOut = db.userBox.delete_one(
{
"_id": user._id,
"isVerified": False,
}
)
assert dbOut.deleted_count in [0, 1] # Assert max 1 deletion.
if dbOut.deleted_count == 0:
raise NotImplementedError("User deletion failed.")
# ==> Non-zero records deleted.
assert dbOut.deleted_count == 1
return True
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx