Example #1
0
def checkTheamLicence(licencesType: str):

    # thre return has this shap:
    #   If OK ["Ok", LicenceID, Current ActiveLicence]
    #   IF Ok but the use has no valide licence ["Reject", LicenceID]

    if licencesType == 'T' or licencesType == 'E':
        None
    else:
        return ['err', 'Unknown licences Type']

    db = SqlConn.ConnectToDB()
    dbAnswer = SqlConn.SendSQL(
        db, "SELECT * FROM licences WHERE type='" + licencesType +
        "' AND CreatedFor=" + session['UserID'])
    db.close()

    if 'err' in dbAnswer:
        return ['err', 'No Licence']
    else:
        # Check if still has more to use
        # if (ActivatedCount) < ( MaxUsingCount )
        #print(dbAnswer[0][2],dbAnswer[0][3] )
        if int(dbAnswer[0][2]) < int(dbAnswer[0][3]):
            # Return the licence ID, ActivatedCount
            return ['OK', dbAnswer[0][0], dbAnswer[0][2]]
        else:
            return ['Rejected', dbAnswer[0][0]]
Example #2
0
def emailVerfication():

    if request.method == 'POST':
        FullInData = json.dumps(request.form)
        FullInData = json.loads(FullInData)
        inVerCode = Checking.RemoveUnwantedChar(FullInData['VerCode'])

        print(FullInData)

        if len(inVerCode) == 8:
            myDB = SqlConn.ConnectToDB()

            para = {"VarCard": inVerCode}
            SQLResult = SqlConn.SendSQL(myDB, "SELECT `userid` FROM `verifications` WHERE `vercode` = %(VarCard)s AND `enddate` > NOW()" \
                                        , parameters=para)

            if SQLResult != None:
                SqlConn.SendSQL(myDB, "UPDATE `ourusers` SET `verified`=TRUE WHERE `userid`='" + str(SQLResult[0][0]) + "'", \
                                returnDate=False)
                myDB.close()
                if 'WEB' not in FullInData:
                    return beecFunc.ReturnResponse("OK")
                else:
                    return flask.send_from_directory("HTML", "loginpage.html")

        if 'WEB' not in FullInData:
            return beecFunc.ReturnResponse("Wrong code!")
        else:
            return flask.send_from_directory("HTML", "EmailVerifcation.html")
    else:
        if 'WEB' not in request.form:
            return beecFunc.ReturnResponse("Wrong code!")
        else:
            return flask.send_from_directory("HTML", "EmailVerifcation.html")
Example #3
0
def AddNewTheam(ThemName: str, TheamInfo: str, ThemStyleID: int, DeptID: int):

    # NOT TEST AT ALL
    # Theam info is a JSON object that has all needed info for the insertion query
    # - theamname
    # - TheamInfo
    # - forDepartment

    # Retun the new inserted theam number

    LicenceCheck = checkTheamLicence('T')

    if 'OK' not in LicenceCheck:
        return ['err', 'Licence Rejection']

    db = SqlConn.ConnectToDB()

    InserSQL = "INSERT INTO `theam`(`theamname`, `colorcodes`, `StyleID`, `createdby`, `forDepartment`, `licenceid`)" \
                        " VALUES (" + ThemName + "," + TheamInfo + "," + str(ThemStyleID) + "," + session["UserID"] + \
                        "," + str(DeptID) + "," + LicenceCheck[1] + ")"

    TheamID = SqlConn.InsertSQL(Conn=db, SQLStatment=InserSQL)

    db.close()

    # NOTE: Licenect update is done automatically by the databse enginge

    if 'err' in TheamID:
        return TheamID
    else:
        return ['OK', TheamID]
