def get_event(self, id):

        print("get_event - entro en la funcion")

        event = {}

        try:
            conn = mariadb.connect(user=os.getenv('MARIADB_USERNAME'),
                                   password=os.getenv('MARIADB_PASSWORD'),
                                   host=os.getenv('MARIADB_HOST'),
                                   database='prometeo',
                                   port=int(os.getenv('MARIADB_PORT')))

            cursor = conn.cursor()

            # cursor.execute('SELECT event_id, event_code, name, surname, email FROM events WHERE deleted_at IS NULL AND event_id = ?', (id,))
            cursor.callproc('sp_select_event', (id, ))

            data = cursor.fetchone()

            if len(data) > 0:
                event = {
                    'id': data[0],
                    'code': data[1],
                    'type': data[3],
                    'date': data[5],
                    'firefighters': 10,
                    'state': data[2]
                }
            else:
                return None

        except Exception as e:
            return None

        finally:
            cursor.close()
            conn.close()

        return event
Example #2
0
 def GuardarDetalle(self, parametros):
     try:
         conn = mariadb.connect(
             user="******",
             password=base64.b64decode(
                 'SXRhY2hpIFVjaGloYSB3aXBlIHRoZW0gYWxs').decode(),
             host="localhost",
             port=3306,
             database="logger")
         conn.autocommit = True
         c = conn.cursor()
         #sql ="INSERT INTO DetalleEjes(idVehiculo, velocidad, peso, pesoRuedaIzquierda, pesoRuedaDerecha, desbalanceIzquierdaDerecha, distancia) VALUES(?, ?, ?, ?, ?, ?, ?)"
         sql = "SU5TRVJUIElOVE8gRGV0YWxsZUVqZXMoaWRWZWhpY3VsbywgdmVsb2NpZGFkLCBwZXNvLCBwZXNvUnVlZGFJenF1aWVyZGEsIHBlc29SdWVkYURlcmVjaGEsIGRlc2JhbGFuY2VJenF1aWVyZGFEZXJlY2hhLCBkaXN0YW5jaWEpIFZBTFVFUyg/LCA/LCA/LCA/LCA/LCA/LCA/KQ=="
         c.execute(base64.b64decode(sql).decode(), parametros)
         conn.close()
         return True
     except mariadb.Error as e:
         print("Al guardar el detalle de ejes: ", repr(e))
         return False
     except Exception as e:
         print("Al guardar el detalle de ejes: ", repr(e))
         return False
Example #3
0
 def GuardarRawData(self, parametros):
     try:
         conn = mariadb.connect(
             user="******",
             password=base64.b64decode(
                 'SXRhY2hpIFVjaGloYSB3aXBlIHRoZW0gYWxs').decode(),
             host="localhost",
             port=3306,
             database="logger")
         conn.autocommit = True
         c = conn.cursor()
         #sql ="INSERT INTO RawData(Vehiculo, RawData) VALUES(?, ?)"
         sql = "SU5TRVJUIElOVE8gUmF3RGF0YShWZWhpY3VsbywgUmF3RGF0YSkgVkFMVUVTKD8sID8p"
         c.execute(base64.b64decode(sql).decode(), parametros)
         conn.close()
         return True
     except mariadb.Error as e:
         print("Al guardar RAWDATA: ", repr(e))
         return False
     except Exception as e:
         print("Al guardar RAWDATA: ", repr(e))
         return False
Example #4
0
    def execSQL(self, sql, method=None):
        """homeDB event tableにSQL直叩き.


        Args:
            sql (str): 叩きたいSQL.
            method (str, optional): mariadb.METHOD_xxxを指定. Defaults to None.

        Returns:
            [int or list]: MEHTODによって返りが異なる. INSERT,UPDATEはrowcount, それ以外はfetchall()の結果.
        """

        connection = mariadb.connect(user=self.DB_USER,
                                     database=self.DB_DATABASE,
                                     host=self.DB_HOST)

        cursor = connection.cursor()

        try:
            if method == mariaDbAgent.METHOD_INSERT or method == mariaDbAgent.METHOD_UPDATE:
                cursor.execute(sql)
                res = cursor.rowcount
                print(f'sql execute succeed. sql={sql}')
                print(f'sql res_rowcount: {res}')
            else:
                cursor.execute(sql)
                res = cursor.fetchall()

            print(f'sql execute succeed. sql={sql}')
            print(f'sql res: {res}')

        except Exception as e:
            print(e)
            res = None

        cursor.close()
        connection.close()

        return res
