Beispiel #1
0
class DirectQuery:
    """
    For piping queries to MSH and building pools of stems from related concepts.

    """
    def __init__(self, identifier):
        """
        :param identifier: (str) search term

        Other attributes are all defaults by design.

        """
        #authorize
        self.AuthClient = Authentication()
        self.AuthClient.gettgt()

        #set attributes
        self.identifier = identifier
        self.version = "current"
        self.source = "MSH"
        self.returntype = "concept"

        #send the query and return dataframe
        self.get_query_result()
        self.df = self.parse_query_result()

    def get_query_result(self):
        """
        Search by human-readable string.

        :return: concepts
        """
        uri = "https://uts-ws.nlm.nih.gov"
        content_endpoint = "/rest/search/{0}?string={1}&sabs={2}&returnIdType={3}".format(
                           self.version, self.identifier, self.source, self.returntype)

        self.query = {'ticket':self.AuthClient.getst()}

        r = requests.get(uri+content_endpoint, params=self.query)

        items = json.loads(r.text)
        self.jsonData = items["result"]

    def parse_query_result(self):
        """
        Extract name and unique id from results.

        :return: pandas dataframe
        """
        results = self.jsonData['results']

        df = pd.DataFrame(results)
        df.drop(['rootSource', 'uri'], axis=1, inplace=True)

        return df
 def __init__(self, clientId, data, verifykey, apiEndPoint):
     self.message = data
     self.sessionkey = verifykey
     self.apiEndPoint = apiEndPoint
     self.splitUrl = apiEndPoint.split('/')
     self.auth = Authentication()
     self.master = Master()
     self.admin = Admin()
     self.role = roleManage()
     self.attendance = attendanceManage()
     self.project = projectManage()
     self.labourer = labbourerManage()
     self.labclass = labourerClass()
     self.shift = shiftManage()
     self.log = Logger()
     self.paymentDesk = paymentDesk()
     self.clientId = clientId
Beispiel #3
0
 def get(self):
     activity = Activity()
     from Authentication import Authentication
     authentication = Authentication(users)
     print(activity)
     return ({
         "activity": str(activity),
         "user": str(authentication),
         "location": "home"
     })
Beispiel #4
0
def get_umls_ticket2(tgt=tgt, AuthClient=AuthClient, apikey=umls_api):
    """
    Get a single use ticket for the UMLS REST services.
    It is supposed that an Author Client and a Ticket
    Granting Service have already been set-up in case
    the apikey = None. If an api-key is given, create the
    above needed instances and generate a new ticket.
    Input:
        - apikey: str,
        UMLS REST services api-key. Default is None and
        the already establised service is used
    Output:
        - string of the generated ticket
    """

    # Get ticket from the already establised service
    if not (tgt) and not (AuthClient):
        AuthClient = Authentication(umls_api)
        tgt = AuthClient.gettgt()
    return AuthClient.getst(tgt)
    def handle(self):
        """
        Handle requests from the clients.
        :return:
        """
        global auth_dict, nonce_dict, crypto_service, password_hash_dict, user_addr_dict, chatting_service
        msg = self.request[0]
        sock = self.request[1]
        # get auth instance for client
        if self.client_address not in auth_dict:
            try:
                _, msg_parts = PacketOrganiser.process_packet(msg)
            except:
                return
            if msg_parts[0] != c.GREETING:
                return
            # new client, create an auth entry in the auth dictionary
            auth_dict[self.client_address] = Authentication(
                self.client_address, crypto_service, password_hash_dict)
        else:
            auth = auth_dict[self.client_address]
            if not PacketOrganiser.isValidTimeStampSeconds(
                    auth.timestamp, c.KEEP_ALIVE_TIME):
                auth_dict.pop(self.client_address)

        cur_auth = auth_dict[self.client_address]
        assert isinstance(cur_auth, Authentication)
        rep = None
        if not cur_auth.is_auth():
            rep = cur_auth.process_request(msg, user_addr_dict)

        else:
            # get decrypted msg
            dec_msg = crypto_service.sym_decrypt(cur_auth.dh_key, msg)
            n, msg_ps = PacketOrganiser.process_packet(dec_msg)
            auth_dict[
                self.
                client_address].timestamp = PacketOrganiser.get_new_timestamp(
                )  # update timestamp
            rep = chatting_service.get_response(self.client_address, msg_ps)
            if rep is not None:
                rep = PacketOrganiser.prepare_packet(rep, n)
                rep = crypto_service.sym_encrypt(cur_auth.dh_key, rep)

        try:
            if rep is not None:
                sys.stdout.flush()
                sock.sendto(rep, self.client_address)
            elif cur_auth.is_auth():
                cur_auth.loginfailures += 1
        except socket.error:
            print(c.FAIL_MSG_FWD)
            return
Beispiel #6
0
 def __init__(self, user, key):
     self.auth = Authentication(user, key)
     try:
         self.auth.doLogin()
     except RackSpaceAuthenticationFailedException:
         print "Invalid credentials was provided!"
         self.auth = None
     except RackSpaceException:
         print "Error during auth procedure"
         # sys.exit(1)
         self.auth = None
     self.updateAuthToken(self.auth.getAuthToken())
Beispiel #7
0
def find_snomedct_server(term):
    apikey = "ca310f05-53e6-4984-82fd-8691dc30174e"
    AuthClient = Authentication(apikey)
    version = "2017AB"
    tgt = AuthClient.gettgt()
    query = {'ticket': AuthClient.getst(tgt), 'targetSource': 'SNOMEDCT_US'}
    base_uri = "https://uts-ws.nlm.nih.gov/rest"
    search_uri = "/search/current?string="
    content_uri = "/content/current/CUI/"
    source = "&sabs=SNOMEDCT_US"
    search_type = '&searchType=words'
    path = base_uri + search_uri + term + search_type + source
    r = requests.get(path, params=query)
    code, name, semantic = "", "", ""
    try:
        items = json.loads(r.text)
        pprint(items['result']['results'])
        code, name = select_code(items['result']['results'], term)
        if code != "":
            path2 = base_uri + content_uri + code
            tgt2 = AuthClient.gettgt()
            query2 = {
                'ticket': AuthClient.getst(tgt2),
                'targetSource': 'SNOMEDCT_US'
            }
            r2 = requests.get(path2, params=query2)
            try:
                items2 = json.loads(r2.text)
                semantic = items2['result']['semanticTypes'][0]['name']
            except json.decoder.JSONDecodeError:
                semantic = "UNKNOWN"
    except json.decoder.JSONDecodeError:
        code, name = "", ""
    return code, name, semantic
Beispiel #8
0
 def main(self):
     auth.auth(self.b, self.selector)
     cons = Conss()
     # if cons.toBeMessaged():
     #     print("the file is empty so we are going to get new connecitons")
     #     cons.getConnection(self.b,self.selector,self.soup)
     message_file = open(credentials.MESSAGE_FILE_PATH, "r")
     message = message_file.read()
     # lastPresent = False
     # last = open(credentials.LAST_CONNECTION_SENT_MESSAGE_FILE_PATH,"r")
     # if last == "":
     #     lastPresent = True
     # print=(last)
     for connection in cons.loadConnections():
         # print(f"{connection.name} {connection.profile}")
         # if not lastPresent:
         #     if f"{connection.name} {connection.profile}" == last:
         #         lastPresent = True
         #     else:
         #         continue
         # print("sending connection message")
         connection.sendMessage(self.b, self.selector, message, webdriver)
     message_file.close()