Example #4
0
def updateSingleTable(tableName:str, newData:json, condationFeild:str , exceptionColumn = []):

    # tableName: the target to update table
    # newData: a jason or dict var that will handle the new data that need to be update with the feild names
    # condationFeild: This will be use in the WHERE close of the UDPATE SQL statment to limit the update
    # exceptionColumn: a list of feild names that the funcion should ignore when creating the SQL. Note that, the funcion will
    #       use the newData for feild names and the table's feild that will be extracted form the data base while ignoreing
    #       the ones in exceptionColumn.

    db = SqlConn.ConnectToDB()

    # Get employee tabel feilds name
    EmpTableFeildsName = SqlConn.SendSQL(db, "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE " \
                + "`TABLE_SCHEMA`='" + SqlConn.getDatabaseName() + "' AND `TABLE_NAME`='" + tableName + "'")

    # Craft the UPDATE SQL
    SqlStatment = "UPDATE `" + tableName + "` SET "
    firstComa = False

    # Loop through the feilds
    for oneFeild in EmpTableFeildsName:

        # Remove any unwanted data
        if oneFeild[0] in exceptionColumn or oneFeild[0] == condationFeild:
            continue

        # Attach the new field
        if oneFeild[0] in newData:
            if str(newData[oneFeild[0]]).upper() == "NONE" or newData[oneFeild[0]] == "":
                continue

            # Handle the first adding comma to the sql
            if firstComa:
                SqlStatment = SqlStatment + "',"
            SqlStatment = SqlStatment + "`" + str(oneFeild[0]) + "`='" + str(newData[oneFeild[0]])

            firstComa = True

    SqlStatment = SqlStatment.strip()
    if SqlStatment[len(SqlStatment)-1] != "'":
        SqlStatment = SqlStatment + "'"

    SqlStatment = SqlStatment + " WHERE `" + condationFeild + "`='" + str(newData[condationFeild]) + "'"

    print(SqlStatment)

    finalUpdateResult = SqlConn.SendSQL (db, SqlStatment, returnDate=False)

    db.close()

    if 'err' in finalUpdateResult:
        return ["err", "Update failed", finalUpdateResult, SqlStatment]
    else:
        if finalUpdateResult[1] == 0:
            # The Update was ok, but it affact no column. Meaning, there is new data need to be inserted
            return ["NO Effect", "No Rows were affected"]
        else:
            return ["OK", ""]
Example #5
0
def NewCard(InJSON: json):

    db = SqlConn.ConnectToDB()

    print("WE ARE HERE")

    # The comming JSON to this funcion should contian three jason inside it [CardInfo, TheamInfo, ThemName, Feilds]
    # Extrat the full card Info
    CardInfoJson = json.dumps(InJSON['CardInfo'])
    CardInfoJson = json.loads(InJSON['CardInfo'])

    # Extract the Theam Info,
    # Should have the shape of [0-0-0:0-0-0:0-0-0] = [R-G-B:R-G-B:R-G-B] = [FontColor:BackgroundColor:FrameColor]

    # Extract the card's Selected feilds of shape [Feild:Feild: ...]
    # FeildsString = InJSON['Feilds']

    # 1. Create and add the company ( From the card info passed )
    #       - Check if company exisit
    #       - Check if the emplyee have a company
    # DONE IN THE PREVIOUS STEP

    # Update the info to the database ( This function should make the the new needed fields also)
    r = updateFullInfo(CardInfoJson)
    if r[0] != "OK":
        # Error is return
        print(str(r))
        return r
    else:
        # Update the JSON Object with the new data from the function as the function might have changed accrodingly
        InJSON = r[1]

    # 2. Create and add the theme if needed
    #       - Check if the comapny has the enough theam licene
    #       - Theam(String that tell what colors seperated with '-', ORDER: Background, FontColor, BoarerColor) d
    #                           (COLORS ARE IN R, G, B for each '-' string)

    TheamID = AddNewTheam(ThemName=InJSON['ThemName'],
                          TheamInfo=InJSON['Theam'],
                          ThemStyleID=InJSON['StyleID'],
                          DeptID=CardInfoJson['departementid'])

    if TheamID[0] == 'err':
        return TheamID
    else:
        TheamID = TheamID[1]

    # 3. Create and add the card
    #       - Check if user have the correct licence for the number of cards allowed
    #       - Set the new card as the default card

    cardInsertSQL = "INSERT INTO `cards`(`isprivate`, `visitcounter`, `foremployee`, `applytheamid`, `INFO`) " \
                    "VALUES (0, 0,'" + str(session['EmpID']) + "'," + str(TheamID) \
                    + "'," + str(InJSON["Feilds"]) + "')"

    print("Card Insertion SQL:", str(cardInsertSQL))

    return ["err", "Not Done yet"]
Example #6
0
def addImageToDB(FileName: str, ImageName: str):

    db = SqlConn.ConnectToDB()

    SQLs = "INSERT INTO imgsave (`Path`, `UploadedBy`, `ImageName`, `type`) VALUES " + \
           "('" + FileName + "','" + str(session['UserID']) + "','" + ImageName + "', 'F')"
    return SqlConn.InsertSQL(db, SQLs)