Example #5
0
def remove_lhs(DB_settings, id_link="%", id_hp="%", id_serv="%"):
    '''
    Remove a Link/Honeypot/Server combination from the internal database

    ARGUMENTS:
        DB_settings (dict) : all the settings to connect to the internal
            database
        id_link (string, optional) : the id of the link we want to remove from
            the internal database
        id_hp (string, optional) : the id of the hp we want to remove from the
            internal database
        id_serv (string, optional) : the id of the serv we want to remove from
            the internal database
    '''
    # Try to connect to the database
    try:
        DB_connection = mariadb.connect(user=DB_settings["username"],
                                        password=DB_settings["password"],
                                        host=DB_settings["hostname"],
                                        port=int(DB_settings["port"]),
                                        database=DB_settings["database"])
        logging.debug(f"[+] Connection to the internal database has started")
    except mariadb.Error as e:
        error = "[X] Can't connect to the internal database : " + str(e)
        logging.error(error)
        raise ValueError(error)
    # Try to remove the link from the internal database
    try:
        remove_in_IDB.lhs(DB_connection, id_link, id_hp, id_serv)
        DB_connection.close()
        logging.debug(
            f"[-] Connection to the internal database has been closed")
    except Exception as e:
        error = "Remove combination from the IDB failed : " + str(e)
        logging.error(error)
        DB_connection.close()
        logging.debug(
            f"[-] Connection to the internal database has been closed")
        raise ValueError(e)
Example #6
0
def getCateLocationTags():
    conn = None
    cursor = None
    data = None
    try:
        conn = mariadb.connect(user=dbcreds.user,
                               password=dbcreds.password,
                               host=dbcreds.host,
                               port=dbcreds.port,
                               database=dbcreds.database)
        print("a")
        cursor = conn.cursor()
        cursor.execute(
            "SELECT f.food_category , COUNT(*) FROM food f GROUP BY f.food_category ORDER BY 2 DESC"
        )
        category = cursor.fetchall()
        print(category)
        cursor.execute(
            "SELECT f.food_location , COUNT(*) FROM food f GROUP BY f.food_location ORDER BY 2 DESC"
        )
        location = cursor.fetchall()
        print(location)
        data = category + location
    except mariadb.ProgrammingError:
        print("program error...")
    except mariadb.DataError:
        print("Data error...")
    except mariadb.DatabaseError:
        print("Database error...")
    except mariadb.OperationalError:
        print("connect error...")
    finally:
        if (cursor != None):
            cursor.close()
        if (conn != None):
            conn.rollback()
            conn.close()
        if data != None:
            return data
