def __reset_user_password_query(self):
        """
        This function will execute the query for resetting the user password
        :return: Json object
        """
        try:
            with transaction.atomic():
                """ Future use """
                # self._psql_session.execute(CHECK_USER_EXISTANCE_QUERY.format(self._request_payload[USERNAME_KEY]))

                if not self._psql_session.rowcount:
                    return JsonResponse({MESSAGE_KEY: USERNAME_NOT_REGISTERED},
                                        status=HTTP_400_BAD_REQUEST)

                obj = HashingSalting()
                hash, salt = obj.get_hashed_password(
                    self._request_payload[USERPASSWORD_KEY])

                self._psql_session.execute(
                    CHANGE_RESET_USER_PASSWORD_QUERY.format(
                        SALT_KEY, salt, USERPASSWORD_KEY, hash, USERNAME_KEY,
                        self._request_payload[USERNAME_KEY]))
                if not self._psql_session.rowcount:
                    return JsonResponse({MESSAGE_KEY: CHANGE_ERROR},
                                        status=HTTP_400_BAD_REQUEST)

                return JsonResponse({MESSAGE_KEY: RESET_SUCCESSFULLY})

        except IntegrityError as e:
            log_error(traceback.format_exc())
            return JsonResponse({MESSAGE_KEY: traceback.format_exc()},
                                status=HTTP_500_INTERNAL_SERVER_ERROR)

        except Exception as e:
            log_error(traceback.format_exc())

            return JsonResponse(
                {MESSAGE_KEY: INTERNAL_ERROR.format(traceback.format_exc())},
                status=HTTP_500_INTERNAL_SERVER_ERROR)
예제 #2
0
    def __add_user_query(self):
        """
        This function will execute the query for creating a new user
        :return: Json paylaod
        """
        self._psql_session.execute(
            CHECK_AUTHENTICATION_QUERY.format(
                self.loggedin_user_details[LOGIN_ID]))
        result_set = self._psql_session.fetchall()
        if not self._psql_session.rowcount:
            return JsonResponse({MESSAGE_KEY: "LOGIN ID NOT REGISTER WITH US"},
                                status=HTTP_400_BAD_REQUEST)
        Permission = pd.DataFrame(result_set)
        if Permission[USER_TYPE].iloc[0] == 'Super Admin':
            if self._request_payload[USER_TYPE] == 'Admin':
                self._psql_session.execute(GET_ADMIN_COUNT)
                all_admin = pd.DataFrame(self._psql_session.fetchall())
                if not all_admin.empty:
                    admin_count = all_admin['count'].iloc[0].item()
                else:
                    admin_count = None
                self._psql_session.execute(GET_ADMIN_USER)
                admin = pd.DataFrame(self._psql_session.fetchall())
                if not admin.empty:
                    admin_user = admin['limit_value'].iloc[0].item()
                else:
                    admin_user = None
                if admin_user <= admin_count:
                    return JsonResponse({
                        MESSAGE_KEY:
                        "MAXIMUM NUMBER OF ADMIN USER COUNT EXCEEDED"
                    })

            self._psql_session.execute(CHECK_LOGIN_ID)
            loginids = self._psql_session.fetchall()
            login_ids = pd.DataFrame(loginids)
            log_in_id = list(login_ids["login_id"])
            email_id = list(login_ids["email_id"])
            if self._request_payload[
                    LOGIN_ID] not in log_in_id and self._request_payload[
                        USEREMAIL_KEY] not in email_id:
                try:
                    with transaction.atomic():
                        obj = HashingSalting()
                        hash_value, salt_value = obj.get_hashed_password(
                            self._request_payload[USERPASSWORD_KEY])
                        self._psql_session.execute(
                            ADD_USER.format(
                                self._request_payload[NAME],
                                self._request_payload[LOGIN_ID],
                                self._request_payload[USEREMAIL_KEY],
                                self._request_payload[DESIGNATION],
                                self._request_payload[USER_TYPE],
                                self._request_payload[EAMIL_NOTIFICATION],
                                hash_value, salt_value))

                        return JsonResponse(
                            {MESSAGE_KEY: CREATED_SUCCESSFULLY})

                except IntegrityError as e:
                    log_error("Exception due to : %s" + str(e))
                    return json_InternalServerError
                except Exception as e:
                    log_error("Exception due to : %s" + str(e))
                    return json_InternalServerError
            else:
                return JsonResponse(
                    {MESSAGE_KEY: "User is all ready registered"})
        else:
            return JsonResponse(
                {MESSAGE_KEY: "User is not have permission to add"})