# print("ME:", getUserFullData("0"))
Example #7
0
def DropListTags(theSQL: str):
    db = SqlConn.ConnectToDB()
    r = SqlConn.SendSQL(db, theSQL)
    theList = ""
    for oneItem in r:
        print(oneItem)
        theList = theList + '<option value="' + str(oneItem[0]) + '">' + str(
            oneItem[1]) + '</option>\n'

    db.close()

    return theList
Example #8
0
def forgetPassword():
    if request.method == "GET":
        return flask.send_from_directory("HTML", "ForgetRequest.html")
    else:
        inEmail = request.form['email']

        if Checking.CheckEamilFormat(inEmail) == False:
            return "Wrong email address format"

        db = SqlConn.ConnectToDB()

        para = {"inEmail": inEmail}
        # Check if email is there
        r = SqlConn.SendSQL(
            db,
            "SELECT concat(`firstname`,' ',`lastname`) as FullName, `ourusers`.`userid` \
            FROM `employee`, `ourusers` WHERE `ourusers`.`userid` = `employee`.`userid` \
            AND `ourusers`.`email`=%(inEmail)s LIMIT 1", para)

        if 'err' in r:
            db.close()
            return "email not found"

        # Generate the Verfication code

        # Create the Verifcation code
        VirifcationCode = str(SqlConn.GenerateRadom(5)) + inEmail
        VirifcationCode = Hashing.sha3_256(
            VirifcationCode.encode()).hexdigest()[3:13]
        VirifcationCode = VirifcationCode.upper()

        # Save the code to the database
        para = {"vcode": VirifcationCode, "userID": r[0][1]}
        SqlConn.SendSQL(
            db,
            "UPDATE `verifications` SET `vercode`=%(vcode)s, `enddate`=DATE_ADD(NOW(), INTERVAL 4 HOUR_MINUTE) WHERE UserID = %(userID)s limit 1",
            para, False)

        db.close()

        # Send the email
        with app.app_context():
            msg = eMail.Message(subject="Forget account password with eCards",
                                sender=app.config.get("*****@*****.**"),
                                recipients=[inEmail],
                                body="Hi Mr. " + str(r[0][0]) +
                                     ", \n You have register with us and complete your registration please click the line bellow or use this Code:\n" + \
                                     str(VirifcationCode) + " \n Thank you ...")
            mail.send(msg)

        return flask.send_from_directory("HTML", "ForgetVerifcation.html")
Example #9
0
def companyAndDepartmentInfo():

    if checkLogin() == False:
        return ['err', "Login"]

    db = SqlConn.ConnectToDB()

    SqlStatment = "SELECT `departement`.* FROM `departement` WHERE `departement`.`belongtocomapny` = " + \
                    "( SELECT companyid FROM `company` WHERE `company`.`representiviteid` = " + session['EmpID']

    Result = SqlConn.SendSQL(db, SQLStatment=SqlStatment)

    db.close()

    return Result
Example #10
0
def CallFor(callingAddress: str, parametersList: str, TableName: str, ExtraData: dict = {}, IdName: str = "",
            inCondation="", idGenSize=7):
    if comFunc.checkLogin() == False:
        return redirect(url_for('login'))

    # Parse the data
    ReqnData = json.dumps(request.form)
    if ExtraData != "":
        ExtraData = json.dumps(ExtraData)
        ReqnData = ReqnData[0:len(ReqnData) - 1] + ", " + ExtraData[1:]

    ReqnData = json.loads(ReqnData)
    FullInData = ReqnData

    # Clean up
    for x in FullInData:
        FullInData[x] = Checking.RemoveUnwantedChar(FullInData[x])

    # React with DB
    db = SqlConn.ConnectToDB()
    if 'newC' in request.form:
        # Generate a new ID

        FullInData[IdName] = SqlConn.GenerateRadom(idGenSize)

        # Create the list of paramter accordingly
        InsertList = SqlConn.makeHTML(WhatYouWant="INSERT", ParaList=parametersList)
        SQLs = "INSERT INTO " + TableName + " (" + parametersList + ") VALUES " + "(" + InsertList + ")"
        r = SqlConn.InsertSQL(db, SQLs, FullInData, returnID=False)

    elif 'editC' in request.form:
        # Create the list of paramter accordingly
        #print("^^^", FullInData)
        UpdateList = SqlConn.makeHTML(WhatYouWant="UPDATE", ParaList=parametersList)
        SQLs = "UPDATE " + TableName + " SET " + UpdateList + " WHERE " + inCondation
        r = SqlConn.SendSQL(db, SQLs, FullInData, returnDate=False)

    db.close()

    # Check Result
    if r[0] == "OK":
        return redirect("/home")
    else:
        return '<center>' + r[1] + '<center>"<meta http-equiv="refresh" content="3";url=' + url_for(
            callingAddress) + '" />"'
