示例#1
0
    def post(self):

        parser = reqparse.RequestParser()
        """collecting args"""
        parser.add_argument('username', type=str, required=True)
        parser.add_argument('email', type=str, required=True)
        parser.add_argument('password', type=str, required=True)
        """getting specific args"""
        args = parser.parse_args()
        username = args['username']
        email = args['email']
        password = args['password']

        if username.strip() == "" or len(username.strip()) < 3:
            return make_response(
                jsonify({
                    "message":
                    "invalid username, Enter correct username please"
                }), 400)
        """to ignore symblos in the username by regular expressions"""

        if re.compile('[!@#$%^&*:;?><.0-9]').match(username):
            return make_response(
                jsonify({
                    "message":
                    "Invalid characters not allowed, numbers and symbols are not allowed"
                }), 400)
        """to check for a valid email"""

        if not re.match(r"([\w\.-]+)@([\w\.-]+)(\.[\w\.]+$)", email):
            return make_response(jsonify({"message": "Enter valid email"}),
                                 400)

        if password.strip() == "" or password.strip() == " " or password.strip(
        ) == "   ":
            return make_response(
                jsonify({"message":
                         "Password Empty, Enter a valid  password"}), 400)

        if len(password.strip()) < 5:
            return make_response(
                jsonify({"message": "Password is too short, < 5"}), 400)
        """creating a sign up  cursor to check for already existing users."""

        conn = configconnection()
        cur = conn.cursor()

        cur.execute("SELECT username from users where username=%s", [username])
        rows = cur.fetchone()

        if rows:

            return make_response(jsonify({"message": 'Username is used'}), 400)
        else:
            cur.execute(
                "INSERT INTO users (username,email,password) VALUES ('" +
                username + "','" + email + "','" + password + "')")
            conn.commit()
            return make_response(
                jsonify({"message": 'User created successfully'}), 201)
示例#2
0
    def put(self, entryId):

        parser = reqparse.RequestParser()
        """collecting args"""

        parser.add_argument('title', type=str, required=True)
        parser.add_argument('content', type=str, required=True)
        parser.add_argument('date', type=str, required=True)
        parser.add_argument('token', location='headers')
        """getting specific args"""
        args = parser.parse_args()
        title = args['title']
        content = args['content']
        date = args['date']

        token = args['token']

        if not token:
            return make_response(jsonify({'message': 'token missing'}), 400)
        """ implementing token decoding"""
        decoded = decode_token(token)
        if decoded["status"] == "Failure":
            return make_response(jsonify({"message": decoded["message"]}), 401)

        try:
            conn = configconnection()
            cur = conn.cursor()
            cur.execute(
                "UPDATE entries SET title=%s,content=%s,date=%s where id=%s",
                (title, content, date, entryId))
            conn.commit()
            return make_response(
                jsonify({'message': 'entry updated successfully'}), 200)
        except:
            return make_response(jsonify({'message': 'entry not found'}), 404)
示例#3
0
    def get(self):
        parser = reqparse.RequestParser()
        """collecting args"""
        parser.add_argument('token', location='headers')
        """getting specific args"""
        args = parser.parse_args()
        token = args['token']

        if not token:
            return make_response(jsonify({'message': 'token missing'}), 400)
        """ implementing token decoding"""
        decoded = decode_token(token)
        if decoded["status"] == "Failure":
            return make_response(jsonify({"message": decoded["message"]}), 401)
        conn = configconnection()
        cur = conn.cursor()
        cur.execute("SELECT * from entries")
        result = cur.fetchall()

        lst = []
        for info in result:

            dic = {}
            dic["id"] = info[0]
            dic["title"] = info[1]
            dic["content"] = info[2]
            dic["date"] = info[3]
            lst.append(dic)
        return lst, 200
示例#4
0
    def insert_entries(self):

        parser = reqparse.RequestParser()
        """collecting args"""
        parser.add_argument('token', location='headers')
        parser.add_argument('title', type=str, required=True)
        parser.add_argument('content', type=str, required=True)
        parser.add_argument('date', type=str, required=True)
        """getting specific args"""
        args = parser.parse_args()
        title = args['title']
        content = args['content']
        date = args['date']

        token = args['token']

        if not token:
            return make_response(jsonify({'message': 'token missing'}), 400)
        """ implementing token decoding"""
        decoded = decode_token(token)
        if decoded["status"] == "Failure":
            return make_response(jsonify({"message": decoded["message"]}), 401)
        conn = configconnection()
        cur = conn.cursor()
        cur.execute("INSERT INTO entries (title,content,date) VALUES ('" +
                    title + "','" + content + "','" + date + "')")
        conn.commit()

        return make_response(
            jsonify({'message': 'Created an entry successfully.'}), 201)