Example #7
0
def getTweets(user_id, checkuser_id):
    conn = None
    cursor = None
    try:
        conn = mariadb.connect(user=dbcreds.user, password=dbcreds.password, host=dbcreds.host, port=dbcreds.port, database=dbcreds.database)
        cursor = conn.cursor()
        print(user_id)
        cursor.execute("SELECT t.id ,t.user_id ,u2.username ,u2.url ,t.content ,t.image ,t.created_at, u.notice FROM tweets t INNER JOIN `@_users` u ON u.tweet_id = t.id INNER JOIN users u2 ON t.user_id = u2.id WHERE u.user_id=? ORDER BY t.created_at DESC", [user_id])
        rows = cursor.fetchall()
        tweets = []
        headers = [ i[0] for i in cursor.description]
        headers[7]="atNotice"
        for row in rows:
            cursor.execute("SELECT COUNT(*) FROM comments c WHERE tweet_id = ?", [row[0],])
            com_amount = cursor.fetchone()[0]
            cursor.execute("SELECT COUNT(*) FROM tweet_like WHERE tweet_id = ?", [row[0],])
            like_amount = cursor.fetchone()[0]
            cursor.execute("SELECT COUNT(*) FROM tweet_like WHERE tweet_id = ? AND user_id = ?", [row[0], checkuser_id])
            iflike = cursor.fetchone()[0]
            tweet = dict(zip(headers,row))
            tweet['com_amount'] = com_amount   
            tweet['like_amount'] = like_amount   
            tweet['iflike'] = iflike
            tweets.append(tweet)   
    except mariadb.ProgrammingError:
        print("program error...")
    except mariadb.DataError:
        print("Data error...")
    except mariadb.DatabaseError:
        print("Database error...")
    except mariadb.OperationalError:
        print("connect error...")
    finally:
        if(cursor != None):
            cursor.close()
        if(conn != None):
            conn.rollback()
            conn.close()
        return tweets
Example #8
0
def reporters():
    import mariadb
    import sys
    try:
        conn = mariadb.connect(user="******",
                               password="******",
                               host="localhost",
                               port=3306,
                               database="flask_db")
    except mariadb.Error as e:
        print(f"Error connecting to MariaDB Platform: {e}")
        sys.exit(1)
    cur = conn.cursor()
    cur.execute('SELECT nickname, phone FROM reporter')
    result = ""
    result += "<!DOCTYPE html>"
    result += "<html lang=\"kor\">"
    result += "<head>"
    result += " <meta charset=\"UTF-8\">"
    result += " <title>리포터</title>"
    result += "</head>"
    result += "<body>"
    result += "<ul>"

    for (nickname, phone) in cur:
        #print("{},{}".format(nickname, phone))
        result += "<li>{}, {}</li>".format(nickname, phone)
    result += "</ul>"
    result += "</body>"
    result += "</html>"
    '''
    <ul>
        <li>신사임당, 01011112222</li>
        <li>이순신, 01011112222</li>
        <!-- 생략 -->
        <li>홍길동, 01011112222</li>
    </ul>
    '''
    return result
 def test_conpy69(self):
     conn= create_connection()
     cursor1= conn.cursor()
     cursor1.execute("CREATE SCHEMA IF NOT EXISTS 中文考试");
     default_conf= conf()
     default_conf["database"]= "中文考试"
     pool= mariadb.ConnectionPool(pool_name="test2")
     pool.set_config(**default_conf)
     for i in range(1,6):
         pool.add_connection()
     conn= mariadb.connect(pool_name="test2")
     cursor= conn.cursor()
     cursor.execute("select database()")
     row= cursor.fetchone()
     self.assertEqual(row[0], "中文考试")
     cursor.execute("CREATE TABLE t1 (a varchar(255)) character set utf8mb4")
     cursor.execute("insert into t1 values (?)", ("123.45 中文考试",))
     cursor.execute("select a from t1")
     row= cursor.fetchone()
     self.assertEqual(row[0], "123.45 中文考试")
     cursor1.execute("DROP SCHEMA 中文考试");
     del pool