Beispiel #9
0
    def on_status(self, status):
        registration_ids = Authentication.firebase_registration_ids()
        message_title = "Support Alert"
        message_body = status.text

        message_data = {
            "link": "https://twitter.com/statuses/" + str(status.id),
            "alternative_link":
            "http://twitter.com/none/status/" + str(status.id)
        }
        self.push_service.notify_multiple_devices(
            registration_ids=registration_ids,
            message_title=message_title,
            message_body=message_body,
            data_message=message_data)
class DatabaseService:
    def __init__(self):
        self.authentication = Authentication()

    def login(self, username, password):
        result = Authentication().login(username, password)
        return result

    def register(self, data):
        result = self.authentication.register(data)
        return result

    def check_token(self, data):
        result = self.authentication.check_token(data)
        return result

    def getAll(self):
        return self.authentication.getAll()

    def getByCategory(self, category):
        return self.authentication.getByCategory(category)

    def search(self, inp):
        return self.authentication.search(inp)
Beispiel #11
0
    def __init__(self, identifier):
        """
        :param identifier: (str) search term

        Other attributes are all defaults by design.

        """
        #authorize
        self.AuthClient = Authentication()
        self.AuthClient.gettgt()

        #set attributes
        self.identifier = identifier
        self.version = "current"
        self.source = "MSH"
        self.returntype = "concept"

        #send the query and return dataframe
        self.get_query_result()
        self.df = self.parse_query_result()
Beispiel #12
0
class TwitterStreamListener(tweepy.StreamListener):
    push_service = FCMNotification(api_key=Authentication.firebase_auth_key())

    def on_status(self, status):
        registration_ids = Authentication.firebase_registration_ids()
        message_title = "Support Alert"
        message_body = status.text

        message_data = {
            "link": "https://twitter.com/statuses/" + str(status.id),
            "alternative_link":
            "http://twitter.com/none/status/" + str(status.id)
        }
        self.push_service.notify_multiple_devices(
            registration_ids=registration_ids,
            message_title=message_title,
            message_body=message_body,
            data_message=message_data)

    def on_error(self, status_code):
        if status_code == 420:
            # returning False in on_data disconnects the stream
            return False
def authenticate():
    authen = Authentication.validate_access()
    if not authen:
        abort(401)
import telebot
from Authentication import Authentication as Auth
from DataBase import EvandExcelParser as EEP
import pandas as pd
TOKEN = '691564985:AAH-B1geClWEv-cUsosVs_PldlLfQSuvd00'

bot = telebot.TeleBot(TOKEN)
auth = Auth(path_file='users_telegram/')
auth.set_state_list(['start', 'get_identication', 'complete'])
eep = EEP(file_path='list.xlsx')

users_row = dict()


def identication_parser(message):
    if auth.get_state(message) == 'start':
        return 1
    else:
        return 0


def entername_stage(message):
    if auth.get_state(message) == 'get_identication':
        return 1
    else:
        return 0


@bot.message_handler(commands=['start'])
def start_command_response(message):
    print(message.chat)
Beispiel #15
0
 def __init__(self):
     self.log = Logger()
     self .authen = Authentication()
Beispiel #16
0
    def cli_authenticate(self):

        #username = args.username
        #password = args.password

        self.AuthClient = Authentication()