Example #11
0
def resendVerifcaiton(UserID):

    #Clean the Passed UserID
    UserID = Checking.RemoveUnwantedChar(UserID)

    # Connect to the SQL server
    dbConn = SqlConn.ConnectToDB()

    # Check if the user exisits and get its data
    para = {"userID": UserID}
    ur = SqlConn.SendSQL(dbConn, "SELECT ourusers.`email` as email, `firstname`, `lastname` FROM ourusers, `employee` " + \
                      "WHERE ourusers.`userid`=%(userID)s AND verified = 0 AND ourusers.userid = employee.userid", para)

    if ur == None:
        print("Fail")
        return beecFunc.ReturnResponse("Fail")

    # Create new Verifcation code
    VirifcationCode = str(SqlConn.GenerateRadom(3))
    VirifcationCode = Hashing.sha3_256(
        VirifcationCode.encode()).hexdigest()[2:10]
    VirifcationCode = VirifcationCode.upper()

    # Update the code to the database
    para = {"vcode": VirifcationCode, "userID": UserID}
    SqlConn.InsertSQL(
        dbConn,
        "UPDATE `verifications` SET `vercode`= %(vcode)s WHERE `UserID`=%(userID)s",
        para, False)

    # Close DB Connection
    SqlConn.CloseConnection(dbConn)

    # Send the email
    try:
        beecFunc.SendEmail(emailSubject="Avtivate you account with eCards", emailTo=ur[0][0],
                       emailBody="Hi Mr. " + ur[0][1] + " " + ur[0][2] + \
                                 ", \n You have register with us and complete your registration please click the line bellow or use this Code:\n" + \
                                 VirifcationCode + " \n Thank you ...")
    except:
        print("Email Failer")
        return beecFunc.ReturnResponse("EmailFail")

    return beecFunc.ReturnResponse("OK")
Example #12
0
def getUserFullData(UserID: str):
    theSQL = "SELECT * FROM `employee`, `jobslist`, `empjob`, `departement`, `empbelongstodeprt`, `company`" + \
            " WHERE `userid`=" + UserID + \
            " AND `jobslist`.`jobid` = `empjob`.`jobid` AND `empjob`.`empid` = `employee`.`empid`" + \
            " AND `departement`.`departementid` = `empbelongstodeprt`.`departid` " + \
            " AND `empbelongstodeprt`.`empid` = `employee`.`empid` AND `company`.`companyid` = `departement`.`belongtocomapny`"

    db = SqlConn.ConnectToDB()
    if type(db) is str:
        print("DB")
        return db

    r = SqlConn.SendSQL(db, theSQL, returnColumns=True)

    if "No Data" in r:
        ColsNameList = []
        ColsNameList.append(
            extractColumnNames(db, "Show COLUMNS FROM `employee`"))
        ColsNameList.append(
            extractColumnNames(db, "Show COLUMNS FROM `jobslist`"))
        ColsNameList.append(
            extractColumnNames(db, "Show COLUMNS FROM `empjob`"))
        ColsNameList.append(
            extractColumnNames(db, "Show COLUMNS FROM `departement`"))
        ColsNameList.append(
            extractColumnNames(db, "Show COLUMNS FROM `empbelongstodeprt`"))
        ColsNameList.append(
            extractColumnNames(db, "Show COLUMNS FROM `company`"))

        JsonArray = {}

        for oneItem in ColsNameList:
            for oneColm in oneItem:
                JsonArray[oneColm] = ""

        return json.dumps(JsonArray)

    return json.dumps(r, ensure_ascii=False,
                      default=DataTimeHandler).encode('utf8')