def post():
    data = request.json
    conn = None
    cursor = None
    result = None
    loginToken=data.get("loginToken")
    tweetId = data.get("tweetId")
    
    if loginToken !="" and loginToken !=None and tweetId : 
        try:
            conn = mariadb.connect(user=dbcreds.user,password=dbcreds.password, host=dbcreds.host,port=dbcreds.port, database=dbcreds.database)
            cursor = conn.cursor()
            cursor.execute("SELECT user_id FROM `session` WHERE login_token=?",[loginToken,])
            user = cursor.fetchone()
            cursor.execute("SELECT user_id from tweet WHERE id = ? ",[tweetId,])
            notified = cursor.fetchone()
            cursor.execute("INSERT INTO tweet_likes (tweet_id,user_id)VALUES(?,?)", [tweetId,user[0] ,])
            conn.commit()
            cursor.execute("INSERT INTO notifications (user_id, notified_id,message) VALUES (?,?,?)",[user[0],notified[0],"Liked your tweet"])
            conn.commit()
            result = cursor.rowcount
        except mariadb.OperationalError as e:
            message = "connection error or wrong entry"
        except mariadb.IntegrityError as e:
            message = "Something is wrong with your data. probably there is another user using the same username or the same email"
        except Exception  as e:
            message = e
        finally:
            if(cursor != None):
                cursor.close()
            if(conn != None):
                conn.rollback()
                conn.close()

            if result == 1 :
                return Response("SUCCESS",mimetype="text/html",status=201)
            return Response(message ,mimetype="text/html",status=400)
    else:
        return Response("There is missing data" ,mimetype="text/html",status=400)
Example #11
0
 def serveScalper(self):
     try:
         conn = mariadb.connect(user=self.user,
                                password=self.password,
                                host=self.host,
                                port=self.port,
                                database=self.database)
     except mariadb.Error as e:
         print(f"Error connecting to MariaDB Platform: {e}")
     cur = conn.cursor()
     query = f"SELECT * FROM symbols ORDER BY servido ASC LIMIT 50"
     cur.execute(query)
     toServe = []
     for pair in cur:
         toServe.append(parseSymbol(pair))
     for i in toServe:
         #print(i[0])
         query = f"UPDATE symbols SET servido = '{datetime.now()}' WHERE symbol = '{i['symbol']}'"
         cur.execute(query)
         conn.commit()
     conn.close()
     return toServe
Example #12
0
def delete():
    token = request.json.get("loginToken")
    affected_rows = None
    try:
        conn = mariadb.connect(user = dbcreds.username , port = dbcreds.port , host = dbcreds.host , password = dbcreds.password , database = dbcreds.database)
        cursor = conn.cursor()
        cursor.execute("DELETE FROM user_session where login_token =? ",[token])
        conn.commit()
        affected_rows = cursor.rowcount
    except Exception as ex :
        print("exception is :" + ex )  
    finally:
        if(conn != None):
            conn.close()
        if (cursor != None):
            cursor.close()
        if affected_rows == 1:
            return Response("login success",mimetype="html/json",status=204)
        else:
            return Response("logout failed",mimetype="html/json",status=400)    

                                                
Example #13
0
 def GuardarFoto(self, parametros):
     try:
         conn = mariadb.connect(
             user="******",
             password=base64.b64decode(
                 'SXRhY2hpIFVjaGloYSB3aXBlIHRoZW0gYWxs').decode(),
             host="localhost",
             port=3306,
             database="logger")
         conn.autocommit = True
         c = conn.cursor()
         #sql ="INSERT INTO Fotos(Vehiculo, Foto) VALUES(?, ?)"
         sql = "SU5TRVJUIElOVE8gRm90b3MoVmVoaWN1bG8sIEZvdG8pIFZBTFVFUyg/LCA/KQ=="
         c.execute(base64.b64decode(sql).decode(), parametros)
         conn.close()
         return True
     except mariadb.Error as e:
         print("Al guardar la foto: ", repr(e))
         return False
     except Exception as e:
         print("Al guardar la foto: ", repr(e))
         return False
Example #14
0
	def connect(self, database, ini=False):
		# if connection exists, return
		if self.conn[database] is not None and not ini:
			return True
		if self.conn[database]:
			self.conn[database].close()
		try:
			self.conn[database] = mariadb.connect(
				# user="******",
				# password="******",
				user="******",
				password="******",
				host="cs527proj.c87d2nussxzu.us-east-2.rds.amazonaws.com",
				port=3306,
				database=database,
				autocommit=False
			)
			self.cur[database] = self.conn[database].cursor()
			return True
		except mariadb.Error as e:
			print(f"Connection failed: {e}")
			return False