예제 #3
0
    def __add_user_query(self):
        """
        This function will execute the query for creating a new user
        :return: Json paylaod
        """
        self._psql_session.execute("select email_id from users")
        email = self._psql_session.fetchall()
        e_i = pd.DataFrame(email)
        em = list(e_i["email_id"])
        if self._request_payload[USEREMAIL_KEY] not in em:
            try:
                with transaction.atomic():
                    obj = HashingSalting()
                    hash_value, salt_value = obj.get_hashed_password(
                        self._request_payload[USERPASSWORD_KEY])
                    self._psql_session.execute(
                        "INSERT INTO users (first_name, middle_name,last_name, email_id,password, salt, "
                        "gender, age, "
                        "mobile, address,status,created_at)VALUES ('{}','{}','{}','{}','{}','{}','{}','{}','{}','{}',"
                        "'{}', "
                        "now())".format(
                            self._request_payload[USERFIRSTNAME_KEY],
                            self._request_payload[USERMIDDLENAME_KEY],
                            self._request_payload[USERLASTNAME_KEY],
                            self._request_payload[USEREMAIL_KEY], hash_value,
                            salt_value, self._request_payload[GENDER_KEY],
                            self._request_payload[AGE_KEY],
                            self._request_payload[PHONE_KEY],
                            self._request_payload[ADDRESS_KEY],
                            self._request_payload[STATUS_KEY]))
                    self._psql_session.execute(
                        "select * from users where email_id='{}'".format(
                            self._request_payload[USEREMAIL_KEY]))
                    result_set = self._psql_session.fetchall()
                    s = pd.DataFrame(result_set)
                    userid = s['id'].iloc[0]
                    self._psql_session.execute(
                        "insert into role_users(role_id,user_id,created_at)VALUES({},{},now())"
                        .format(self._request_payload[ROLE_ID], userid))
                    self._psql_session.execute(
                        "select permission_id from role_permission where role_id={}"
                        .format(self._request_payload[ROLE_ID]))
                    result = self._psql_session.fetchall()
                    p = pd.DataFrame(result)
                    pid = list(p['permission_id'])
                    data = []
                    for i in pid:
                        data.append((userid, i))
                    execute_values(
                        self._psql_session,
                        "INSERT INTO user_permission (user_id,permission_id) VALUES %s",
                        data)
                    return JsonResponse({MESSAGE_KEY: CREATED_SUCCESSFULLY})

            except IntegrityError as e:
                log_error("Exception due to : %s" + str(e))
                return JsonResponse({MESSAGE_KEY: traceback.format_exc()},
                                    status=HTTP_500_INTERNAL_SERVER_ERROR)

            except Exception as e:
                log_error("Exception due to : %s" + str(e))
                return JsonResponse(
                    {
                        MESSAGE_KEY: INTERNAL_ERROR.format(
                            traceback.format_exc())
                    },
                    status=HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            return JsonResponse({MESSAGE_KEY: "Email is all ready registered"})
예제 #4
0
    def __change_user_password_query(self):
        """
        This function will execute the query for resetting the user password
        :return: Json object
        """
        try:
            with transaction.atomic():

                if DEVELOPMENT:
                    self._psql_session.execute(
                        CHECK_AUTHENTICATION_QUERY.format(
                            self.loggedin_userid_details[LOGIN_ID]))
                else:
                    self._psql_session.execute(
                        CHECK_AUTHENTICATION_QUERY.format(
                            self.loggedin_userid_details[LOGIN_ID]))
                if not self._psql_session.rowcount:
                    return JsonResponse({MESSAGE_KEY: USERNAME_NOT_REGISTERED},
                                        status=HTTP_400_BAD_REQUEST)
                result_set = self._psql_session.fetchall()
                Permission = pd.DataFrame(result_set)
                self._psql_session.execute(
                    CHECK_AUTHENTICATION_QUERY.format(
                        self._request_payload[LOGIN_ID]))
                admin = pd.DataFrame(self._psql_session.fetchall())
                if not admin.empty:
                    check_admin = admin[USER_TYPE].iloc[0]
                    receiver = admin['email_id'].iloc[0]
                else:
                    return JsonResponse(
                        {MESSAGE_KEY: "USER IS NOT REGISTER WITH US"})

                if Permission[USER_TYPE].iloc[0] == 'Super Admin':
                    self._psql_session.execute(CHECK_LOGIN_ID)
                    loginids = self._psql_session.fetchall()
                    login_ids = pd.DataFrame(loginids)
                    log_in_id = list(login_ids["login_id"])
                    if self._request_payload[LOGIN_ID] in log_in_id:
                        obj = HashingSalting()
                        hash, salt = obj.get_hashed_password(
                            self._request_payload[USERPASSWORD_KEY])

                        self._psql_session.execute(
                            CHANGE_RESET_USER_PASSWORD_QUERY.format(
                                SALT_KEY, salt, USERPASSWORD_KEY, hash,
                                LOGIN_ID, self._request_payload[LOGIN_ID]))
                        port = 465  # For SSL
                        smtp_server = "smtpout.ingenero.com"

                        context = ssl.create_default_context()
                        with smtplib.SMTP_SSL(smtp_server,
                                              port,
                                              context=context) as server:
                            print(
                                server.login('*****@*****.**',
                                             'Ap5sn%k*20'))
                            msg = MIMEMultipart('alternative')
                            msg['Subject'] = "Reset Password"
                            msg['From'] = '*****@*****.**'
                            msg['To'] = '*****@*****.**'

                            context = """Hi.\n Here is the you are Password .\n {}""".format(
                                self._request_payload[USERPASSWORD_KEY])
                            part1 = MIMEText(context, 'plain')
                            msg.attach(part1)
                            server.sendmail('*****@*****.**',
                                            '*****@*****.**',
                                            msg.as_string())

                            server.quit()

                        if self._psql_session.rowcount:
                            return JsonResponse({
                                MESSAGE_KEY:
                                "PASSWORD UPDATED SUCCESSFULLY AND PASSWORD SENT TO "
                                "MAIL"
                            })

                        return JsonResponse({MESSAGE_KEY: RESET_ERROR},
                                            status=HTTP_400_BAD_REQUEST)

                    return JsonResponse(
                        {MESSAGE_KEY: "USER IS NOT REGISTER WITH US"})
                else:
                    return JsonResponse({
                        MESSAGE_KEY:
                        "NON ADMIN USER IS NOT ACCESS TO CHANGE PASSWORD"
                    })

        except IntegrityError as e:

            log_error("Exception due to : %s" + str(e))

            return json_InternalServerError

        except Exception as e:

            log_error("Exception due to : %s" + str(e))

            return json_InternalServerError
예제 #5
0
    def __reset_user_password_query(self):
        """
        This function will execute the query for resetting the user password
        :return: Json object
        """
        try:
            with transaction.atomic():
                try:
                    decode_jwt = TokenManagement.is_valid_jwt(
                        self._request_payload[TOKEN])
                    login_id = decode_jwt['login_id']
                    self._psql_session.execute(
                        CHECK_AUTHENTICATION_QUERY.format(login_id))
                    admin = pd.DataFrame(self._psql_session.fetchall())
                    check_admin = None
                    if not admin.empty:
                        check_admin = admin[USER_TYPE].iloc[0]
                        receiver = admin['email_id'].iloc[0]
                    else:
                        return JsonResponse(
                            {MESSAGE_KEY: "USER IS NOT REGISTER WITH US"})

                    if check_admin == 'Admin' or check_admin == 'Super Admin':
                        self._psql_session.execute(CHECK_LOGIN_ID)
                        loginids = self._psql_session.fetchall()
                        login_ids = pd.DataFrame(loginids)
                        log_in_id = list(login_ids["login_id"])
                        if login_id in log_in_id:
                            obj = HashingSalting()
                            hash_value, salt = obj.get_hashed_password(
                                self._request_payload[USERPASSWORD_KEY])

                            self._psql_session.execute(
                                CHANGE_RESET_USER_PASSWORD_QUERY.format(
                                    SALT_KEY, salt, USERPASSWORD_KEY,
                                    hash_value, LOGIN_ID, login_id))
                            # s = smtplib.SMTP('smtp.gmail.com', 587)
                            # s.starttls()
                            # sender = '*****@*****.**'
                            # s.login(sender, 'Mdevendra@1996')
                            # receiver_mail = receiver
                            # msg = MIMEMultipart('alternative')
                            # msg['Subject'] = "Password"
                            # msg['From'] = sender
                            # msg['To'] = receiver_mail
                            # context = """Hi.\n Here is the you are Password .\n {}""".format(
                            #     self._request_payload[USERPASSWORD_KEY])
                            # part1 = MIMEText(context, 'plain')
                            # msg.attach(part1)
                            # s.sendmail(sender, '*****@*****.**', msg.as_string())
                            # s.quit()
                            port = 465  # For SSL
                            smtp_server = "smtpout.ingenero.com"

                            context = ssl.create_default_context()
                            with smtplib.SMTP_SSL(smtp_server,
                                                  port,
                                                  context=context) as server:
                                print(
                                    server.login('*****@*****.**',
                                                 'Ap5sn%k*20'))
                                msg = MIMEMultipart('alternative')
                                msg['Subject'] = "Reset Password"
                                msg['From'] = '*****@*****.**'
                                msg['To'] = '*****@*****.**'

                                context = """Hi.\n Here is the you are Password .\n {}""".format(
                                    self._request_payload[USERPASSWORD_KEY])
                                part1 = MIMEText(context, 'plain')
                                msg.attach(part1)
                                server.sendmail('*****@*****.**',
                                                '*****@*****.**',
                                                msg.as_string())

                except jwt.ExpiredSignatureError:
                    return JsonResponse({MESSAGE_KEY: "Token Expired"})

                if not self._psql_session.rowcount:
                    return JsonResponse({MESSAGE_KEY: CHANGE_ERROR},
                                        status=HTTP_400_BAD_REQUEST)

                return JsonResponse({MESSAGE_KEY: RESET_SUCCESSFULLY})

        except IntegrityError as e:

            log_error("Exception due to : %s" + str(e))

            return json_InternalServerError

        except Exception as e:

            log_error("Exception due to : %s" + str(e))

            return json_InternalServerError