class ModuleLauncher:
    def __init__(self, clientId, data, verifykey, apiEndPoint):
        self.message = data
        self.sessionkey = verifykey
        self.apiEndPoint = apiEndPoint
        self.splitUrl = apiEndPoint.split('/')
        self.auth = Authentication()
        self.master = Master()
        self.admin = Admin()
        self.role = roleManage()
        self.attendance = attendanceManage()
        self.project = projectManage()
        self.labourer = labbourerManage()
        self.labclass = labourerClass()
        self.shift = shiftManage()
        self.log = Logger()
        self.paymentDesk = paymentDesk()
        self.clientId = clientId

    def handleRequest(self):
        if self.splitUrl[0] == "master":
            return self.handleMaster()
        elif self.apiEndPoint == "/register":
            return self.master.adminRegister(self.message, self.sessionkey)

        elif self.apiEndPoint == "/companyprofile":
            return self.admin.companyProfile(self.clientId, self.sessionkey)

        elif self.apiEndPoint == "/userprofile":

            return self.admin.userProfile(self.clientId, self.message,
                                          self.sessionkey)

        else:
            return self.handleClient(self.splitUrl[0])

    def handleClient(self, clientId):
        if self.splitUrl[1] == "login":
            return self.admin.login(self.clientId, self.message,
                                    self.sessionkey)
        elif self.splitUrl[1] == "user":
            return self.handleClientUser()

        elif self.splitUrl[1] == "projects":
            return self.handleProjects()

        elif self.splitUrl[1] == "paymentDesk":
            return self.handlePaymentDesk()

        elif self.splitUrl[1] == "userrole":
            return self.roleManage()

        elif self.splitUrl[1] == "labourer":
            return self.handleLabourer()

        elif self.splitUrl[1] == "attendance":
            if self.splitUrl[2] == "list":
                return self.attendance.getAttendace(self.clientId,
                                                    self.sessionkey)
        elif self.splitUrl[1] == "logout":
            return self.auth.logout(self.message, self.sessionkey)

        elif self.splitUrl[1] == "payments":
            pass

        else:
            self.log.logEvent("ModuleLauncher", 3, "wrong url acess")
        return "url does not defined"

    def handleMaster(self):
        if self.splitUrl[1] == "login":
            return self.master.login(self.message, self.sessionkey)

        elif self.splitUrl[1] == "register":
            # digest = self.auth.signUp(self.message["password"])
            # self.message["password"] = digest["hashPassword"]
            # self.message["salt"] = digest["salt"]
            # print("message",self.message)
            # return self.master.createMaster(self.message)
            # self.log.logEvent("ModuleLauncher",3,"Master registerd")
            return self.master.createMaster(self.message, self.sessionkey)
            #return "sucess"

        elif self.splitUrl[1] == "user":
            return self.handleMasterUser()

        elif self.splitUrl[1] == "app":

            if self.splitUrl[2] == "logs":
                return self.master.fetchAppLogs(self.message, self.sessionkey)

        elif self.splitUrl[1] == "clients":
            return self.handleMasterclients()
        elif self.splitUrl[1] == "logout":
            return self.auth.logout(self.message, self.sessionkey)

        else:
            print("master can't have  this endpoint")
            self.log.logEvent("ModuleLauncher", 3,
                              "master can't have  this endpoint")
            return "master can't have  this endpoint"

    def handleMasterUser(self):
        if self.splitUrl[2] == "add":
            return self.master.addUser(self.message, self.sessionkey)

        elif self.splitUrl[2] == "delete":
            return self.master.deleteUser(self.message, self.sessionkey)

        elif self.splitUrl[2] == "list":
            return self.master.listUser(self.sessionkey)

        elif self.splitUrl[2] == "editlist":
            return self.master.mastereditList(self.message, self.sessionkey)

        elif self.splitUrl[2] == "save":
            return self.master.editUser(self.message, self.sessionkey)

        elif self.splitUrl[2] == "archive":
            return self.master.archiveUser(self.message, self.sessionkey)

        elif self.splitUrl[2] == "unarchive":
            return self.master.unArchiveUser(self.message, self.sessionkey)

        else:
            self.log.logEvent("ModuleLauncher", 3,
                              "master_user can't have  this endpoint")
            return "wrong url access1"

    def handleMasterclients(self):
        if self.splitUrl[2] == "list":
            return self.master.getRegUserDetails(self.sessionkey)

        elif self.splitUrl[2] == "editlist":
            return self.master.clienteditList(self.message)

        elif self.splitUrl[2] == 'delete':
            return self.master.deleteClient(self.message, self.sessionkey)

        elif self.splitUrl[2] == "archive":
            return self.master.archiveClient(self.message, self.sessionkey)

        elif self.splitUrl[2] == "save":
            return self.master.editClient(self.message, self.sessionkey)

        elif self.splitUrl[2] == "approve":
            return self.master.clientApprove(self.message, self.sessionkey)

        elif self.splitUrl[2] == "reject":
            self.master.rejectClients(self.message, self.sessionkey)

        else:
            self.log.logEvent("ModuleLauncher", 3,
                              "master_client can't have  this endpoint")
            return "url access error"

    def handleClientUser(self):
        if self.splitUrl[2] == "add":
            return self.admin.addUser(self.clientId, self.message,
                                      self.sessionkey)

        elif self.splitUrl[2] == "delete":
            return self.admin.deleteUser(self.clientId, self.message,
                                         self.sessionkey)

        elif self.splitUrl[2] == "save":
            return self.admin.editUser(self.clientId, self.message,
                                       self.sessionkey)

        elif self.splitUrl[2] == "archive":
            return self.admin.archiveUser(self.clientId, self.message,
                                          self.sessionkey)
        elif self.splitUrl[2] == "unarchive":
            return self.admin.unArchiveUser(self.clientId, self.message,
                                            self.sessionkey)

        elif self.splitUrl[2] == "list":
            return self.admin.listClientUser(self.clientId, self.sessionkey)
        elif self.splitUrl[2] == "roles":
            return self.admin.roleList(self.clientId, self.sessionkey)
        elif self.splitUrl[2] == "editlist":
            return self.admin.editList(self.clientId, self.message,
                                       self.sessionkey)

        else:
            self.log.logEvent("ModuleLauncher", 3,
                              "client_user can't have  this endpoint")
            return "wrong url access2"

    def handleProjects(self):
        if self.splitUrl[2] == "list":
            return self.project.listProjects(self.clientId, self.sessionkey)

        elif self.splitUrl[2] == "add":
            return self.project.projectsAdding(self.clientId, self.message,
                                               self.sessionkey)
        elif self.splitUrl[2] == "siteadd":
            return self.project.addSites(self.clientId, self.message,
                                         self.sessionkey)
        elif self.splitUrl[2] == "editList":
            return self.project.editList(self.clientId, self.message,
                                         self.sessionkey)
        elif self.splitUrl[2] == "sitedelete":
            return self.project.deletSites(self.clientId, self.message,
                                           self.sessionkey)
        elif self.splitUrl[2] == "idList":
            return self.project.projectIdList(self.clientId, self.sessionkey)
        else:
            self.log.logEvent("ModuleLauncher", 3,
                              "client_user can't have  this endpoint")
            return "wrong url access2"

    def handleLabourer(self):
        if self.splitUrl[2] == "info":
            return self.labourer.labourerInfo(self.clientId, self.message,
                                              self.sessionkey)
        elif self.splitUrl[2] == "list":
            return self.labourer.labouerList(self.clientId, self.sessionkey)

        elif self.splitUrl[2] == "personalInfo":
            return self.labourer.personalInfo(self.clientId, self.message,
                                              self.sessionkey)

        elif self.splitUrl[2] == "employeeInfo":
            return self.labourer.employeeInfo(self.clientId, self.message,
                                              self.sessionkey)

        elif self.splitUrl[2] == "identityInfo":
            return self.labourer.identityInfo(self.clientId, self.message,
                                              self.sessionkey)

        elif self.splitUrl[2] == "bankInfo":
            return self.labourer.bankInfo(self.clientId, self.message,
                                          self.sessionkey)

        elif self.splitUrl[2] == "save":
            return self.labourer.labourerReg(self.clientId, self.message,
                                             self.sessionkey)

        elif self.splitUrl[2] == "update":
            return self.labourer.editLabourer(self.clientId, self.message,
                                              self.sessionkey)

        elif self.splitUrl[2] == "delete":
            return self.labourer.deleteLabourer(self.clientId, self.message,
                                                self.sessionkey)

        elif self.splitUrl[2] == "attendance":
            return self.labourer.getAttendacePers(self.clientId, self.message,
                                                  self.sessionkey)
        elif self.splitUrl[2] == "class":
            return self.classManage()
        elif self.splitUrl[2] == "addlist":
            return self.labourer.labbourerAddlist(self.clientId,
                                                  self.sessionkey)

        elif self.splitUrl[2] == "shift":
            return self.shiftManage()

        else:
            return "wrong url access"

    def shiftManage(self):
        if self.splitUrl[3] == "add":
            return self.shift.shiftCreation(self.clientId, self.message,
                                            self.sessionkey)

        elif self.splitUrl[3] == "list":
            return self.shift.shiftList(self.clientId, self.sessionkey)

        elif self.splitUrl[3] == "delete":
            return self.shift.shiftDeleted(self.clientId, self.message,
                                           self.sessionkey)
        else:
            return "wrong url acess"

    def classManage(self):
        if self.splitUrl[3] == "list":
            return self.labclass.classList(self.clientId, self.sessionkey)

        elif self.splitUrl[3] == "add":
            return self.labclass.classAdding(self.clientId, self.message,
                                             self.sessionkey)

        elif self.splitUrl[3] == "delete":
            return self.labclass.classDelete(self.clientId, self.message,
                                             self.sessionkey)

        else:
            return "wrong url acess"

    def roleManage(self):
        if self.splitUrl[2] == "add":
            return self.role.createRoles(self.clientId, self.message,
                                         self.sessionkey)
        elif self.splitUrl[2] == "list":
            return self.role.listRoles(self.clientId, self.sessionkey)
        elif self.splitUrl[2] == "update":
            return self.role.editRoles(self.clientId, self.message,
                                       self.sessionkey)
        else:
            return "wrong url acess"

    def handlePaymentDesk(self):
        if self.splitUrl[2] == "apply":
            return self.paymentDesk.advanceApply(self.clientId, self.message,
                                                 self.sessionkey)
        elif self.splitUrl[2] == "applyList":

            return self.paymentDesk.requstList(self.clientId, self.sessionkey)
        elif self.splitUrl[2] == "payList":

            return self.paymentDesk.advancePayList(self.clientId,
                                                   self.sessionkey)

        elif self.splitUrl[2] == "approveCodeList":
            return self.paymentDesk.approvecodeList(self.clientId,
                                                    self.message,
                                                    self.sessionkey)

        elif self.splitUrl[2] == "payment":
            return self.paymentDesk.payProcess(self.clientId, self.message,
                                               self.sessionkey)

        elif self.splitUrl[2] == "status":
            return self.paymentDesk.advanceRespo(self.clientId, self.message,
                                                 self.sessionkey)

        elif self.splitUrl[2] == "approve":
            return self.paymentDesk.requstApprove(self.clientId, self.message,
                                                  self.sessionkey)

        elif self.splitUrl[2] == "reject":
            return self.paymentDesk.requstReject(self.clientId, self.message,
                                                 self.sessionkey)

        else:
            return "wrong url acess"
