def create_new_survey(self, args, person, ip):
     event_type = "CREATE_NEW_SURVEY"
     f_name, l_name = get_username(person)
     survey_id = get_uuid()
     img_filename = uploaded_file_security(args["SURVEY_PIC_FILE"], "survey_pic", survey_id)
     page_type = "SubProperty"
     location = "/do-survey"
     role = "All"
     parent_page = "Survey"
     if not isinstance(img_filename, str):
         return img_filename
     if get_surveys_table(where="NAME='" + args["SURVEY_NAME"] + "'", count=True) > 0:
         return response_create(json.dumps({"STATUS": "error", "ERROR": "Survey name is already exists."}))
     if "All" in args["PROJECT"]:
         args["PROJECT"] = ["All"]
     self.write_mysql("INSERT INTO surveys VALUES ('{0}','{1}','{2}','{3}','{4}')".format(
         survey_id, args["SURVEY_NAME"], args["SURVEY_TEXT"], args["SURVEY_EXP"], ",".join([self.get_project_name(i) for i in args["PROJECT"]])
     ))
     self.write_mysql("INSERT INTO pages VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','Enabled')".format(
         args["SURVEY_NAME"], location, role, img_filename, page_type, parent_page, survey_id, ",".join([self.get_project_name(i) for i in args["PROJECT"]])
     ))
     log = "New survey added by \"{0} {1}\".Name: {2}, ID: {3}.".format(f_name, l_name, args["SURVEY_NAME"], survey_id)
     write_log_to_mysql(event_type, ip, "INFO", log, self.system_username)
     self.mysql_commit()
     return response_create(json.dumps({"STATUS": "OK", "MESSAGE": "New survey added."}))
 def add_new_project(self, args, person, ip):
     event_type = "ADD_NEW_PROJECT"
     f_name, l_name = get_username(person)
     if get_projects_table(where="NAME='" + args["PROJECT_IDENTIFIER"] + "'", count=True) > 0:
         return response_create(json.dumps({"STATUS": "error", "ERROR": "Project already exists."}))
     project_id = get_uuid()
     self.write_mysql("INSERT INTO projects VALUES ('{0}','{1}','{2}','Passive')".format(project_id, args["PROJECT_IDENTIFIER"], args["PROJECT_EXP"]))
     log = "New project added by \"{0} {1}\".Project ID: {2}, Project Name: {3}.".format(f_name, l_name, project_id, args["PROJECT_IDENTIFIER"])
     write_log_to_mysql(event_type, ip, "INFO", log, self.system_username)
     self.mysql_commit()
     return response_create(json.dumps({"STATUS": "OK", "MESSAGE": "New project added."}))
 def save_survey_results(self, args, person, ip):
     event_type = "SAVE_SURVEY"
     survey_data, survey_session_id = args
     survey_data = json.loads(survey_data)
     if session.get("survey_id") != survey_session_id:
         return response_create(json.dumps({"STATUS": "error", "ERROR": "Survey ID is wrong."}))
     survey_data["survey_identifier"] = survey_session_id
     survey_id = self.mongodb.survey.insert_one(survey_data)
     session.pop("survey_id", None)
     f_name, l_name = get_username(person)
     log = "Survey completed by \"{0} {1}\".Survey ID: {2}".format(f_name.title(), l_name.upper(), survey_id.inserted_id)
     write_log_to_mysql(event_type, ip, "INFO", log, self.system_username)
     self.mysql_commit()
     return response_create(json.dumps({"STATUS": "OK", "MESSAGE": "Complete survey successful."}))
 def register(self, args, ip):
     event_type = "REGISTER"
     if get_users_table(where="IP='" + ip + "'", count=True) > 0:
         return response_create(
             json.dumps({
                 "STATUS": "error",
                 "ERROR": "Your IP address not permitted."
             }))
     if args["PASSWORD"] != args["RE-PASSWORD"]:
         return response_create(
             json.dumps({
                 "STATUS": "error",
                 "ERROR": "Your passwords does not match."
             }))
     try:
         uid = get_uuid()
         self.write_mysql(
             "INSERT INTO users(ID,F_NAME,L_NAME,EMAIL,MAJORITY,COUNTRY,PASSWORD,CITY,HOSPITAL,IP) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')"
             .format(uid, args["FIRSTNAME"], args["LASTNAME"],
                     args["EMAIL"], args["MAJORITY"], args["COUNTRY"],
                     calculate_hash(args["PASSWORD"], "sha256"),
                     args["CITY"], args["HOSPITAL"], ip))
         self.write_mysql(
             "INSERT INTO user_profile(ID) VALUES ('{0}')".format(uid))
         log = "New user created.Name: {0}, Surname: {1}, Majority: {2}, Country: {3}, UserID: {4}.".format(
             args["FIRSTNAME"], args["LASTNAME"], args["MAJORITY"],
             args["COUNTRY"], uid)
         write_log_to_mysql(event_type, ip, "INFO", log,
                            self.system_username)
         self.mysql_commit()
         return response_create(json.dumps({"STATUS": "OK", "target": "/"}))
     except mdb.IntegrityError:
         self.mysql_rollback()
         return response_create(
             json.dumps({
                 "STATUS":
                 "error",
                 "ERROR":
                 "Your account already created.If you forget your password, contact us."
             }))
     except Exception as e:
         self.mysql_rollback()
         return response_create(
             json.dumps({
                 "STATUS":
                 "error",
                 "ERROR":
                 "Query could not be completed.Error: {0}".format(e)
             }))
 def decide_user_first_status(self, args, person, ip):
     event_type = "REGISTERED_USER_STATUS"
     f_name, l_name = get_username(person)
     t_name, t_surname = get_username(args["USER_ID"])
     if args["USER_STATUS"] == "enable":
         if args["PROJECT"][0] == "none":
             return response_create(json.dumps({"STATUS": "error", "ERROR": "Project is not none for this process."}))
         self.write_mysql("UPDATE users SET STATUS='Enabled', PROJECT='{0}' WHERE ID='{1}'".format(",".join([self.get_project_name(i) for i in args["PROJECT"] if i != "none"]), args["USER_ID"]))
         user_base_folder = os.path.join(current_app.config.get("PROJECT_BASE") + current_app.config.get("USER_BASE"), args["USER_ID"])
         os.mkdir(user_base_folder)
     elif args["USER_STATUS"] == "delete":
         self.write_mysql("DELETE FROM users WHERE ID='{0}'".format(args["USER_ID"]))
         self.write_mysql("DELETE FROM user_profile WHERE ID='{0}'".format(args["USER_ID"]))
     log = "User status changed by \"{0} {1}\".Status: {2}, Projects: {3}, Name: {4}, Surname: {5}.".format(f_name, l_name, args["USER_STATUS"].capitalize(), ",".join([self.get_project_name(i) for i in args["PROJECT"]]), t_name, t_surname)
     write_log_to_mysql(event_type, ip, "INFO", log, self.system_username)
     self.mysql_commit()
     return response_create(json.dumps({"STATUS": "OK", "MESSAGE": "Status changed."}))
 def change_project_status(self, args, person, ip):
     convert_table = {"Active": "Passive", "Passive": "Active"}
     event_type = "PROJECT_STATUS_CHANGE"
     f_name, l_name = get_username(person)
     if get_projects_table(where="ID='" + args["PROJECT_ID"] + "' AND STATUS='" + convert_table[args["PROJECT_STATUS"]] + "'", count=True) > 0:
         self.write_mysql("UPDATE projects SET STATUS='{1}' WHERE ID='{0}'".format(args["PROJECT_ID"], args["PROJECT_STATUS"]))
         log = "Project status changed by \"{0} {1}\".Status: {2}, Project Name: {3}.".format(f_name, l_name, args["PROJECT_STATUS"], self.get_project_name(args["PROJECT_ID"]))
         write_log_to_mysql(event_type, ip, "INFO", log, self.system_username)
         self.mysql_commit()
     return response_create(json.dumps({"STATUS": "OK", "MESSAGE": "Status changed."}))
 def sign_in(self, email, password, ip):
     event_type = "LOGIN"
     password = calculate_hash(password, method="sha256")
     session_environ = [
         "UID", "FIRSTNAME", "LASTNAME", "EMAIL", "MAJORITY", "COUNTRY",
         "STATUS", "ROLE", "CITY", "HOSPITAL", "PROJECT"
     ]
     try:
         user_data = get_users_table(
             where="EMAIL='" + email + "' AND PASSWORD='******'",
             column=
             "ID,F_NAME,L_NAME,EMAIL,MAJORITY,COUNTRY,STATUS,ROLE,CITY,HOSPITAL,PROJECT"
         )[0]
     except IndexError:
         user_data = tuple()
     if len(user_data) > 0:
         if user_data[-5] in ["Pending", "Disabled"]:
             return response_create(
                 json.dumps({
                     "STATUS":
                     "error",
                     "ERROR":
                     "Your account is disabled.Please contact Middleware Team."
                 }))
         session["logged-in"] = True
         for i in range(len(session_environ)):
             session[session_environ[i]] = user_data[i]
         log = "Successful login. Email: {0}".format(email)
         write_log_to_mysql("LOGIN", ip, "INFO", log, self.system_username)
         return response_create(
             json.dumps({
                 "STATUS": "OK",
                 "target": "/main"
             }))
     log = "Failed login. Email: {0}".format(email)
     write_log_to_mysql(event_type, ip, "WARNING", log,
                        self.system_username)
     return response_create(
         json.dumps({
             "STATUS": "error",
             "ERROR": "Incorrect username or password."
         }))
 def password_change(self, curr_pass, new_pass, again_pass, ip):
     event_type = "PASSWORD_CHANGE"
     user_id = session.get("UID")
     old_pass = get_users_table(where="ID='" + session.get("UID") + "'",
                                column="PASSWORD")[0][0]
     control = re.compile(
         "^(?=.*?\d)(?=.*?[A-Z])(?=.*?[@.*\-_!])(?=.*?[a-z])[A-Za-z\d@.*\-_!]{8,}$"
     )
     if not bool(control.search(new_pass)):
         return response_create(
             json.dumps({
                 "STATUS":
                 "error",
                 "ERROR":
                 "Your password is weak.Your password may only contain special characters (@. * -_!), Upper / lower case, and numbers."
             }))
     if str(old_pass) == str(calculate_hash(new_pass, method="sha512")):
         return response_create(
             json.dumps({
                 "STATUS": "error",
                 "ERROR": "You have to your change password."
             }))
     elif str(old_pass) != str(calculate_hash(curr_pass, method="sha512")):
         return response_create(
             json.dumps({
                 "STATUS": "error",
                 "ERROR": "Your old password is incorrect."
             }))
     elif str(new_pass) != str(again_pass):
         return response_create(
             json.dumps({
                 "STATUS": "error",
                 "ERROR": "Your new passwords not match."
             }))
     else:
         secret = calculate_hash(new_pass, method="sha256")
         changer = "UPDATE users SET PASSWORD='******' WHERE UID='{1}'".format(
             secret, user_id)
         try:
             self.write_mysql(changer)
             session.clear()
             log = "Password changed.User: {0}.".format(" ".join(
                 get_username(user_id)))
             write_log_to_mysql(event_type, ip, "INFO", log,
                                self.system_username)
             return response_create(
                 json.dumps({
                     "STATUS": "OK",
                     "target": "/"
                 }))
         except Exception as e:
             self.mysql_rollback()
             return response_create(
                 json.dumps({
                     "STATUS":
                     "error",
                     "ERROR":
                     "Query could not be completed.Error: {0}".format(e)
                 }))
 def change_user_details(self, args, person, ip):
     event_type = "USER_DETAILS_CHANGE"
     f_name, l_name = get_username(person)
     t_name, t_surname = get_username(args["USER_ID"])
     changes = dict()
     columns = ("MAJORITY", "COUNTRY", "HOSPITAL", "CITY", "ROLE", "PROJECT")
     args["COUNTRY"] = self.get_country_id(args["COUNTRY_NAME"])
     args["PROJECT"] = ",".join([self.get_project_name(i) for i in args["PROJECT"]])
     update_statement = "UPDATE users SET"
     old_data = get_users_table(where="ID='" + args["USER_ID"] + "'", column=",".join(columns))[0]
     for i in range(len(columns)):
         if args[columns[i]] != old_data[i]:
             changes[columns[i]] = (old_data[i], args[columns[i]])
             update_statement += " " + columns[i] + "='" + args[columns[i]] + "'"
     if len(changes) > 0:
         update_statement += " WHERE ID='" + args["USER_ID"] + "'"
         self.write_mysql(update_statement)
         log = "User details changed by \"{0} {1}\".Name: {2}, Surname: {3}, Changes: {4}.".format(f_name, l_name, t_name, t_surname, changes)
         write_log_to_mysql(event_type, ip, "INFO", log, self.system_username)
         self.mysql_commit()
         return response_create(json.dumps({"STATUS": "OK", "MESSAGE": "Status changed."}))
     return response_create(json.dumps({"STATUS": "error", "ERROR": "No changes found."}))
 def change_user_status(self, args, person, ip):
     event_type = "USER_STATUS_CHANGE"
     f_name, l_name = get_username(person)
     t_name, t_surname = get_username(args["USER_ID"])
     if args["USER_STATUS"] == "enable" or args["USER_STATUS"] == "activate":
         if get_users_table(where="ID='" + args["USER_ID"] + "' AND STATUS IN ('Disabled', 'Deleted')", count=True) > 0:
             self.write_mysql("UPDATE users SET STATUS='Enabled' WHERE ID='{0}'".format(args["USER_ID"]))
     elif args["USER_STATUS"] == "disable":
         if get_users_table(where="ID='" + args["USER_ID"] + "' AND STATUS='Enabled'", count=True) > 0:
             self.write_mysql("UPDATE users SET STATUS='Disabled' WHERE ID='{0}'".format(args["USER_ID"]))
     elif args["USER_STATUS"] == "delete":
         if get_users_table(where="ID='" + args["USER_ID"] + "' AND STATUS IN ('Enabled', 'Disabled')", count=True) > 0:
             self.write_mysql("UPDATE users SET STATUS='Disabled' WHERE ID='{0}'".format(args["USER_ID"]))
     log = "User status changed by \"{0} {1}\".Status: {2}, Name: {3}, Surname: {4}.".format(f_name, l_name, args["USER_STATUS"].capitalize(), t_name, t_surname)
     write_log_to_mysql(event_type, ip, "INFO", log, self.system_username)
     self.mysql_commit()
     return response_create(json.dumps({"STATUS": "OK", "MESSAGE": "Status changed."}))