Example #15
0
def login():
    if request.method == 'POST':

        conn = None
        cursor = None
        blogger_username = request.json.get("username")
        blogger_password = request.json.get("password")

        try:
            conn = mariadb.connect(user=dbcreds.user,
                                   password=dbcreds.password,
                                   host=dbcreds.host,
                                   database=dbcreds.database,
                                   port=dbcreds.port)
            cursor = conn.cursor()
            cursor.execute(
                "SELECT * FROM blogger WHERE username=? AND password=?",
                [blogger_username, blogger_password])
            user = cursor.fetchone()
            print(user)

        except Exception as error:
            print("something went wrong: ")
            print(error)
        finally:
            if (cursor != None):
                cursor.close()
            if (conn != None):
                conn.rollback()
                conn.close()
            if (user != None):

                return Response(json.dumps(user, default=str),
                                mimetype="text/html",
                                status=201)
            else:
                return Response("something went wrong",
                                mimetype="text/html",
                                status=501)
Example #16
0
def viewTable(tablename=None, limit=100):
    """This should only be allowed to viewed by admin users
    since it's kind of dangerous to leave this open to the
    general user"""
    if not tablename:
        return render_template(
            'error.html',
            error="Format is //table//tablename//limit where limit is option")
    success = True
    err = None
    try:
        dbTable = paramToDBMap[tablename]['tableName']
        conn = mariadb.connect(**dbConfig)
        cursor = conn.cursor()
        query = f"SELECT * FROM {dbTable} LIMIT {limit}"
        print(query)
        cursor.execute(query)
        row_headers = [x[0] for x in cursor.description]
        print(f"row headers {row_headers}")
        rv = cursor.fetchall()
        print(rv)
    except KeyError:
        return render_template("error.html", error="Table does not exist")
    except Exception as e:
        print("error")
        print(str(e))
        success = False
        err = e
    finally:
        conn.close()
    if success:
        print(f"title: {dbTable}")
        print(f"header: {row_headers}")
        return render_template('tableview.html',
                               title=dbTable,
                               headers=row_headers,
                               data=rv)
    else:
        return render_template('error.html', error=err)
def deleteTweet(token, tweet_id):
    conn = None
    cursor = None
    row = None
    user_id = None
    try:
        conn = mariadb.connect(user=dbcreds.user,
                               password=dbcreds.password,
                               host=dbcreds.host,
                               port=dbcreds.port,
                               database=dbcreds.database)
        cursor = conn.cursor()
        cursor.execute("SELECT user_id FROM token WHERE token=?", [
            token,
        ])
        user_id = cursor.fetchone()[0]
        if user_id != None:
            cursor.execute("DELETE FROM tweets WHERE user_id=? AND id=?",
                           [user_id, tweet_id])
            conn.commit()
            row = cursor.rowcount
    except mariadb.ProgrammingError:
        print("program error...")
    except mariadb.DataError:
        print("Data error...")
    except mariadb.DatabaseError:
        print("Database error...")
    except mariadb.OperationalError:
        print("connect error...")
    finally:
        if (cursor != None):
            cursor.close()
        if (conn != None):
            conn.rollback()
            conn.close()
        if row == 1:
            return True
        else:
            return False
Example #18
0
def connect_database(update=None, context=None):
    try:
        conn = mariadb.connect(user=mariadbUser,
                               password=mariadbPassword,
                               host=mariadbHost,
                               port=mariadbPort,
                               database=mariadbDatabase,
                               autocommit=True)
        return conn
    except mariadb.Error as e:
        print(f"Error connecting to MariaDB Platform: {e}")
        if update != None and context != None:
            if update.message.from_user.id in adminIds:
                context.bot.send_message(
                    chat_id=update.effective_chat.id,
                    text=
                    f'Ho ricevuto un errore nel connettermi al database: {e}')
            else:
                context.bot.send_message(
                    chat_id=update.effective_chat.id,
                    text=f'C'
                    'è stato un errore, riprova più tardi')