Example #13
0
def DisplayCard(cardID):
    if request.method == 'POST':
        cardID = request.form["cardid"]

    # Clear the input
    cardID = Checking.RemoveUnwantedChar(cardID)

    # Get the card information form DB
    TheSql = "SELECT `isprivate`,`applytheamid`,`INFO` FROM cards WHERE cardid=%(cardID)s"
    db = SqlConn.ConnectToDB()
    para = {"cardID": cardID}
    CardDB_Data = SqlConn.SendSQL(db, TheSql, para)

    if CardDB_Data == []:
        return "Card not found!"

    # Get the Theam Data
    TheSql = "SELECT HTMLcode FROM theam WHERE theamid='" + str(CardDB_Data[0][1]) + "'"
    CardTheam = SqlConn.SendSQL(db, TheSql)

    if CardTheam == []:
        return "Theam not found!"

    db.close()

    ########################3

    TheFinalHTML = CardTheam[0][0]
    CardInfo = json.loads(CardDB_Data[0][2])

    # Extart the between {} Strings
    inHTML_ParaList = re.findall(r"\{[a-zA-Z]*\}", TheFinalHTML)

    # Replace the {} with the data form the database
    for oneWord in inHTML_ParaList:
        DataPeice = oneWord[1:len(oneWord) - 1]
        TheFinalHTML = TheFinalHTML.replace(oneWord.strip(), CardInfo[DataPeice])

    return TheFinalHTML
Example #14
0
def insertNewData(tableName:str, newData:json, idFeildName:str, exceptionColumn = []):

    db = SqlConn.ConnectToDB()

    # Get tabel feilds name
    EmpTableFeildsName = SqlConn.SendSQL(db, "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE " \
                + "`TABLE_SCHEMA`='" + SqlConn.getDatabaseName() + "' AND `TABLE_NAME`='" + tableName + "'")

    ColumnName:str = ""
    ValuesData:str = ""

    # Loop through the feilds
    for oneFeild in EmpTableFeildsName:
        print(oneFeild[0])
        # Remove any unwanted data
        if oneFeild[0] in exceptionColumn or oneFeild[0] in idFeildName:
            continue

        # Attach the new field
        if oneFeild[0] in newData:
            if str(newData[oneFeild[0]]).lower() == "none":
                continue
            ColumnName = ColumnName + "`" + str(oneFeild[0])  + "`,"
            ValuesData = ValuesData + "'" + str(newData[oneFeild[0]]) + "',"

    # Craft the UPDATE SQL
    SqlStatment = "INSERT INTO `" + tableName + "` (" + ColumnName[0:len(ColumnName)-1] + ") VALUES (" \
                  + ValuesData[0:len(ValuesData)-1] + ")"

    print(SqlStatment)
    db.close()

    return SqlConn.InsertSQL(db, SqlStatment)

# --------------------------------------------------------------------------------

# print(updateFullInfo(getUserFullData("5973461")))
# print(insertNewData(tableName="departement", newData=getUserFullData("5973461"), idFeildName="departementid"))
Example #15
0
def forgetPwdVeri():

    if 'VerifcationCode' in request.form:
        incode = request.form['VerifcationCode']

        db = SqlConn.ConnectToDB()

        para = {'incode': incode}
        r = SqlConn.SendSQL(
            db,
            "SELECT `UserID` FROM `verifications` WHERE `vercode`=%(incode)s AND `enddate`> NOW() LIMIT 1",
            para)

        if 'err' in r:
            db.close()
            return str(r)
        else:
            if 'passwordCheck' in request.form and 'NewPassword' in request.form:
                if request.form['passwordCheck'] == request.form[
                        'NewPassword']:
                    para = {
                        "NewPassword":
                        beecFunc.hasPassword(request.form['NewPassword']),
                        "UserID":
                        r[0][0]
                    }
                    SqlConn.SendSQL(
                        db,
                        "UPDATE `ourusers` SET `password`= %(NewPassword)s WHERE `userid`=%(UserID)s",
                        para,
                        returnDate=False)
                    db.close()
                    return redirect("/login")

    else:
        return flask.send_from_directory("HTML", "ForgetVerifcation.html")
