aboutsummaryrefslogtreecommitdiffstats
path: root/services/database/db_user.py
blob: 10d02ffa6c1ba894f600d6f1f3212d54f8ae65b2 (plain)
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# ============LICENSE_START==========================================
# org.onap.vvp/test-engine
# ===================================================================
# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
# ===================================================================
#
# Unless otherwise specified, all software contained herein is licensed
# under the Apache License, Version 2.0 (the “License”);
# you may not use this software 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.
#
#
#
# Unless otherwise specified, all documentation contained herein is licensed
# under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
# you may not use this documentation except in compliance with the License.
# You may obtain a copy of the License at
#
#             https://creativecommons.org/licenses/by/4.0/
#
# Unless required by applicable law or agreed to in writing, documentation
# 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.
#
# ============LICENSE_END============================================
#
# ECOMP is a trademark and service mark of AT&T Intellectual Property.
import time

from django.conf import settings
import psycopg2

from services.constants import Constants
from services.database.db_bridge import DBBridge
from services.database.db_general import DBGeneral
from services.database.db_virtual_function import DBVirtualFunction
from services.frontend.base_actions.wait import Wait
from services.logging_service import LoggingServiceFactory
from services.session import session


logger = LoggingServiceFactory.get_logger()


class DBUser:

    @staticmethod
    def get_activation_url(email):
        # Fetch one user ID.
        uuid = DBUser.select_user_uuid(email)
        # Fetch one user ID.
        index = DBGeneral.select_where_email("id", "auth_user", email)
        activation_token = DBGeneral.select_where(
            "activation_token", "ice_custom_user", "user_ptr_id", index, 1)
        # / activate /:userID /:token
        activationUrl = settings.ICE_PORTAL_URL + '/#/activate/' + \
            str(uuid) + '/' + str(activation_token)
        logger.debug("activationUrl :" + activationUrl)
        return activationUrl

    @staticmethod
    def get_contact_signup_url(
            invite_token,
            uuid,
            email,
            fullName,
            phoneNum,
            companyName):
        companyId = DBGeneral.select_where(
            "uuid", "ice_vendor", "name", companyName, 1)
        signUpURLforContact = settings.ICE_PORTAL_URL + \
            "#/signUp?invitation=" + invite_token + \
            "&email=" + email + "&full_name=" + fullName + \
            "&phone_number=" + phoneNum + "&company=" + companyId
        logger.debug("SignUpURLforContact :" + signUpURLforContact)
        return signUpURLforContact

    @staticmethod
    def select_invitation_token(
            queryColumnName,
            queryTableName,
            whereParametrType,
            whereParametrValue,
            email,
            fetchNum):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            queryStr = \
                "select %s from %s Where %s = '%s' and email = '%s' ;" % (
                    queryColumnName, queryTableName, whereParametrType,
                    whereParametrValue, email)
            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            if (fetchNum == 0):
                result = str(cur.fetchall())
            elif (fetchNum == 1):
                result = str(cur.fetchone())
                if(result.find("',)") != -1):  # formatting strings e.g uuid
                    result = result.partition('\'')[-1].rpartition('\'')[0]
                elif(result.find(",)") != -1):  # formatting ints e.g id
                    result = result.partition('(')[-1].rpartition(',')[0]
            dbConn.close()
            if result is None:
                errorMsg = "select_where_pr_state FAILED "
                logger.error(errorMsg)
                raise
            logger.debug("Query result: " + str(result))
            return result
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_where FAILED "
            raise Exception(errorMsg, "select_where")

    @staticmethod
    def get_el_name(vfName):
        try:
            # Fetch one AT&T user ID.
            engagement_id = DBVirtualFunction.select_eng_uuid(vfName)
            engagement_manual_id = DBGeneral.select_where(
                "engagement_manual_id", "ice_engagement", "uuid",
                engagement_id, 1)
            reviewer_id = DBGeneral.select_where(
                "reviewer_id",
                "ice_engagement",
                "engagement_manual_id",
                engagement_manual_id,
                1)
            engLeadFullName = DBGeneral.select_where_and(
                "full_name", "ice_user_profile", "id", reviewer_id,
                "role_id", "2", 1)
            return engLeadFullName
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "get_el_name FAILED "
            raise Exception(errorMsg, "get_el_name")

    @staticmethod
    def get_email_by_full_name(fullname):
        #         try:
        query_str = "select email from ice_user_profile where " +\
            "full_name = '%s';" % (fullname)
        user_email = DBGeneral.select_query(query_str)
        return user_email

    @staticmethod
    def select_recent_vf_of_user(user_uuid, fetchNum):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            queryStr = "SELECT vf_id FROM public.ice_recent_engagement " +\
                "where user_uuid = '%s' order by last_update " % user_uuid +\
                "desc limit 20;"
            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            if (fetchNum == 0):
                result = str(cur.fetchall())
            elif (fetchNum == 1):
                result = str(cur.fetchone())
                if(result.find("',)") != -1):  # formatting strings e.g uuid
                    result = result.partition('\'')[-1].rpartition('\'')[0]
                elif(result.find(",)") != -1):  # formatting ints e.g id
                    result = result.partition('(')[-1].rpartition(',')[0]
            dbConn.close()
            logger.debug("Query result: " + str(result))
            return result
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_where FAILED "
            raise Exception(errorMsg, "select_where")

    @staticmethod
    def select_el_email(vfName):
        try:
            # Fetch one AT&T user ID.
            engagement_id = DBVirtualFunction.select_eng_uuid(vfName)
            engagement_manual_id = DBGeneral.select_where(
                "engagement_manual_id", "ice_engagement", "uuid",
                engagement_id, 1)
            reviewer_id = DBGeneral.select_where(
                "reviewer_id",
                "ice_engagement",
                "engagement_manual_id",
                engagement_manual_id,
                1)
            engLeadEmail = DBGeneral.select_where_and(
                "email", "ice_user_profile", "id", reviewer_id, "role_id",
                "2", 1)
            return engLeadEmail
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_el_email FAILED "
            raise Exception(errorMsg, "select_el_email")

    @staticmethod
    def select_user_native_id(email):
        try:
            # Fetch one AT&T user ID.
            engLeadId = DBUser.select_user_profile_property(email, "id")
            return engLeadId
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_user_native_id FAILED "
            raise Exception(errorMsg, "select_user_native_id")

    @staticmethod
    def select_personal_next_step(email):
        user_id = DBUser.select_user_native_id(email)
        return DBGeneral.select_where(
            "uuid", "ice_next_step", "owner_id", user_id, 1)

    @staticmethod
    def select_pr_email(vfName):
        try:
            # Fetch one AT&T user ID.
            engagement_id = DBVirtualFunction.select_eng_uuid(vfName)
            engagement_manual_id = DBGeneral.select_where(
                "engagement_manual_id", "ice_engagement", "uuid",
                engagement_id, 1)
            reviewer_id = DBGeneral.select_where(
                "peer_reviewer_id",
                "ice_engagement",
                "engagement_manual_id",
                engagement_manual_id,
                1)
            engLeadEmail = DBGeneral.select_where(
                "email", "ice_user_profile", "id", reviewer_id, 1)
            return engLeadEmail
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_el_email FAILED "
            raise Exception(errorMsg, "select_el_email")

    @staticmethod
    def get_notification_id_by_email(userEmail):
        uuid = DBGeneral.select_where_email(
            "id", "ice_user_profile", userEmail)
        notifIDs = DBGeneral.select_where(
            "uuid", "ice_notification", "user_id", uuid, 0)
        return notifIDs

    @staticmethod
    def get_not_seen_notifications_number_by_email(
            user_email, is_negative=False):
        user_id = DBGeneral.select_where_email(
            "id", Constants.DBConstants.IceTables.USER_PROFILE, user_email)
        notifications_number = DBGeneral.select_where_and(
            Constants.DBConstants.Queries.COUNT,
            Constants.DBConstants.IceTables.NOTIFICATION,
            "user_id",
            user_id,
            "is_read",
            "False",
            1)
        if is_negative:
            counter = 0
            while notifications_number != "0" and counter <= Constants.\
                    Dashboard.Avatar.Notifications.Count.RETRIES_NUMBER:
                notifications_number = DBGeneral.select_where_and(
                    Constants.DBConstants.Queries.COUNT,
                    Constants.DBConstants.IceTables.NOTIFICATION,
                    "user_id",
                    user_id,
                    "is_read",
                    "False",
                    1)
                time.sleep(1)
                counter += 1
        return notifications_number

    @staticmethod
    def get_eng_lead_email_per_enguuid(enguuid):
        reviewer_id = DBGeneral.select_where(
            "reviewer_id",
            Constants.DBConstants.IceTables.ENGAGEMENT,
            "uuid",
            enguuid,
            1)
        engLeadEmail = DBGeneral.select_where(
            "email", Constants.DBConstants.IceTables.USER_PROFILE, "id",
            reviewer_id, 1)
        return engLeadEmail

    @staticmethod
    def select_all_user_engagements(engLeadID):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            queryStr = "select COUNT(*) from ice_engagement_engagement_team" +\
                " Where iceuserprofile_id = %s" % engLeadID +\
                " and (select " +\
                "engagement_stage from public.ice_engagement " +\
                "where uuid = engagement_id LIMIT 1) != 'Archived';"

            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            result = cur.fetchall()
            dbConn.close()
            logger.debug("Query result: " + str(result))
            logger.debug(result[0][0])
            return result[0][0]
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_user_engagements_by_stage FAILED "
            raise Exception(errorMsg, "select_user_engagements_by_stage")

    @staticmethod
    def select_user_engagements_by_stage(stage, engLeadID):
        try:
            dbConn = psycopg2.connect(
                DBGeneral.return_db_native_connection('em_db'))
            dbConn = dbConn
            cur = dbConn.cursor()
            queryStr = "select count(*) from ice_engagement INNER JOIN " +\
                "ice_engagement_engagement_team ON " +\
                "ice_engagement_engagement_team.engagement_id= " +\
                "ice_engagement.uuid Where " +\
                "(ice_engagement.engagement_stage  " +\
                "= '%s')  and " % stage +\
                "(ice_engagement_engagement_team.iceuserprofile_id =  " +\
                "%s );" % engLeadID
            logger.debug("Query : " + queryStr)
            cur.execute(queryStr)
            result = cur.fetchall()
            dbConn.close()
            logger.debug("Query result: " + str(result))
            logger.debug(result[0][0])
            return result[0][0]
        # If failed - count the failure and add the error to list of errors.
        except BaseException:
            errorMsg = "select_user_engagements_by_stage FAILED "
            raise Exception(errorMsg, "select_user_engagements_by_stage")

    @staticmethod
    def set_new_temp_password(email):
        encodePass = DBGeneral.select_where_email(
            "password", "auth_user", Constants.Users.Admin.EMAIL)
        # Fetch one user ID.
        index = DBGeneral.select_where_email("id", "auth_user", email)
        DBGeneral.update_where(
            "ice_custom_user",
            "temp_password",
            encodePass,
            "user_ptr_id",
            index)

    @staticmethod
    def set_password_to_default(email):
        encodePass = DBGeneral.select_where_email(
            "password", "auth_user", Constants.Users.Admin.EMAIL)
        DBGeneral.update_where(
            "auth_user", "password", encodePass, "email", email)

    @staticmethod
    def select_el_not_in_engagement(el_name, pr_name):
        query_str = "select full_name from ice_user_profile where " +\
            "role_id = 2 and full_name != '%s' and full_name != '%s';" % (
                el_name, pr_name)
        new_user = DBGeneral.select_query(query_str)
        if new_user == 'None':
            new_user = DBUser.update_to_el_not_in_engagement()
        return new_user

    @staticmethod
    def select_user_uuid(email):
        user_uuid = DBUser.select_user_profile_property(email, "uuid")
        return user_uuid

    @staticmethod
    def select_access_key(email):
        access_key = DBUser.select_user_profile_property(
            email, "rgwa_access_key")
        return access_key

    @staticmethod
    def select_secret_key(email):
        secret_key = DBUser.select_user_profile_property(
            email, "rgwa_secret_key")
        return secret_key

    @staticmethod
    def update_to_el_not_in_engagement():
        query_str = "select uuid from ice_user_profile where role_id = 1 ;"
        user_uuid = DBGeneral.select_query(query_str)
        updatequery = "UPDATE ice_user_profile SET role_id=2 ,full_name" +\
            " = 'el_for_test' WHERE uuid = '%s' ;" % (
                user_uuid)
        DBGeneral.update_query(updatequery)
        updatequery = "UPDATE ice_user_profile SET role_id=2 WHERE " +\
            "full_name = '%s' ;" % (
                'el_for_test')
        DBGeneral.update_query(updatequery)
        return 'el_for_test'

    @staticmethod
    def rollback_for_el_not_in_engagement():
        query_str = "select uuid from ice_user_profile where full_name = " +\
            "'el_for_test';"
        user_uuid = DBGeneral.select_query(query_str)
        fullName = DBBridge.helper_rand_string("randomString")
        updatequery = "UPDATE ice_user_profile SET role_id=1,full_name " +\
            "= '%s' WHERE uuid = '%s'  ;" % (fullName, user_uuid)
        DBGeneral.update_query(updatequery)

    @staticmethod
    def set_engagement_peer_reviewer(engagement_uuid, email):
        user_uuid = DBUser.select_user_uuid(email)
        update_query = "UPDATE ice_user_profile SET role_id=2 WHERE " +\
            "uuid = '%s';" % user_uuid
        DBGeneral.update_query(update_query)

        user_id = DBGeneral.select_query(
            "SELECT id FROM ice_user_profile WHERE uuid = '%s';" % user_uuid)
        update_query = "UPDATE ice_engagement SET peer_reviewer_id=%s " +\
            "WHERE uuid = '%s';" % (
                user_id, engagement_uuid)
        DBGeneral.update_query(update_query)

    @staticmethod
    def select_user_profile_property(user_email, property_name):
        return DBGeneral.select_where(
            property_name,
            "ice_user_profile",
            "email",
            user_email,
            1)

    @staticmethod
    def validate_user_profile_settings_in_db(user_email, checked):
        Wait.page_has_loaded()
        regular_email_updates = DBUser.select_user_profile_property(
            user_email, 'regular_email_updates')
        DBBridge.helper_internal_assert(regular_email_updates, checked)
        email_updates_on_every_notification = \
            DBUser.select_user_profile_property(
                user_email, 'email_updates_on_every_notification')
        DBBridge.helper_internal_assert(
            email_updates_on_every_notification, checked)
        email_updates_daily_digest = DBUser.select_user_profile_property(
            user_email, 'email_updates_daily_digest')
        DBBridge.helper_internal_assert(
            email_updates_daily_digest, not checked)

    @staticmethod
    def retrieve_admin_ssh_from_db():
        ssh_key = DBGeneral.select_where(
            'ssh_public_key', Constants.DBConstants.IceTables.USER_PROFILE,
            'email', Constants.Users.Admin.EMAIL, 1)
        return ssh_key

    @staticmethod
    def get_access_key(user_uuid):
        counter = 0
        access_key = DBGeneral.select_where(
            "rgwa_access_key",
            Constants.DBConstants.IceTables.USER_PROFILE,
            "uuid",
            user_uuid,
            1)
        while access_key == "None" and counter <= \
                Constants.RGWAConstants.RETRIES_NUMBER:
            time.sleep(session.wait_until_time_pause)
            logger.debug(
                "rgwa_access_key are not ready yet, trying again (%s of 20)" %
                counter)
            access_key = DBGeneral.select_where(
                "rgwa_access_key",
                Constants.DBConstants.IceTables.USER_PROFILE,
                "uuid",
                user_uuid,
                1)
            counter += 1
        return access_key

    @staticmethod
    def get_access_secret(user_uuid):
        counter = 0
        access_secret = DBGeneral.select_where(
            "rgwa_secret_key",
            Constants.DBConstants.IceTables.USER_PROFILE,
            "uuid",
            user_uuid,
            1)
        while access_secret == "None" and counter <= Constants.\
                RGWAConstants.RETRIES_NUMBER:
            time.sleep(session.wait_until_time_pause)
            logger.debug(
                "rgwa_secret_key are not ready yet, trying again (%s of 100)" %
                counter)
            access_secret = DBGeneral.select_where(
                "rgwa_secret_key",
                Constants.DBConstants.IceTables.USER_PROFILE,
                "uuid",
                user_uuid,
                1)

            counter += 1
        return access_secret