Beispiel #11
0
def arguman_controller(args, log_patern=False):
    mail = re.compile(
        "^[a-zA-Z0-9.\-_]+@[a-zA-Z0-9]{,8}\.([a-zA-Z0-9]{,8}\.[a-zA-Z0-9]{,8}|[a-zA-Z0-9]{,8})$"
    )
    names = re.compile(r"^[a-zA-Z ]{,20}$", re.UNICODE)
    identifier = re.compile(r"^[a-zA-Z0-9 \-]{1,50}$", re.UNICODE)
    hospital = re.compile(r"^[a-zA-Z ]{,50}$", re.UNICODE)
    password = re.compile(
        "^(?=.*?\d)(?=.*?[A-Z])(?=.*?[@.*\-_!])(?=.*?[a-z])[A-Za-z\d@.*\-_!]{8,}$"
    )
    ip = re.compile("^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|[\d.*]{,12})$")
    keyword = re.compile("([a-zA-Z0-9.,\-]+)")
    date = re.compile("^\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}$")
    severity = re.compile("^none|{0}$".format("|".join([
        i[0] for i in get_system_logs_table(column="DISTINCT(EVENT_SEVERITY)")
    ])))
    etype = re.compile("^none|{0}$".format("|".join(
        [i[0] for i in get_system_logs_table(column="DISTINCT(EVENT_TYPE)")])))
    users = re.compile("^none|{0}$".format("|".join(
        [i[0] for i in get_system_logs_table(column="DISTINCT(USERNAME)")])))
    country_codes = re.compile("^{0}$".format("|".join(
        [i[0] for i in get_country_table(column="CODE")])))
    country_names = re.compile("^{0}$".format("|".join(
        [i[0] for i in get_country_table(column="NAME")])))
    user_id = re.compile("^{0}$".format("|".join(
        [i[0] for i in get_users_table(column="ID")])))
    user_role = re.compile("^{0}$".format("|".join(
        [i[0] for i in get_user_roles_table(column="NAME")])))
    projects = re.compile("^All|none|{0}$".format("|".join(
        [i[0] for i in get_projects_table(column="ID")])))
    patern = {
        "EMAIL": [mail, "Mail address syntax error."],
        "FIRSTNAME": [names, "Firstname syntax error."],
        "LASTNAME": [names, "Lastname syntax error."],
        "PASSWORD": [password, "Your password is week."],
        "RE-PASSWORD": [password, "Your password is week."],
        "MAJORITY": [names, "Majority syntax error."],
        "COUNTRY": [country_codes, "Invalid country code."],
        "CITY": [names, "Invalid city name."],
        "HOSPITAL": [hospital, "Invalid hospital name."],
        "USER_ID": [user_id, "Invalid user id."],
        "PROJECT_ID": [projects, "Invalid project ID."],
        "PROJECT": [projects, "Invalid project."],
        "PROJECT_IDENTIFIER": [identifier, "Invalid project."],
        "USER_STATUS": [
            re.compile("(enable|delete|disable|activate)"),
            "Invalid user status."
        ],
        "PROJECT_STATUS":
        [re.compile("(Active|Passive)"), "Invalid project status."],
        "COUNTRY_NAME": [country_names, "Invalid country name."],
        "ROLE": [user_role, "Invalid role name."],
        "SURVEY_NAME": [names, "Invalid survey name."],
        "SURVEY_EXP": [keyword, "Invalid survey explanation."],
        "PROJECT_EXP": [keyword, "Invalid project explanation."],
        "SURVEY_PIC_FILE": []
    }
    for_log_patern = {
        "ALL_LOG": [re.compile("(True|False)"), "Invalid bool value error."],
        "EVENT_IP": [ip, "Invalid ip error."],
        "EVENT_KEYWORD": [keyword, "Invalid keyword options error."],
        "EVENT_START_DATE": [date, "Invalid date error."],
        "EVENT_END_DATE": [date, "Invalid date error."],
        "EVENT_TYPE": [etype, "Invalid type error."],
        "EVENT_SEVERITY": [severity, "Invalid severity error."],
        "EVENT_USERS": [users, "Invalid user error."]
    }
    try:
        if log_patern:
            if args["ALL_LOG"] == "True":
                return True, 0
            for k, v in args.iteritems():
                if v != "none":
                    if isinstance(v, list):
                        for key in v:
                            if key != "none":
                                if not bool(for_log_patern[k][0].search(key)):
                                    return False, json.dumps({
                                        "STATUS":
                                        "error",
                                        "ERROR":
                                        for_log_patern[k][1]
                                    })
                    elif not bool(for_log_patern[k][0].search(v)):
                        return False, json.dumps({
                            "STATUS": "error",
                            "ERROR": for_log_patern[k][1]
                        })
        else:
            for k, v in args.iteritems():
                if isinstance(v, list):
                    for key in v:
                        if not bool(patern[k][0].search(key)):
                            return False, json.dumps({
                                "STATUS": "error",
                                "ERROR": patern[k][1]
                            })
                elif k not in ["SURVEY_TEXT", "SURVEY_PIC_FILE"]:
                    if not bool(patern[k][0].search(v)):
                        return False, json.dumps({
                            "STATUS": "error",
                            "ERROR": patern[k][1]
                        })
        return True, 0
    except Exception as e:
        return False, response_create(
            json.dumps({
                "STATUS": "error",
                "ERROR": "Something went wrong.Exception is : " + str(e)
            }))
    def search_log(self, args, person, ip):
        event_type = "LOG_SEARCH"
        where = None
        f_name, l_name = get_username(person)
        navigations = {
            "EVENT_IP": "EVENT_IP",
            "EVENT_KEYWORD": "EVENT",
            "EVENT_TYPE": "EVENT_TYPE",
            "EVENT_SEVERITY": "EVENT_SEVERITY",
            "EVENT_USERS": "USERNAME"
        }
        if args["ALL_LOG"] != "True":
            where = ""
            del args["ALL_LOG"]
            for k, v in args.iteritems():
                if "none" not in v:
                    if not k.endswith("DATE"):
                        if isinstance(v, list):
                            qlist = []
                            for val in v:
                                if val != "none":
                                    if val.endswith("*") and val.startswith("*"):
                                        qlist.append(" {0} LIKE '%{1}%'".format(navigations[k], val.replace("*", "")))
                                    elif val.endswith("*"):
                                        qlist.append(" {0} LIKE '{1}%'".format(navigations[k], val.replace("*", "")))
                                    elif val.startswith("*"):
                                        qlist.append(" {0} LIKE '%{1}'".format(navigations[k], val.replace("*", "")))
                                    else:
                                        qlist.append(" {0}='{1}'".format(navigations[k], val))
                            if len(qlist) > 0:
                                where += " ("
                                where += " OR".join(qlist)
                                where += ") AND"
                        else:
                            if v != "none":
                                if v.endswith("*"):
                                    where += " {0} LIKE '{1}%' AND".format(navigations[k], v.replace("*", ""))
                                elif v.startswith("*"):
                                    where += " {0} LIKE '%{1}' AND".format(navigations[k], v.replace("*", ""))
                                elif v.startswith("*") and v.endswith("*"):
                                    where += " {0} LIKE '%{1}%' AND".format(navigations[k], v.replace("*", ""))
                                else:
                                    where += " {0}='{1}' AND".format(navigations[k], v)
            if args["EVENT_START_DATE"] != "none" and args["EVENT_END_DATE"] != "none":
                where += " EVENT_TIME BETWEEN '{0}' AND '{1}'".format(datetime_patern(pt="js", dt=args["EVENT_START_DATE"], ct="%d.%m.%Y %H:%M"), datetime_patern(pt="js", dt=args["EVENT_END_DATE"], ct="%d.%m.%Y %H:%M"))
            elif args["EVENT_START_DATE"] != "none":
                where += " EVENT_TIME='{0}' AND".format(datetime_patern(pt="js", dt=args["EVENT_START_DATE"], ct="%d.%m.%Y %H:%M"))
            elif args["EVENT_END_DATE"] != "none":
                where += " EVENT_TIME='{0}' AND".format(datetime_patern(pt="js", dt=args["EVENT_END_DATE"], ct="%d.%m.%Y %H:%M"))

            if where.endswith("AND"):
                where = where[0:-3] + " ORDER BY EVENT_TIME ASC"
            if where.endswith("WHERE"):
                return response_create(json.dumps({"STATUS": "error", "ERROR": "No results found for your search criteria."}))
        if where is not None and len(where) > 0:
            result_set = get_system_logs_table(where=where)
        else:
            result_set = get_system_logs_table()
        if len(result_set) > 0:
            html = []
            colors = {
                "ERROR": "btn btn-danger",
                "INFO": "btn btn-info",
                "WARNING": "btn btn-warning",
                "SUCCESS": "btn btn-success",
                "CRITICAL": "btn btn-critical",
                "ATTACK": "btn btn-attack"
            }
            for i in result_set:
                data_set = {
                    "id": i[0],
                    "type": i[1],
                    "ip": i[2],
                    "severity": [i[3], colors[i[3]]],
                    "log": i[4],
                    "timestamp": datetime_patern(dt=i[5]),
                    "username": i[6]
                }
                html.append(data_set)
            return response_create(json.dumps({"STATUS": "OK", "content": html, "q": "Results found."}))
        else:
            log = "Unsuccessful search by \"{0} {1}\" .Search criteria: \"{2}\" .".format(f_name, l_name, "; ".join(["{0}:{1}".format(k, ", ".join(v)) for k, v in args.iteritems() if "none" not in v]))
            write_log_to_mysql(event_type, ip, "ERROR", log, self.system_username)
            return response_create(json.dumps({"STATUS": "error", "ERROR": "No results found for your search criteria."}))