Example #16
0
def login():
    #print("Login")
    if request.method == 'POST':

        # Check if POST request has the Username paramter
        if 'Username' in request.form:
            # OK
            pass
        else:
            # Not passed
            print("Wrong Request")
            return "WORNG REQUEST"

        # Parse the data
        FullInData = json.dumps(request.form)
        FullInData = json.loads(FullInData)

        # Clean the username
        if Checking.CheckEamilFormat(FullInData['Username']):
            username = FullInData['Username']
        else:
            print("Wrong Request2")
            if 'WEB' not in FullInData:
                return beecFunc.ReturnResponse("Fail")

            return flask.render_template(
                "loginpage.html",
                SystemMessage="Wrong user name or password. Please try again.")

        password = beecFunc.hasPassword(FullInData['password'])

        # Send the sql
        db = SqlConn.ConnectToDB()

        if type(db).__name__ == "str":
            print("Wrong Request3 db", db)
            return beecFunc.ReturnResponse("error")

        #print(password)
        para = {"username": username, "password": password}
        r = SqlConn.SendSQL(db, "SELECT `ourusers`.`userid`, `ourusers`.`email`, `CanLogin`, `verified`, `points`, `userroleid`, " + \
                            "`employee`.`firstname`, `employee`.`lastname`, `ourusers`.`verified`, `ourusers`.`defultCardID`, `employee`.`empid` " +\
                            "FROM `ourusers`, `employee` WHERE `employee`." +  \
                            "userid = ourusers.userid AND `ourusers`.`email` = %(username)s AND `password`=%(password)s AND " + \
                            "`CanLogin`=1 LIMIT 1", para)
        db.close()

        # Check the user
        if r != []:

            # Open the session
            #print(r)
            session['Username'] = username
            session['UserID'] = r[0][0]
            session['Email'] = r[0][1]
            session['CanLogin'] = r[0][2]
            session['Verified'] = r[0][3]
            session['Points'] = r[0][4]
            session['UserRoleID'] = r[0][5]
            session['FullName'] = r[0][6] + " " + r[0][7]
            session['EmpID'] = r[0][8]

            #print(session)

            if 'WEB' not in FullInData:
                # Check if the user has completed his verifction
                if r[0][8] != 1:
                    responseDic = {"Result": "Verification"}
                else:
                    responseDic = {"Result": "Success!"}

                for l in session:
                    responseDic[l] = session[l]

                response = app.response_class(response=json.dumps(responseDic),
                                              status=200,
                                              mimetype='application/json')

                return response  # ReturnResponse("Success!")
            else:
                return redirect("/home")

            # return open("HTML/homepage.html").read().format(first_header='Welcome', p1=session['FullName'])
        else:
            # Wrong user name or password
            if 'WEB' not in FullInData:
                print("Fails")
                return beecFunc.ReturnResponse("Fail")
            else:
                return flask.render_template(
                    "loginpage.html",
                    SystemMessage=
                    "Wrong user name or password. Please try again.")

    return flask.render_template("loginpage.html")
Example #17
0
def CardsEdit():
    if comFunc.checkLogin() == False:
        return redirect(url_for('login'))

    if request.method == 'POST':
        ReqnData = json.dumps(request.form)
        ReqnData = json.loads(ReqnData)
        FullInData = ReqnData

        # Clean up
        for x in FullInData:
            FullInData[x] = Checking.RemoveUnwantedChar(FullInData[x])

        # React with DB
        db = SqlConn.ConnectToDB()
        if 'newC' in request.form:
            # Generate a new ID

            FullInData['cardid'] = SqlConn.GenerateRadom(5)

            # Fix the checkbox input
            if FullInData['isprivate'] == 'on':
                FullInData['isprivate'] = "1"
            else:
                FullInData['isprivate'] = "0"

            ##############################
            #   Fix the INFO feild to JSON object
            ##############################

            # Get the Theam HTML
            para = {"applytheamid": FullInData['applytheamid']}
            ThemSQL_Result = SqlConn.SendSQL(db, "SELECT `HTMLcode` FROM `theam` WHERE `theamid`=%(applytheamid)s", para)

            # Extart the requried data
            inHTML_ParaList = re.findall(r"\{[a-zA-Z]*\}", ThemSQL_Result[0][0])
            # Remove the {} from the results
            for x in range(0, len(inHTML_ParaList)):
                inHTML_ParaList[x] = inHTML_ParaList[x][1:len(inHTML_ParaList[x]) - 1]

            ##################
            # Get the full data JSON
            FullDataJSON =   GetUserFullData(session['UserID'], app, True)
            FullDataJSON = json.loads(FullDataJSON)

            ResultJSON: dict = {}
            # Match the needed data with the data in FullDataJSON

            for oneEntry in FullDataJSON:
                if oneEntry in inHTML_ParaList:
                    ResultJSON[oneEntry] = FullDataJSON[oneEntry]

            # Fix Full Name `firstname``middlename``grandname``lastname`
            ResultJSON['FullName'] = FullDataJSON['firstname']
            if "middlename" in FullDataJSON:
                ResultJSON['FullName'] = ResultJSON['FullName'] + " " + FullDataJSON['middlename']
            if "grandname" in FullDataJSON:
                ResultJSON['FullName'] = ResultJSON['FullName'] + " " + FullDataJSON['grandname']

            ResultJSON['FullName'] = str(ResultJSON['FullName'] + " " + FullDataJSON['lastname'])

            # Assign the JSON object
            FullInData['INFO'] = json.dumps(ResultJSON, ensure_ascii=False)

            ###############################################

            # Create the Insert SQL
            SQLs = "INSERT INTO cards (`cardid`, `cardname`, `hashlink`, `isprivate`, `visitcounter`, `htmllink`, `foremployee`, `applytheamid`, `INFO`, `QRCodeImg`) VALUES " \
                   + "('" + str(FullInData['cardid']) + "','" + FullInData['cardname'] + "','" + FullInData[
                       'hashlink'] + "','" + \
                   FullInData['isprivate'] + "','0','" + FullInData['htmllink'] + "','" + \
                   str(FullInData['foremployee']) + "','" + str(FullInData['applytheamid']) + "','" + FullInData[
                       'INFO'] + "','" + \
                   str(FullInData['QRCodeImg']) + "')"

            r = SqlConn.InsertSQL(db, SQLs, FullInData, returnID=False)

            return str(r)

        elif 'editC' in request.form:
            # Create the list of paramter accordingly
            print("^^^", FullInData)

        db.close()


    else:
        return flask.render_template("EditCard.html")