Example #19
0
    def __init__(self,
                 password,
                 database,
                 user="******",
                 host="localhost",
                 port=3306):
        # Instantiate Connection
        try:
            self.connection = mariadb.connect(user=user,
                                              password=password,
                                              host=host,
                                              port=port,
                                              database=database)

            self.cursor = None
            self.connected = True
        except mariadb.Error as e:
            print(f"Error connecting to MariaDB Platform: {e}")
            self.connected = False

        if self.connected:
            self.cursor = self.connection.cursor()
Example #20
0
def insertaggregation(methodid, populationid, df):
    try:
        conn = mariadb.connect(**dbconfig)
    except mariadb.Error as e:
        print(f"Error connecting to MariaDB Platform: {e}")
        sys.exit(1)

    cur = conn.cursor()
    query = "INSERT INTO aggindicator(realindicatorid,description,formula,fk_methodid,fk_populationid,fk_periodid) VALUES (?,?,?,?,?,?)"
    for i in range(len(df)):
        realindicatorid = df['AggIndID'][i]
        description = df['Description'][i]
        formula = df['formula'][i]
        periodid = df['period'][i]
        parameters = (realindicatorid, description, formula, int(methodid),
                      int(populationid), int(periodid))
        try:
            cur.execute(query, (parameters))
        except mariadb.Error as e:
            print(f"Error: {e}")
    conn.commit()
    conn.close()
    def get_device(self, id):

        print("get_device - entro en la funcion")

        device = {}

        try:
            conn = mariadb.connect(user=os.getenv('MARIADB_USERNAME'),
                                   password=os.getenv('MARIADB_PASSWORD'),
                                   host=os.getenv('MARIADB_HOST'),
                                   database='prometeo',
                                   port=int(os.getenv('MARIADB_PORT')))

            cursor = conn.cursor()

            cursor.execute(
                'SELECT IntSensorId, SensorID, model, version FROM sensors WHERE deleted_at IS NULL AND IntSensorId = ?',
                (id, ))

            data = cursor.fetchone()

            if len(data) > 0:
                device = {
                    'id': data[0],
                    'code': data[1],
                    'model': data[2],
                    'version': data[3]
                }
            else:
                return None

        except Exception as e:
            return None

        finally:
            cursor.close()
            conn.close()

        return device
Example #22
0
def get():
    params=request.args
    userId= params.get("userId")
    conn = None
    cursor = None
    result = None
    if userId:
        try:
            conn = mariadb.connect(user=dbcreds.user,password=dbcreds.password, host=dbcreds.host,port=dbcreds.port, database=dbcreds.database)
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM users INNER JOIN  user_follows uf ON id=uf.followId WHERE uf.user_id =?" ,[userId,])
            result=cursor.fetchall()
        except mariadb.OperationalError as e:
            message = "connection error or wrong entry"
        except:
            message =  "somthing went wrong"
        finally:
            if(cursor != None):
                cursor.close()
            if(conn != None):
                conn.rollback()
                conn.close()
            if result or result==[]:
                users=[]
                for row in result:
                    user = {

                    "userId":row[4],    
                    "email":row[1],
                    "username":row[0],
                    "bio":row[2],
                    "birthdate":row[5],   
                    }
                    users.append(user)
                return Response(json.dumps(users,default=str),mimetype="application/json",status=200)
            else:
                return Response("failed",mimetype="text/html",status=400)
    else:
        return Response("somthing wen wrong",mimetype="text/html",status=400)
Example #23
0
def createDatabase(databaseName):
    connection = mariadb.connect(pool_name="create_pool",
                                 pool_size=1,
                                 host="store.usr.user.hu",
                                 user="******",
                                 password="******")

    cursor = connection.cursor()
    sqlDropDatabaseScript = "DROP DATABASE IF EXISTS " + databaseName
    cursor.execute(sqlDropDatabaseScript)
    connection.commit()
    sqlCreateSchemaScript = "CREATE DATABASE IF NOT EXISTS " + databaseName + " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
    cursor.execute(sqlCreateSchemaScript)
    connection.commit()
    cursor.execute("USE " + databaseName)
    file = open("SQL create table transaction.txt", "r")
    sqlCreataTableScript = file.read()
    cursor.execute("DROP TABLE IF EXISTS transaction")
    cursor.execute(sqlCreataTableScript)
    connection.commit()
    connection.close()
    print(f"{databaseName} created")