Beispiel #18
0
Utility functions.

"""

import time
import logging
import requests
import json
from config import settings
from Authentication import Authentication

# API-kEY FOR UMLS REST TICKET SERVICES
umls_api = settings['apis']['umls']
# UMLS REST SERVICES INITIALIZATION OF CLIENT AND TICKET
# GRANTING SERVICE TO BE USED IN ALL CASES
AuthClient = Authentication(umls_api)
tgt = AuthClient.gettgt()

logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)


def get_umls_ticket2(tgt=tgt, AuthClient=AuthClient, apikey=umls_api):
    """
    Get a single use ticket for the UMLS REST services.
    It is supposed that an Author Client and a Ticket
    Granting Service have already been set-up in case
    the apikey = None. If an api-key is given, create the
    above needed instances and generate a new ticket.
    Input:
        - apikey: str,
 def Api(self):
     self.judger = Authentication()
Beispiel #20
0
import socket

from Authentication import Authentication


def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP


auth = Authentication()
client_ip = get_ip()
username = input("User name: ")

if auth.authenticate_user(username, client_ip):
    print("user authenticated: true")
else:
    print("user authenticated: false")
# auth.publicVerification()





# pubkey = b'\x1aA)\x16\xf3\x03\x0f!\xdc/#:\xd7n\xb2\xf1\x03\x8f\xd2\xfa\x80.\x12\xf8HG\x85\xe3\x14\x0b\x159'
# # msg = "karthiban"
# cond = {"userid":"1551"}
# # data = auth.encrypt(msg,pubkey,cond)
# # print("karthihack",data)
# encmsg =  b'\x91\x12n\xd9\xdd\x19\x1d\xcd\xe6\x87\xcd\x037\x01\xa4\xbc\xbb\xf6\xda\xb9\xfaI\xa0]\xacA\xdb\xeb\xcc\xd3\x8a\x7f\xdf\xe3\xeb\xec\xad\xb2\xd9\x1f\x8d\xcfm;\x8b\x87\xfc\xc3W'
# realtext = auth.decrypt(encmsg,pubkey,cond)
# print("text",realtext)

#signup test
auth = Authentication()
#some = auth.signUp("karthiban")
auth.testing()
# print("returnvalue",some["salt"])
# print("msge=",some["hashPassword"])


# #login
# msg = {}
# msg["username"] = "******"
# msg["password"] = "******"
# tt = auth.login(msg)
# print("fg ",tt)

# print("session" ,console.sessions[sessid][0][3])
Beispiel #22
0
                writer = csv.writer(f, delimiter=";")
                writer.writerow(
                    [text, tags, user, time, location, coordinates])

                # Increment counter
                MyStreamListener.counter += 1

    def on_error(self, status_code):
        print(status_code)
        return False


if __name__ == "__main__":

    FILE_NAME = "#CoronaHoax.csv"
    api = Authentication(isApp=False).get_api()
    auth = api.auth
    myStreamListener = MyStreamListener(FILE_NAME)
    myStream = tweepy.Stream(auth=auth, listener=myStreamListener)

    try:
        print('Start streaming...')
        myStream.filter(languages=['en'],
                        track=[
                            "#CoronaHoax", "#CovidHoax", "#coronahoax",
                            "#covidhoax", "plandemic", "Plandemic",
                            "#scamdemic", "#Scamdemic", "#SCAMDEMIC"
                        ])

    except KeyboardInterrupt:
        print("Stopped.")
 def __init__(self):
     self.auth = Authentication()
     self.log = Logger()
     self.rejx = dataVerify()
class Communication:  
    def __init__(self):
        self.auth = Authentication()
        self.log = Logger()
        self.rejx = dataVerify()
        # self.modulauncher = ModuleLauncher()
        # self.launcher = ModuleLauncher()
    # def seralize(self,dicto):
    #     #self.deseralize(data_json)
    #     obj = json.dumps(dicto,default=getDict)
    #     return obj
        

    def deserialize(self, jsonData):
        try:
            deserialized = json.loads(jsonData)
            print(deserialized)
            return deserialized
        except Exception as expc:
            self.log.logEvent("communication deserialize",2,"exception ocureed"+str(expc))            

    def verifyStructure(self, msgDict):
        try:
            containsHeader = False
            containsBody = False
            containsExtraField = False
            containsSignature = False
            for key in msgDict:
                if key == "Header":
                    containsHeader = True
                elif key == "Body":
                    containsBody = True
                elif key == "Signature":
                    containsSignature = True
                else:
                    containsExtraField = True
                    break

            return containsHeader and containsSignature and containsBody and not containsExtraField
        except Exception as expc:
            self.log.logEvent("communication verify structure function",2,"exception ocureed"+str(expc))
            

    def createMessage(self, dictData, message):
        try:
            message.header = dictData["Header"]
            message.body = dictData["Body"]
            message.Signature = dictData["Signature"]
        except Exception as expc:
            self.log.logEvent("communication at create message function",2,"exception ocureed"+str(expc))            

    def sanitizeBody(self,msgBody):
        try:
            success = False
            for key in msgBody:
                if self.sanitizeString(key):
                    if type(msgBody[key]) is dict:
                        if not self.sanitizeBody(msgBody[key]):
                            return False
                        else:
                            success = True
                        self.sanitizeBody(msgBody[key])
                    else:
                        if self.sanitizeString(msgBody[key]):
                            success = True
                            continue

                        else:
                            success = False     
                else:
                    return False

            return success
        except Exception as expc:
            self.log.logEvent("communication at sanatizeBody function",2,"exception ocureed"+str(expc))

    def sanitizeHeader(self,msgheader):
        try:        
            success = True
            for msg in msgheader:
                if self.sanitizeString(msg):
                    if self.sanitizeString(msgheader[msg]):
                        continue
                    else:
                        success = False
                else:
                    success = False

            return success
        except Exception as expc:
            self.log.logEvent("communication at sanitizeHeader function",2,"exception ocureed"+str(expc))            

        

    def sanitizeString(self, stringData):
        try:
            text = str(stringData)
            print("data is" + text)
            ignore_words = [';','"','$','&&','../','*','<','>','%3C','%3E','\'','--','1,2','\x00','`','(',')','file://','input://'] 
            for ch in ignore_words: 
                if ch in text:
                    print("1false")
                    return False
            return True
        except Exception as expc:
            self.log.logEvent("communication at sanitizeString function",2,"exception ocureed"+str(expc))             
            