Example #18
0
def RegisterNewUser():
    if request.method == 'POST':
        # Convert the input to JSON object
        FullInData = json.dumps(request.form)
        FullInData = json.loads(FullInData)

        # print("Resived:", FullInData)

        try:
            # return FullInData;

            # Check email format
            if Checking.CheckEamilFormat(FullInData['email']):
                # Check email Match
                if (FullInData['email']) == (FullInData['Reenter']
                                             or 'WEB' not in FullInData):
                    print("email check passed")
                    pass
                else:
                    if 'WEB' not in FullInData:
                        return beecFunc.ReturnResponse("Email Match")
                    else:
                        return Msgs.getErrorMessage(0, "EN")
            else:
                if 'WEB' not in FullInData:
                    return beecFunc.ReturnResponse("Email Format")
                else:
                    return Msgs.getErrorMessage(1, "EN")

            # Check Password Match
            if FullInData['Passowrd'] == FullInData[
                    'pReenter'] or 'WEB' not in FullInData:
                # Password Complexity
                d = Checking.passwordComplexity(FullInData['Passowrd'])

                if d == "OK":
                    print("Password Complexity Passed")
                    pass
                else:
                    print("Password Complexity FAILD")
                    if 'WEB' not in FullInData:
                        return beecFunc.ReturnResponse("Pwd Complexity")
                    else:
                        return Msgs.getErrorMessage(2, "EN")
            else:
                if 'WEB' not in FullInData:
                    return beecFunc.ReturnResponse("Pwd Match")
                else:
                    return Msgs.getErrorMessage(3, "EN")

            # Virify the username
            # FullInData['UserName'] = Checking.RemoveUnwantedChar(FullInData['UserName'])

            # Clean all input data
            for x in FullInData:
                if x != "Passowrd" and x != "email":
                    FullInData[x] = Checking.RemoveUnwantedChar(FullInData[x])
        except KeyError:
            if 'WEB' not in FullInData:
                return beecFunc.ReturnResponse("Passed Key error: " +
                                               str(KeyError))
            else:
                return "Passed Key error: " + str(KeyError)
        except:
            if 'WEB' not in FullInData:
                return beecFunc.ReturnResponse("Other Error")
            else:
                return "Some error in you request"

        # ----------------------------------------
        #   Everything is ok
        # ----------------------------------------

        print("Everything is OK")

        ErrorArray = []

        # Create User ID
        FullInData['userid'] = str(SqlConn.GenerateRadom(8))
        FullInData['password'] = beecFunc.hasPassword(FullInData['Passowrd'])

        # Connect to the SQL serer
        dbConn = SqlConn.ConnectToDB()

        # 1 Insert the user
        ResultData = SqlConn.InsertSQL(
            dbConn,
            "INSERT INTO `ourusers`(`CanLogin`,`points`,`userroleid`,`userid`, `email`,`password`) VALUES (1, 0, 122, %(userid)s, %(email)s, %(password)s )",
            FullInData, False)

        # Check if result is ok
        if ResultData == None or ResultData[0] != "OK":

            # If the error was becuse exisiting email, change the 'err' title to exisit
            # This is to dispaly the correct error message on the app

            if 'WEB' not in FullInData:
                if "exisits" in ResultData[1]:
                    return beecFunc.ReturnResponse("Exisit")
                else:
                    return beecFunc.ReturnResponse(ResultData[1])
            else:
                return str(ResultData)

        # 2 Get the new created Licese ID
        # LicSQL = SqlConn.SendSQL(dbConn, "SELECT `licencesid` FROM `licences` WHERE `type`='E' AND `CreatedFor`=' " + str(UserID) + "'")

        para = {"username": FullInData['userid']}
        LicSQL = SqlConn.SendSQL(
            dbConn,
            "SELECT `licencesid` FROM `licences` WHERE `type`='E' AND `CreatedFor`=%(username)s",
            para)
        # print(FullInData['userid'])
        FullInData["LicenceID"] = str(LicSQL[0][0])

        # 3 Create and employee

        # print("FullInData[1LicenceID1]=", FullInData["LicenceID"])
        myInsert = "INSERT INTO `employee`(`empid`, `nickname`, `firstname`, `middlename`, `grandname`, `lastname`, `abuname`, " + \
                   "`phone`, `mobile`, `hometel`, `email`, `workphone`, `notes`, `userid`, `licencesid`) VALUES ('1'," + \
                   " %(Nickname)s , %(FirstName)s, %(MiddleName)s , %(GrandFatherName)s , %(FamilyName)s ,%(AbuName)s , %(PhoneNumber)s" + \
                   ", %(MobileNumber)s , %(HomePhone)s , %(email)s , %(Workphone)s , %(notes)s , %(userid)s , %(LicenceID)s )"

        ResultData = SqlConn.InsertSQL(dbConn, myInsert, FullInData, True)

        # ------------
        # 4 SEND EMAIL

        if ResultData[0] == "OK":
            # Create the Verifcation code
            VirifcationCode = str(SqlConn.GenerateRadom(3))
            VirifcationCode = Hashing.sha3_256(
                VirifcationCode.encode()).hexdigest()[2:10]
            VirifcationCode = VirifcationCode.upper()

            # Save the code to the database
            para = {"vcode": VirifcationCode, "userID": FullInData['userid']}
            SqlConn.InsertSQL(
                dbConn,
                "INSERT INTO `verifications`(`vercode`, `UserID`) VALUES (%(vcode)s,%(userID)s )",
                para, False)

            # Send the email
            try:
                beecFunc.SendEmail(emailSubject="Avtivate you account with eCards", emailTo=FullInData['email'],
                               emailBody="Hi Mr. " + FullInData['FirstName'] + \
                                         ", \n You have register with us and complete your registration please click the line bellow or use this Code:\n" + \
                                         VirifcationCode + " \n Thank you ...")
            except:
                ErrorArray.append("Email")

            # Close DB Connection
            SqlConn.CloseConnection(dbConn)

            # 5 Redirect to verificaiton
            RR = flask.send_from_directory("HTML", "EmailVerifcation.html")
            if 'WEB' not in FullInData:
                if len(ErrorArray) > 0:
                    if "Email" in ErrorArray:
                        return beecFunc.ReturnResponse(
                            {
                                "Result": "Email",
                                "UserID": ResultData[1]
                            }, True)
                else:
                    return beecFunc.ReturnResponse(
                        {
                            "Result": "OK",
                            "UserID": ResultData[1]
                        }, True)
            else:
                return str(RR)

        # Close DB Connection
        SqlConn.CloseConnection(dbConn)

        if 'WEB' not in FullInData:
            return beecFunc.ReturnResponse(ResultData)
        else:
            return str(ResultData)

        # return Msgs.getErrorMessage(4, "EN") + FullInData['UserName']

    elif request.method == 'GET':
        # If it get, simply return the registration form
        return flask.send_from_directory("HTML", "Register.html")