Example #24
0
def login_check(alias, password):
    conn = None
    cursor = None
    try:
        conn = mariadb.connect(user=dbcreds.user, password=dbcreds.password, port=dbcreds.port, database=dbcreds.database, host=dbcreds.host)
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM hackers WHERE alias=? AND password=?", [alias, password])
        hackers = cursor.fetchall()
        for hacker in hackers:
            if alias == hacker[0] and password == hacker[1]:
                return True
        return False
    except mariadb.ProgrammingError:
        print("You need lessons.")
    except mariadb.OperationalError:
        print("There seems to be something wrong with the connection.")
    finally:
        if(cursor != None):
            cursor.close()
        if(conn != None):
            conn.rollback()
            conn.close()
Example #25
0
def signup():
    if request.method == 'POST':

        conn = None
        cursor = None
        blogger_username = request.json.get("username")
        blogger_password = request.json.get("password")
        print(blogger_username)
        rows = None
        try:
            conn = mariadb.connect(user=dbcreds.user,
                                   password=dbcreds.password,
                                   host=dbcreds.host,
                                   database=dbcreds.database,
                                   port=dbcreds.port)
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO blogger(username,password) VALUES(?,?)",
                [blogger_username, blogger_password])
            conn.commit()
            rows = cursor.rowcount
        except Exception as error:
            print("something went wrong: ")
            print(error)
        finally:
            if (cursor != None):
                cursor.close()
            if (conn != None):
                conn.rollback()
                conn.close()
            if (rows == 1):
                return Response("you made an account",
                                mimetype="text/html",
                                status=201)
            else:
                return Response("something went wrong",
                                mimetype="text/html",
                                status=501)
Example #26
0
def post_user():
    email = request.json.get("email")
    username = request.json.get("username")
    password = request.json.get("password")
    bio = request.json.get("bio")
    birthday = request.json.get("birthday")
    affected_rows = None
    userId = None

    try:
        conn = mariadb.connect(user = dbcreds.username , port = dbcreds.port , host = dbcreds.host , password = dbcreds.password , database = dbcreds.database)
        cursor = conn.cursor()
        cursor.execute("INSERT INTO users (username,email,,password,bio,birthday) Values(?,?,?,?,?)", [username,email,password,bio,birthday])
        conn.commit()
        userId = cursor.lastrowid
        token = secrets.token_urlsafe(24)
        cursor.execute("INSERT INTO user_session VALUES (?,?)", [userId,token])
        conn.commir()
        affected_rows = cursor.rowcount
    except Exception as ex :
        print("exception is :" + ex )  
    finally:
        if(conn != None):
            conn.close()
        if (cursor != None):
            cursor.close()
        if affected_rows == 1:
            user = {
                "userId": userId,
                "email": email,
                "username": username,
                "bio": bio,
                "birthday": birthday,
                "logintoken": token
            }
            return Response (json.dumps(user,default=str),mimetype="application/json",status=201)
        else:
            return Response("user insert failed",mimetype="html/text",status=400)    
Example #27
0
def login():

    # Output message if something goes wrong...
    msg = ''

    # Declaration of the global variable Current User Id to be able to modify its value
    global CURRENT_USER_ID

    # Check if "username" and "password" POST requests exist (user submitted form)
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:

        # Create variables for easy access
        username = request.form['username']
        password = request.form['password']

        # connection for MariaDB
        conn = mariadb.connect(**config)
        cursor = conn.cursor()
        cursor.execute(
            'SELECT * FROM USUARIO WHERE Usuario = %s AND Password = %s',
            (username, password))

        # Fetch one record and return result
        account = cursor.fetchone()

        # If account exists in User table in out database
        if account:
            # Get the User Id from the BBDD
            CURRENT_USER_ID = account[0]
            #Let's go to the home page
            return redirect(url_for('index'))

        else:
            # Account doesnt exist or username/password incorrect
            msg = 'Login Incorrecto'

    # Show the login form with message (if any)
    return render_template('login.html', msg=msg)