#######################################################################master handle#######################################################################33
    def receiveRequest(self,data,clientid,apiEndPoint):
        # try:
        print("JSON : ",data)
        msg = Message()
        signString = str(data).split("Body")[1]
        plainMsg = ((signString.split("Signature")[0])[:-2])[2:]
        dictData = self.deserialize(data)
        if self.verifyStructure(dictData):
            self.createMessage(dictData, msg)
            print("MESSAGE HEADER: ")
            for key in msg.Signature:
                print("keys ", key)
                if key == "signature":
                    print(" encrypetedkey will be there")
                elif key == "Key":
                    print("verfykey will  be there")
                else:
                    self.log.logEvent("Communication",3,"signatrue part is missing")
                    print("signature missing  there")
                    return "signature missing  there"
            verifyKey = msg.Signature["Key"]
            signature = msg.Signature["signature"]
            contStr = ""            
            # print("signString..........................",plainMsg)
            # sigtest = self.auth.signatureVerify(verifyKey, signature,plainMsg)
            # print("Signature Verified::::::::::::::::::::::::::::::::::::::", sigtest)
            if self.auth.signatureVerify(verifyKey, signature,plainMsg):
                if self.rejx.verifyData(msg.body):
                    if clientid == "signup" :
                        modLauncher = ModuleLauncher(clientid, msg.body,verifyKey,'/register')
                        return modLauncher.handleRequest()
                    elif clientid == "masterregister":
                        modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                        return modLauncher.handleRequest()                        
                    elif clientid == "master":
                        modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                        # return modLauncher.handleRequest()
                        resDict =  modLauncher.handleRequest()
                        body = resDict["Body"]
                        print("body part is....",body)
                        jsnfyBody = json.dumps(body)
                        print("jsnfyBody) = ",jsnfyBody)
                        if resDict["Header"]["status"] == "success":
                            signkey1 = sessionMange.session[verifyKey]["signkey"]
                            verifykey1 = sessionMange.session[verifyKey]["verifykey"]
                            print("verifykey type",type(verifykey1))
                            verify_key_hex =verifykey1.encode(encoder=nacl.encoding.HexEncoder)
                            print("signature private key type",type(signkey1))
                            print("type(jsnfyBody) = ", type(jsnfyBody))
                            sessionSign = signkey1.sign(jsnfyBody.encode("utf-8"))
                            print("sessionkey type",type(sessionSign))
                            print("sessionkey ............on backend",sessionSign)
                            sHexSignature = binascii.hexlify(bytes(sessionSign))
                            resDict["Signature"]["signature"] = (sHexSignature)
                            resDict["Signature"]["Key"] = (verify_key_hex)
                            print("siggened signature message................................",resDict)
                            return resDict                        
                    elif apiEndPoint == "/login":
                        # modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                        # return modLauncher.handleRequest()
                        try:
                            modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                            resDict =  modLauncher.handleRequest()
                            body = resDict["Body"]
                            print("body part is....",body)
                            jsnfyBody = json.dumps(body)
                            print("jsnfyBody) = ",jsnfyBody)
                            if resDict["Header"]["status"] == "success":
                                signkey1 = sessionMange.session[verifyKey]["signkey"]
                                verifykey1 = sessionMange.session[verifyKey]["verifykey"]
                                print("verifykey type",type(verifykey1))
                                verify_key_hex =verifykey1.encode(encoder=nacl.encoding.HexEncoder)
                                print("signature private key type",type(signkey1))
                                print("type(jsnfyBody) = ", type(jsnfyBody))
                                sessionSign = signkey1.sign(jsnfyBody.encode("utf-8"))
                                print("sessionkey type",type(sessionSign))
                                print("sessionkey ............",sessionSign)
                                sHexSignature = binascii.hexlify(bytes(sessionSign))
                                resDict["Signature"]["signature"] = (sHexSignature)
                                resDict["Signature"]["Key"] = (verify_key_hex)

                            return resDict 
                        except Exception as expc:
                            print("expection",expc)                      
                            response = {"Header":{"status":"fail","module":"communication"},"Body":{"message":"wrong username or password","data":""},"Signature":{"signature":"","Key":""}}
                            return response                          
                    elif apiEndPoint == "/logout":
                        modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                        return modLauncher.handleRequest()                    
                        # resDict =  modLauncher.handleRequest()
                        # body = resDict["Body"]
                        # print("body part is....",body)
                        # jsnfyBody = str(jsonify(body))
                        # signkey1 = sessionMange.session[verifyKey]["signkey"]
                        # verifykey1 = sessionMange.session[verifyKey]["verifykey"]
                        # verify_key_hex =verifykey1.encode(encoder=nacl.encoding.HexEncoder)
                        # print("signature private key type",type(signkey1))
                        # print("type(jsnfyBody) = ", type(jsnfyBody))
                        # sessionSign = signkey1.sign(jsnfyBody.encode("utf-8"))
                        # print("sessionkey type",type(sessionSign))
                        # sHexSignature = binascii.hexlify(bytes(sessionSign))
                        # resDict["Signature"]["signature"] = (sHexSignature)
                        # resDict["Signature"]["Key"] = (verify_key_hex)
                        # return resDict                    
                    elif self.auth.uRolePermissionCheck(clientid,apiEndPoint,verifyKey) :
                        # try:
                        modLauncher = ModuleLauncher(clientid,msg.body,verifyKey, apiEndPoint)
                        resDict =  modLauncher.handleRequest()
                        body = resDict["Body"]
                        print("body part is....",body)
                        jsnfyBody = json.dumps(body)
                        print("jsnfyBody) = ",jsnfyBody)
                        if resDict["Header"]["status"] == "success":
                            signkey1 = sessionMange.session[verifyKey]["signkey"]
                            verifykey1 = sessionMange.session[verifyKey]["verifykey"]
                            print("verifykey type",type(verifykey1))
                            verify_key_hex =verifykey1.encode(encoder=nacl.encoding.HexEncoder)
                            print("signature private key type",type(signkey1))
                            print("type(jsnfyBody) = ", type(jsnfyBody))
                            sessionSign = signkey1.sign(jsnfyBody.encode("utf-8"))
                            print("sessionkey type",type(sessionSign))
                            print("sessionkey ............",sessionSign)
                            sHexSignature = binascii.hexlify(bytes(sessionSign))
                            resDict["Signature"]["signature"] = (sHexSignature)
                            resDict["Signature"]["Key"] = (verify_key_hex)
                        return resDict     
                        # except Exception as expc:
                        #     print("expection",expc) 
                        #     self.log.logEvent("communication",2,"role checking function ")        
                else:
                    print(">>............................wrong datastructure")
                    return " wrong datastructure at communication"                           
                    
            else:
                self.log.logEvent("Communication",3,"signature is wrong")
                return "error occured"            
        elif self.sanitizeBody(msg.body) and self.sanitizeHeader(msg.header):
            print("Message body verified")
        else:
            self.log.logEvent("Communication",3,"invalied requst formate")
            print("Invalid body structure format ")
            return "Invalid body structure format "
 def login(self, username, password):
     result = Authentication().login(username, password)
     return result
 def __init__(self):
     self.authentication = Authentication()