示例#5
0
    def post(self):

        parser = reqparse.RequestParser()
        """collecting args"""
        parser.add_argument('username', type=str, required=True)
        parser.add_argument('password', type=str, required=True)
        """getting specific args"""
        args = parser.parse_args()
        username = args['username']
        password = args['password']

        if username.strip() == "" or len(username.strip()) < 3:
            return make_response(
                jsonify({
                    "message":
                    "invalid username, Enter correct username please"
                }), 400)
        """to ignore symblos in the username by regular expressions"""

        if re.compile('[!@#$%^&*:;?><.0-9]').match(username):
            return make_response(
                jsonify({
                    "message":
                    "Invalid characters not allowed, numbers and symbols are not allowed"
                }), 400)

        if password.strip() == "" or password.strip() == " " or password.strip(
        ) == "   ":
            return make_response(
                jsonify({"message":
                         "Password Empty, Enter a valid  password"}), 400)

        conn = configconnection()
        cur = conn.cursor()
        cur.execute(
            "select username from users where username=%s and password=%s ",
            (username, password))

        rows = cur.fetchone()

        if rows:
            token = generate_token(username)
            return make_response(
                jsonify({
                    "message": 'User signed in successfully',
                    'token': token
                }), 200)

        else:
            return make_response(
                jsonify({"message": 'invalid username or password'}), 400)
示例#6
0
    def post(self):
        conn = configconnection()
        try:

            return self.insert_entries()

        except psycopg2.DatabaseError as e:
            if conn:
                print(e)
                conn.rollback()
                return self.insert_entries()
        except psycopg2.InterfaceError as Ie:
            print(Ie)
            return self.insert_entries()
示例#7
0
class Database:

    connection = configconnection()
    cursor = connection.cursor()

    def create_db_tables(self):
        """creates all the tables for the db"""
        create_table = "CREATE TABLE IF NOT EXISTS userstable\
        ( user_id SERIAL PRIMARY KEY, name VARCHAR(150), username VARCHAR(100) UNIQUE, password VARCHAR(100))"

        self.cursor.execute(create_table)

        create_table = "CREATE TABLE IF NOT EXISTS questionstable\
        (questionid SERIAL PRIMARY KEY, user_id INTEGER, \
        FOREIGN KEY (user_id) REFERENCES userstable (user_id) ON UPDATE CASCADE ON DELETE CASCADE,\
        title VARCHAR(255), body VARCHAR,tag VARCHAR(255), posted_at TIMESTAMP DEFAULT NOW())"

        self.cursor.execute(create_table)

        create_table = "CREATE TABLE IF NOT EXISTS answerstable\
        (answer_id SERIAL PRIMARY KEY, questionid INTEGER NOT NULL, \
        FOREIGN KEY (questionid) REFERENCES questionstable (questionid) ON UPDATE CASCADE ON DELETE CASCADE,\
        content VARCHAR(255), user_id INTEGER NOT NULL, \
        FOREIGN KEY (user_id) REFERENCES userstable (user_id) ON UPDATE CASCADE ON DELETE CASCADE)"

        self.cursor.execute(create_table)
        self.connection.commit()

    def insert_user_data(self, name, username, password):
        """insert user"""
        insert_cmd = "INSERT INTO userstable (name, username, password) VALUES\
         ('{}', '{}', '{}');".format(name, username, password)
        self.cursor.execute(insert_cmd)
        self.connection.commit()

    def get_by_parameter(self, table, column_name, parameter):
        fetch_cmd = "SELECT * FROM {} WHERE {} = '{}';".format(
            table, column_name, parameter)
        self.cursor.execute(fetch_cmd)
        result = self.cursor.fetchone()
        return result

    def get_all(self, table):
        fetchall_cmd = "SELECT * FROM {} ;".format(table)
        self.cursor.execute(fetchall_cmd)
        result = self.cursor.fetchall()
        if result:
            return result
        return None

    def insert_question_data(self, user_id, title, body, tag):
        """insert question"""
        insertquestion_cmd = "INSERT INTO questionstable (user_id,title, body, tag) VALUES\
         ('{}','{}', '{}', '{}');".format(user_id, title, body, tag)
        self.cursor.execute(insertquestion_cmd)
        self.connection.commit()

    def delete_question(self, owner_id, questionid):
        """delete question"""
        selected_quest_statement = "SELECT * FROM questionstable WHERE questionid={};".format(
            questionid)
        self.cursor.execute(selected_quest_statement)
        selected_quest = self.cursor.fetchone()
        self.connection.commit()
        author_id = selected_quest[1]
        if author_id == owner_id:
            deletequestion_cmd = "DELETE FROM questionstable WHERE questionid='{}';".format(
                questionid)
            self.cursor.execute(deletequestion_cmd)
            self.connection.commit()
            return True
        return False

    def insert_answer_data(self, user_id, questionid, content):
        """insert question"""
        insertquestion_cmd = "INSERT INTO answerstable (user_id,questionid,content) VALUES\
         ('{}', '{}', '{}');".format(user_id, questionid, content)
        self.cursor.execute(insertquestion_cmd)
        self.connection.commit()

    def update_answer_data(self, answer_ID, questionid, content):
        """insert question"""
        insertquestion_cmd = "UPDATE  answerstable SET content='{}' where questionid='{}' and answer_id='{}';".format(
            content, questionid, answer_ID)
        self.cursor.execute(insertquestion_cmd)
        self.connection.commit()