def signUp(email, username, password, birthdate, bio, date, url):
    conn = None
    cursor = None
    row = None
    user = {}
    try:
        conn = mariadb.connect(user=dbcreds.user,
                               password=dbcreds.password,
                               host=dbcreds.host,
                               port=dbcreds.port,
                               database=dbcreds.database)
        cursor = conn.cursor()
        print("1")
        print(date)
        cursor.execute(
            "INSERT INTO users(username, email, birthdate, bio, password, join_date, url) VALUES (?, ?, ?, ?, ?, ?, ?)",
            [username, email, birthdate, bio, password, date, url])
        print("b")
        conn.commit()
        row = cursor.rowcount
    except mariadb.ProgrammingError:
        print("program error...")
    except mariadb.DataError:
        print("Data error...")
    except mariadb.DatabaseError:
        print("Database error...")
    except mariadb.OperationalError:
        print("connect error...")
    finally:
        if (cursor != None):
            cursor.close()
        if (conn != None):
            conn.rollback()
            conn.close()
        if row == 1:
            return True
        else:
            return False
Example #29
0
def modify_hacker_exploits(alias, password):
    conn = None
    cursor = None
    try:
        conn = mariadb.connect(user=dbcreds.user, password=dbcreds.password, port=dbcreds.port, database=dbcreds.database, host=dbcreds.host)
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM hackers WHERE alias =? AND password =?", [alias, password])
        row = cursor.fetchone()
        id = row[2]
        cursor.execute("SELECT * FROM exploits WHERE user_id=?", [id])
        old_contents = cursor.fetchall()
        for old_content in old_contents:
            print(old_content[0])
            print(old_content[1])              
        pick_id = input("Please type id of exploits you would like to modify: ")
        print("Please type your new exploit:")
        new_content = input()                           
        cursor.execute("UPDATE exploits SET content=? WHERE id=?", [new_content, pick_id])
        conn.commit()
        if(cursor.rowcount == 1):
            print("Congrats, exploit has been updated!")
        else:
            print("Shame, exploit has not been updated!")
        print(row[0])
        cursor.execute("SELECT * FROM exploits WHERE user_id=?", [id])
        updated_contents = cursor.fetchall()
        for updated_content in updated_contents:
            print(updated_content[1])
    except mariadb.ProgrammingError:
        print("You need lessons.")
    except mariadb.OperationalError:
        print("There seems to be something wrong with the connection.")
    finally:
        if(cursor != None):
            cursor.close()
        if(conn != None):
            conn.rollback()
            conn.close()
Example #30
0
def get():
    program_id = request.args.get("programId")
    conn = None
    cursor = None
    excercises = None
    try:
        conn = mariadb.connect(user=dbcreds.username,
                               port=dbcreds.port,
                               host=dbcreds.host,
                               password=dbcreds.password,
                               database=dbcreds.database)
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM excercise where program_id = ?",
                       [program_id])
        excercises = cursor.fetchall()
    except Exception as ex:
        print(ex)
    finally:
        if (conn != None):
            conn.close()
        if (cursor != None):
            cursor.close
        if (excercises != None):
            excercisesList = []
            for excercise in excercises:
                excer = {
                    "excerciseId": excercise[0],
                    "programId": excercise[4],
                    "title": excercise[1],
                    "description": excercise[2],
                    "period": excercise[3]
                }
                excercisesList.append(excer)
            return Response(json.dumps(excercisesList, default=str),
                            mimetype="application/json",
                            status=200)
        else:
            return Response("Bad request", mimetype="html/text", status=400)