Beispiel #27
0
class RackSpaceClient:
    VALID_HTTP_METHODS = ("GET", "POST", "DELETE", "PUT")

    # Authentication object
    auth = None

    # Default headers
    headers = {"Content-Type": "application/json", "Accept": "application/json"}

    connection = None

    def __init__(self, user, key):
        self.auth = Authentication(user, key)
        try:
            self.auth.doLogin()
        except RackSpaceAuthenticationFailedException:
            print "Invalid credentials was provided!"
            self.auth = None
        except RackSpaceException:
            print "Error during auth procedure"
            # sys.exit(1)
            self.auth = None
        self.updateAuthToken(self.auth.getAuthToken())
        # print self.headers

    def updateAuthToken(self, token):
        self.headers.update({"X-Auth-Token": token})

    def makeConnection(self, hostname, port):
        self.closeConnection()
        self.connection = HTTPSConnection(hostname, port)

    def closeConnection(self):
        if self.connection is not None:
            self.connection.close()

    def SendRequest(self, rType, method, data, params):
        # Send API request

        if rType not in self.VALID_HTTP_METHODS:
            # Invalid request method
            raise RackSpaceException()

        uri = urlparse.urlparse(self.auth.getServerManagementURL())

        headers = self.headers.copy()
        if isinstance(params, dict):
            headers.update(params)

        def make_request():
            self.makeConnection(uri.hostname, uri.port)
            self.connection.request(rType, self.auth.getServerManagementURL() + method, data, headers)
            resp = self.connection.getresponse()
            return resp

        response = make_request()

        # 401 == unauthorized
        if response.status == 401:
            try:
                self.auth.doLogin()
                # retry request
                response = make_request()
            except RackSpaceException:
                self.closeConnection()
                raise

        #        if response.status == 413:
        #            raise RackSpaceOverLimitException()
        #        if response.status == 400 or response.status == 500:
        #            raise RackSpaceCloudServersFaultException()
        #        if response.status == 503:
        #            raise RackSpaceServiceUnavailableException()

        result = {"code": response.status, "body": response.read()}
        self.closeConnection()

        return result
Beispiel #28
0
def auth(callback: Callable, request: request, admin: bool = True, id_user: bool = False) -> tuple:
	authentication = Authentication(admin)
	if (authentication.is_authenticated(request)):
		return callback(authentication.get_id_user()) if id_user else callback()
	else:
		return Response(ResponseType.INVALID_CREDENTIALS).message()
Beispiel #29
0
import sys

# My libraries
from Authentication import Authentication
from HarvestingTweets import BasicHarvestTweets
from GatherTweets import GatherTweetsByWords, GatherTweetsByAccounts

if __name__ == "__main__":
    data_path = "/home/user/TwitterData"
    auth = Authentication()

    if sys.argv[1] == "words":
        gtw = GatherTweetsByWords(BasicHarvestTweets(auth.auth, auth.api),
                                  ["startups", "machinelearning"])
        gtw.gatherTweets(data_path, "words")

    elif sys.argv[1] == "accounts":
        gta = GatherTweetsByAccounts(BasicHarvestTweets(auth.auth, auth.api),
                                     ["Forbes", "businessinsider"])
        gta.gatherTweets(data_path, "accounts")

    else:
        print(sys.argv[1] + " not implemented...")
Beispiel #30
0
class CLI:
    """
    Command-line interface for querying single terms.
    More flexible, keeping around for potential future use/historical reasons.
    """

    def __init__(self, argv=None):
        """
        :param argv: for testing purposes only

        """
        self.parser = argparse.ArgumentParser(description='process user given parameters')
        #parser.add_argument("-u", "--username", required =  True, dest="username", help = "enter username")
        #parser.add_argument("-p", "--password", required =  True, dest="password", help = "enter passowrd")
        self.parser.add_argument("-k", "--apikey", required = False, dest = "apikey",
                                 default = os.environ.get("APIKEY"),
                                 help = "enter api key from your UTS Profile")
        self.parser.add_argument("-v", "--version", required = False, dest="version",
                                 default = "current", help = "enter version example-2015AA")
        self.parser.add_argument("-i", "--identifier", required = True, dest="identifier",
                                 help = "enter identifier example-C0018787")
        self.parser.add_argument("-s", "--source", required = False, dest="source",
                                 default = 'MSH', help = "enter source name if known")
        self.parser.add_argument("-r", "--returntype", required = False, dest='returntype',
                                 default = "concept",
                                 help = "choose return type (‘aui’,‘concept’,‘code’,\
                                        ‘sourceConcept’,‘sourceDescriptor’, ‘sourceUi’)")

        if argv is not None:
            self.args = self.parser.parse_args(argv)
        else:
            self.args = self.parser.parse_args()

    def cli_authenticate(self):

        #username = args.username
        #password = args.password

        self.AuthClient = Authentication()

    def construct_query(self):

        self.version = self.args.version
        self.identifier = self.args.identifier
        self.source = self.args.source
        self.returntype = self.args.returntype
        self.AuthClient.gettgt()

    def get_query_result(self):
        """
        Search by human-readable string.

        :return: concepts
        """

        self.construct_query()

        uri = "https://uts-ws.nlm.nih.gov"
        content_endpoint = "/rest/search/{0}?string={1}&sabs={2}&returnIdType={3}".format(
                           self.version, self.identifier, self.source, self.returntype)

        self.query = {'ticket':self.AuthClient.getst()}

        r = requests.get(uri+content_endpoint, params=self.query)

        items = json.loads(r.text)
        self.jsonData = items["result"]

        #print(self.jsonData)

        ##uncomment the print statment if you want the raw json output, or you can just look at the documentation :=)
        #https://documentation.uts.nlm.nih.gov/rest/concept/index.html#sample-output
        #https://documentation.uts.nlm.nih.gov/rest/source-asserted-identifiers/index.html#sample-output
        #print (json.dumps(items, indent = 4))

    def parse_query_result(self):
        """
        Extract name and unique id from results.

        :return: pandas dataframe
        """
        results = self.jsonData['results']

        df = pd.DataFrame(results)
        df.drop(['rootSource', 'uri'], axis=1, inplace=True)

        return df
Beispiel #31
0
import Authentication.Authentication as aut
import Manager.RepoManager as repom
import json

user = aut.login()


class CommandsClass:
    def commands(catcher):
        n = 0
        print("----- COMMANDS -----\n")
        with open("Commands\\Commands.json") as f:
            for command in json.load(f)["commands"]:
                print("({}): {}".format(n, command))
                n += 1

    def repos(catcher):
        print("----- REPOSITORIES -----")
        repom.list_repos(user)

    def create(name):
        repom.create_repo(user, name)

    def fpush(args):
        repom.fpush(user, args)

    def edit(args):
        repom.edit(user, args)
Beispiel #32
0
class Admin:
    def __init__(self):
        self.log = Logger()
        self.authen = Authentication()

    def addUser(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        digest = self.authen.signUp(msgDict["password"])
        msgDict["password"] = digest["hashPassword"]
        msgDict["salt"] = digest["salt"]
        print("message", msgDict)
        # admin = Admin()
        nameLs = []
        valueLs = []
        for key, val in msgDict.items():
            nameLs.append(key.lower())
            valueLs.append(val)
        print(nameLs)
        print(valueLs)
        reval = False
        try:
            if not adminDb.fetchData("clientusers", ["username"],
                                     {"username": msgDict["userName"]}):
                if adminDb.pushData("clientusers", nameLs, valueLs):
                    self.log.logEvent(
                        "Admin", 1, msgDict["userName"] +
                        " Client user registerd successfully", clientId,
                        msgDict["userName"])
                    response = {
                        "Header": {
                            "status": "success",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user added successfully",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response
                else:
                    self.log.logEvent(
                        "Admin", 1, msgDict["userName"] +
                        "Client user registerd failed and eception is occured")
                    response = {
                        "Header": {
                            "status": "success",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user can't added ",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response
            else:
                self.log.logEvent(
                    "Admin", 1,
                    msgDict["userName"] + "Client user name alraedy exist",
                    clientId, msgDict["userName"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "user name already exixt ",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response

        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc))
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def login(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        fileds = ["username", "password"]
        con = {"clientid": clientId}
        data = masterDb.fetchData("regusers", fileds, con)
        print("........................", data)
        datalis = [clientId, clientId, data[0][1], 5432]
        print("...datalis...........", datalis)
        adminDb = DatabaseAgent(clientId, clientId, conf.host, data[0][1],
                                5432)
        adminDb.initConnection()
        try:
            statusFlag = masterDb.fetchData("regusers", ["status"],
                                            {"clientid": clientId})
            if statusFlag[0][0] == "approved":
                #####################################################################
                filedLs = ["password", "salt", "employeeid", "userrole"]
                if self.authen.login(msgDict, "clientusers", filedLs, datalis,
                                     sessionkey):
                    adminDb = DatabaseAgent(clientId, clientId, conf.host,
                                            data[0][1], 5432)
                    adminDb.initConnection()
                    userid = adminDb.fetchData(
                        "clientusers", ["employeeid"],
                        {"username": msgDict["userName"]})
                    archiveflag = adminDb.fetchData(
                        "clientusers", ["archive"],
                        {"username": msgDict["userName"]})
                    print("boolean value", archiveflag)
                    if archiveflag:
                        self.log.logEvent("Admin", 3,
                                          "user logined suceessfully",
                                          clientId, msgDict["userName"])
                        response = {
                            "Header": {
                                "status": "success",
                                "module": "admin"
                            },
                            "Body": {
                                "message": "user login successfully",
                                "data": userid
                            },
                            "Signature": {
                                "signature": "",
                                "Key": ""
                            }
                        }
                        return response
                    else:
                        self.log.logEvent(
                            "Admin", 3,
                            "your archived please connact to the admin",
                            clientId, msgDict["userName"])
                        response = {
                            "Header": {
                                "status": "fail",
                                "module": "admin"
                            },
                            "Body": {
                                "message":
                                "your archived please connact to the admin",
                                "data": ""
                            },
                            "Signature": {
                                "signature": "",
                                "Key": ""
                            }
                        }
                        return response
                else:
                    self.log.logEvent("Admin", 3, "user logined error",
                                      clientId, msgDict["userName"])
                    response = {
                        "Header": {
                            "status": "fail",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "wrong username or password",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response

            elif statusFlag[0][0] == "rejected":
                self.log.logEvent("Admin", 3, "comapny is rejected", clientId,
                                  msgDict["userName"])
                response = {
                    "Header": {
                        "status": "fail",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "your comapny is rejected",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response

            else:
                self.log.logEvent("Admin", 3, "comapny has not been approved",
                                  clientId, msgDict["userName"])
                response = {
                    "Header": {
                        "status": "fail",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "your comapny has not been approved",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response

        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId, msgDict["userName"])
            # self.syslog.eventHandle("admin","exception","exception on admin module"+str(expc))

    def editUser(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        condition = {"employeeid": msgDict["employeeId"]}
        changDist = {}

        for key in msgDict:
            if key == "emplyeeId":
                continue
            else:
                changDist[key.lower()] = (msgDict[key])
        try:

            if adminDb.editData("clientusers", changDist, condition):
                self.log.logEvent(
                    "Admin", 2,
                    msgDict["employeeId"] + "user edited successfully",
                    clientId, sessionMange.session[sessionkey]["userid"])
                # datalis = ["fullname","employeeid","designation","emailid","userrole",'archive']
                # adminDb.fetchData("clients",datalis)
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "user deatils edited successfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response

            else:
                self.log.logEvent("Admin", 2, "user cant edited", clientId,
                                  sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "user deatils can't edited ",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def deleteUser(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        delete = " set delete = 'True' where "
        datdict = {"employeeid": msgDict["employeeId"]}
        try:
            if msgDict["employeeId"] == "kcemp1001":
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "admin can't be delete",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                if adminDb.updateTable(delete, "clientusers", datdict):
                    self.log.logEvent(
                        "Admin", 2, msgDict["employeeId"] +
                        "Client user deletd successfully", clientId,
                        sessionMange.session[sessionkey]["userid"])
                    response = {
                        "Header": {
                            "status": "success",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user delete successfully",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response  #self.listClientUser()
                else:
                    self.log.logEvent(
                        "Admin", 2,
                        msgDict["employeeId"] + "Client can't user deleted ",
                        clientId, sessionMange.session[sessionkey]["userid"])
                    response = {
                        "Header": {
                            "status": "success",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user can't delete",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def archiveUser(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        archive = " set archive = 'True' where "
        admin = Admin()
        datdict = {"employeeid": msgDict["employeeId"]}
        try:
            if msgDict["employeeId"] == "kcemp1001":
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "admin can't be archived",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                if adminDb.updateTable(archive, "clientusers", datdict):
                    self.log.logEvent(
                        "Admin", 2,
                        msgDict["employeeId"] + "Client archived successfully",
                        clientId, sessionMange.session[sessionkey]["userid"])
                    response = {
                        "Header": {
                            "status": "success",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user archived successfully",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response

                else:
                    self.log.logEvent(
                        "Admin", 2,
                        msgDict["employeeId"] + "Client canot archived",
                        clientId, sessionMange.session[sessionkey]["userid"])
                    response = {
                        "Header": {
                            "status": "fail",
                            "module": "admin"
                        },
                        "Body": {
                            "message": "user can't archived ",
                            "data": ""
                        },
                        "Signature": {
                            "signature": "",
                            "Key": ""
                        }
                    }
                    return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId, msgDict["employeeId"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc)

    def unArchiveUser(
        self,
        clientId,
        msgDict,
    ):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        archive = " set archive = 'False' where "
        admin = Admin()
        datdict = {"employeeid": msgDict["employeeId"]}
        try:
            if adminDb.updateTable(archive, "clientusers", datdict):
                self.log.logEvent(
                    "Admin", 2,
                    msgDict["employeeId"] + "Client archived successfully",
                    clientId, sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "success",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "user unarchived successfully",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
            else:
                self.log.logEvent(
                    "Admin", 2,
                    msgDict["employeeId"] + "Client canot archived", clientId,
                    sessionMange.session[sessionkey]["userid"])
                response = {
                    "Header": {
                        "status": "fail",
                        "module": "admin"
                    },
                    "Body": {
                        "message": "user can't unarchived ",
                        "data": ""
                    },
                    "Signature": {
                        "signature": "",
                        "Key": ""
                    }
                }
                return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def editList(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        condition = {"employeeid": msgDict["employeeId"]}
        datalis = [
            "fullname", "employeeid", "designation", "emailid", "userrole",
            'archive'
        ]
        cliList = adminDb.fetchData("clientusers", datalis, condition)
        infolist = []
        try:
            for info in cliList:
                for tup in info:
                    infolist.append(tup)
            role = adminDb.fetchData("permission", ["rolename", "roleid"])
            infolist.append(role)
            self.log.logEvent("Admin", 2,
                              "edit button wanted listed successfully",
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            response = {
                "Header": {
                    "status": "success",
                    "module": "admin"
                },
                "Body": {
                    "message": "user edit list",
                    "data": infolist
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def roleList(self, clientId, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        self.log.logEvent("Admin", 2,
                          "total permission list listed successfully",
                          clientId, sessionMange.session[sessionkey]["userid"])
        try:
            responseData = adminDb.fetchData("permission",
                                             ["rolename", "roleid"])
            response = {
                "Header": {
                    "status": "success",
                    "module": "admin"
                },
                "Body": {
                    "message": "user role list",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def listClientUser(self, clientId, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        print(".................", dbData)
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        datalis = [
            "fullname", "employeeid", "designation", "userrole", 'archive'
        ]
        self.log.logEvent("Admin", 0, "Client user listed successfully",
                          clientId, sessionMange.session[sessionkey]["userid"])
        try:
            responseData = adminDb.fetchData("clientusers", datalis)
            print("dbdata is................................", responseData)
            response = {
                "Header": {
                    "status": "success",
                    "module": "admin"
                },
                "Body": {
                    "message": "user list",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def userProfile(self, clientId, msgDict, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        dbCompanyname = masterDb.fetchData("regusers", ["companyname"], cond)
        print(".................", dbData)
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        conditions = {"employeeid": msgDict["employeeId"]}
        detail = ["fullname", "employeeid", "userrole", "designation"]
        self.log.logEvent("Admin", 0, "user profile showed", clientId,
                          msgDict["employeeId"])
        try:
            responseData = adminDb.fetchData("clientusers", detail, conditions)
            print("response data", responseData)
            responseData.append(dbCompanyname[0][0])
            response = {
                "Header": {
                    "status": "success",
                    "module": "admin"
                },
                "Body": {
                    "message": "user profile",
                    "data": responseData
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

######################################################companyprofile#######################################################

    def companyProfile(self, clientId, sessionkey):
        masterDb = DatabaseAgent(conf.mdbName, conf.muserName, conf.host,
                                 conf.mdbPassword, conf.port)
        masterDb.initConnection()
        cond = {"clientid": clientId}
        dbData = masterDb.fetchData("regusers", ["password"], cond)
        password = dbData[0][0]
        adminDb = DatabaseAgent(clientId, clientId, conf.host, password, 5432)
        adminDb.initConnection()
        try:
            compnydata = self.fetchCompanySummary(adminDb)

            projectsColl = self.fetchProjectsSummary(adminDb)

            finalList = []
            finalList.append(list(compnydata))
            finalList.append(list(projectsColl))
            self.log.logEvent("Admin", 2, "Company pofile sended successfully",
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            print("final list is...", finalList)
            response = {
                "Header": {
                    "status": "success",
                    "module": "admin"
                },
                "Body": {
                    "message": "companyprile",
                    "data": finalList
                },
                "Signature": {
                    "signature": "",
                    "Key": ""
                }
            }
            return response
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def fetchCompanySummary(self, dbAgent):
        condition = {"userrole": "Admin"}
        dataList = ["fullname", "employeeid", "designation", "companyname"]
        try:
            return dbAgent.fetchData("clientusers", dataList, condition)
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))

    def fetchProjectsSummary(self, dbAgent):
        projCollection = []
        projectData = dbAgent.fetchData("projects",
                                        ["Projectname", "projectid"])
        # print("\n\n\n")
        try:
            for i in range(len(projectData)):
                cond = {"projectid": projectData[i][1]}
                curSite = dbAgent.fetchData("sites", ["sitenames"], cond)
                lCount = dbAgent.fetchData("sites", ["numOfLabourer"], cond)
                # print("\n\n\nSites:::::::::::: ", curSite)
                # print("\nSites:::::::::::::: ", curSite[0])
                # print("\nSites:::::::::::::: ", curSite[0][0])
                projectSummary = [[], []]

                for j in range(len(curSite)):
                    # print ("\n\n\n\nJ:::::::    ", j)
                    sitesList = curSite[j][0]
                    labourerList = lCount[j][0]
                    projectSummary[-1].append(sitesList)
                    projectSummary[-2].append(labourerList)

                projectSummary.insert(0, projectData[i][0])
                projCollection.append(projectSummary)
                #del labourerList[:]
                #del sitesList[:]
                # print("Project Summary:::::::::::::::::::::::::::::::: ", projectSummary)
                # print("sites..........  ",sitesList)
                # print("lab........................  ",labourerList)
                # print("\n\n\n")

            print("PROJECTS CONTAINER:::::::::::::::::::::::::: ",
                  projCollection)

            return projCollection
        except Exception as expc:
            self.log.logEvent("Admin", 0, "occured exception is " + str(expc),
                              clientId,
                              sessionMange.session[sessionkey]["userid"])
            # self.syslog.eventHandle("admin","exception","exception on admin module",str(expc))


#################################################################permissions#########################################

##################################################################attendance############################################################################

######################################################################company management################################################

# try:
#     reval

# except Exception as expc:
#     print("oocured exception is",expc)

# admin = Admin()
# print("companyprofile.....",admin.companyProfile("kec119","karthiban"))

# # print(admin.classList("sessionkey"))
# # # print("....................",admin.labbourerAddlist("karthiban"))
# # admin.roleList("sessionkey")
# # print("list is..........",admin.listRoles("sessionkey"))
# # print("datasss.....................................",admin.listRoles())

# # sessions["xyzabcd"] = ["karthiban","karthi007"]

# # # admin.adminRegister({"userName":"******","fullName":"karthibanvediraj","emailId":"*****@*****.**","companyName":"admin","employId":"k1551","designation":"softwaredeveloper","password":"******"})
# # admin.createRoles()
# # ###################labourer reg###################################
# # data = {"labourername":"spartan","callbyname":"spartan","gender":"male","dateofbirth":"07/07/1997","fathername":"spartan","bloodgroup":"a1+","nextofkin":"ben","contactnumberofnextofkin":"155525145522","mothertounge":"tamil","addressline1":"address","addressline2":"somthing2","addressline3":"somthing","village":"newyear","state":"newyark","country":"usa","pincode":"600000" ,"mobilenumber":"666575454654656","residancephonenumber":"456518555472320","emergencyphonenumber":"45545554360","dateofjoining":"09/04/1993" ,"migrantworker":"yes" ,"siteid":"usa" ,"siteofjoining":"05/03/2019","designation":"admin","labourerclass":"best","wageclass":"good","documenttype":"adhar","documentnumber":"2585685758120","nameasperdoc":"spartan","bankname":"national","ifsccode":"55365845435520","backaccountnumber":"546546544420","brancname":"usa","nameinbank":"indian"}
# # print("datais",admin.labourerReg(data))
# ###############################################labourerlist########################################
# #print("list labourer",admin.labourerInfo())
# ######################labourer change##############################################################
# # data = {"labourerId":""}
# shift = {"shiftstart":"12:00","shiftend":"07:00","break1start":"00:00","break1end":"04:00","lunchbreakstart":"03:00","lunchbreakend":"00:00","break2start":"00:00","break2end":"04:00"}
# # admin.labourerChange()
# admin.shiftCreation(shift,"sessionkey")
# #print("list of shift",admin.shiftList())
# # shiftedit = {"shiftId":"shift1001","lunchstart":"07:00"}
# # print("list of shift",admin.shiftEdit(shiftedit))
# # shiftdelete = {"shiftId":"shift1003"}
# # print("list of shift",admin.shiftDeleted(shiftdelete))
# # print("company profile page",admin.shiftAssingn(shiftdelete))
# # print("njnkjnbkjbkjbkj",admin.companyProfile())
# #