def decorated(*args, **kwargs): token = get_token() try: database = Database() data = jwt.decode( token, 'trulysKey', ) query = database.get_user_by_value('users', 'user_id', data['user_id']) if not query: return {"message": "User does not exist"}, 400 current_user = User(query[0], query[1], query[2], query[3], query[4], query[5]) except jwt.ExpiredSignatureError as e: return response_message('Error', 'Signature expired,please login again', 401) except jwt.InvalidSignatureError as serr: return response_message('Error', 'Signature is invalid,please login again', 401) except jwt.DecodeError: return response_message('Error', 'please login', 401) return f(current_user, *args, **kwargs)
def test_create(self): Database.execute_schema() test_app = app.test_client() response = test_app.post('/users', data=json.dumps({ "firstname": "user", }), content_type=content_type.JSON) assert response.status_code == 200 user1_id = int(response.data.decode('utf-8')) response = test_app.post('/articles', data=json.dumps({ "title": "mon article", "text": "blabla", "writer": user1_id }), content_type=content_type.JSON) assert response.status_code == 200 article1_id = int(response.data.decode('utf-8')) response = test_app.post('/articles/' + str(article1_id) + '/comments', data=json.dumps({ "text": "blabla", "writer": user1_id }), content_type=content_type.JSON) assert response.status_code == 200
def test_create(self): time_before = datetime.now() Database.execute_schema() test_app = app.test_client() response = test_app.post('/users', data=json.dumps({"firstname": "john"}), content_type=content_type.JSON) assert response.status_code == 200 user1_id = response.data.decode("utf-8") response = test_app.post('/users/' + user1_id + '/notifications', data=json.dumps({"text": "hello"}), content_type=content_type.JSON) assert response.status_code == 200 response = test_app.get('/users/' + user1_id + '/inbox') assert response.status_code == 200 messages = json.loads(response.data) assert len(messages) == 1 assert messages[0]['type'] == 'NOTIFICATION' time = datetime.strptime(messages[0]['time'], date_format.CLASSIC) assert time > time_before assert time < datetime.now()
def test_name_validation_number(self): Database.execute_schema() test_app = app.test_client() response = test_app.post('/users', data=json.dumps({ "firstname": "test1" }), content_type=content_type.JSON) assert response.status_code == 400
def __init__(self, master, **options): super().__init__(master) self.options = options self.database = Database() self.plan_exists_in_db = False self.master = master self.bind('<Control-s>', self.save) self.create_widgets(**options)
def test_date_order(self): Database.execute_schema() test_app = app.test_client() response = test_app.post('/users', data=json.dumps({"firstname": "john"}), content_type=content_type.JSON) assert response.status_code == 200 user1_id = response.data.decode("utf-8") response = test_app.post('/users', data=json.dumps({"firstname": "jane"}), content_type=content_type.JSON) assert response.status_code == 200 user2_id = response.data.decode("utf-8") response = test_app.post('/messages', data=json.dumps({ "from_user": 1, "to_user": 2, "text": "..." }), content_type=content_type.JSON) assert response.status_code == 200 message1_id = response.data.decode("utf-8") response = test_app.post('/users/' + user2_id + '/notifications', data=json.dumps({ "to_user": 2, "text": "..." }), content_type=content_type.JSON) assert response.status_code == 200 notification1_id = response.data.decode("utf-8") response = test_app.post('/messages', data=json.dumps({ "from_user": 1, "to_user": 2, "text": "..." }), content_type=content_type.JSON) assert response.status_code == 200 message2_id = response.data.decode("utf-8") response = test_app.get('/users/' + user2_id + '/inbox') assert response.status_code == 200 messages = json.loads(response.data) assert len(messages) == 3 assert messages[0]['id'] == int( message1_id) and messages[0]['type'] == message_types.USER assert messages[1]['id'] == int(notification1_id) and messages[1][ 'type'] == message_types.NOTIFICATION assert messages[2]['id'] == int( message2_id) and messages[2]['type'] == message_types.USER
def test_create(self): Database.execute_schema() test_app = app.test_client() response = test_app.post('/users', data=json.dumps({ "firstname": "test" }), content_type=content_type.JSON) assert response.status_code == 200 user_id = response.data.decode('utf-8') response = test_app.get('/users/' + user_id) assert response.status_code == 200 user = json.loads(response.data) assert user['firstname'] == 'test'
def test_search(self): Database.execute_schema() test_app = app.test_client() response = test_app.post('/users', data=json.dumps({"firstname": "john"}), content_type=content_type.JSON) assert response.status_code == 200 user1_id = int(response.data.decode('utf-8')) response = test_app.post( '/articles', data=json.dumps({ "title": "article 1", "text": "bla bla des phrases, hop bilbo, du bla bla", "writer": user1_id }), content_type=content_type.JSON) assert response.status_code == 200 article1_id = int(response.data.decode("utf-8")) response = test_app.post( '/articles', data=json.dumps({ "title": "article 2", "text": "bla bla des phrases, hop baggins, du bla bla", "writer": user1_id }), content_type=content_type.JSON) assert response.status_code == 200 article2_id = int(response.data.decode("utf-8")) response = test_app.post('/articles', data=json.dumps({ "title": "article 3", "text": "bilbo", "writer": user1_id }), content_type=content_type.JSON) assert response.status_code == 200 article3_id = int(response.data.decode("utf-8")) response = test_app.get('/articles/search/bilbo') assert response.status_code == 200 search_results = json.loads(response.data) assert len(search_results) == 2 assert article1_id in [result['id'] for result in search_results] assert not article2_id in [result['id'] for result in search_results] assert article3_id in [result['id'] for result in search_results]
def __init__(self): self.base_price = 1.5 self.trulyKey = os.environ.get('TRULYS_KEY', '') self.categories = { "0-5": 1, "6-30": 3, "31-60": 6, "70-100": 9, "101-300": 12, "301-499": 15, "500-1000": 18, "1001-5000": 25 } db = Database() self.parcels = db.get_all_parcels()
def test_update(self): Database.execute_schema() test_app = app.test_client() user_id = UserDao.create({'firstname': 'toto'}) assert user_id > 0 response = test_app.put('/users/' + str(user_id), data=json.dumps({"firstname": "testupdate"}), content_type=content_type.JSON) assert response.status_code == 200 response = test_app.get('/users/' + str(user_id)) assert response.status_code == 200 user = json.loads(response.data) assert user['firstname'] == 'testupdate'
def test_delete(self): Database.execute_schema() test_app = app.test_client() response = test_app.post('/users', data=json.dumps({ "firstname": "test" }), content_type=content_type.JSON) assert response.status_code == 200 user_id = response.data.decode("utf-8") response = test_app.delete('/users/' + user_id) assert response.status_code == 200 response = test_app.get('/users') assert response.status_code == 200 assert len(json.loads(response.data)) == 0
def test_delete(self): Database.execute_schema() test_app = app.test_client() response = test_app.post('/users', data=json.dumps({"firstname": "test"}), content_type=content_type.JSON) assert response.status_code == 200 user_id = response.data.decode('utf-8') response = test_app.delete('/users/' + str(user_id)) print(response.status_code) assert response.status_code == 204 response = test_app.get('/users/' + user_id) assert response.status_code == 404
def exists(model): return len( Database.read( """ SELECT * FROM article_reverse_index WHERE article_id = ? AND word = ? """, [model['article_id'], model['word']])) > 0
def create(model): return Database.create( """ INSERT INTO message(from_user, to_user, text, time) VALUES (?, ?, ?, ?); """, [ model['from_user'], model['to_user'], model['text'], model['time'] ])
def create(model): return Database.create( """ INSERT INTO comment(text, time, writer, article_id) VALUES (?, ?, ?, ?) """, [ model['text'], model['time'], model['writer'], model['article_id'] ])
def test_create(self): Database.execute_schema() test_app = app.test_client() time_before = datetime.now() response = test_app.post('/articles', data=json.dumps({ "title": "Titre", "text": "text", "writer": "moi" }), content_type=content_type.JSON) time_after = datetime.now() assert response.status_code == 200 article_id = response.data.decode('utf-8') article = ArticleDao.get(article_id) time = datetime.strptime(article['time'], DATE_FORMAT) assert article['title'] == 'Titre' and article['text'] == 'text' and article['writer'] == 'moi' \ and time_before < time < time_after
def test_create(self): Database.execute_schema() test_app = app.test_client() user_id = UserDao.create({'firstname': 'toto'}) assert user_id > 0 response = test_app.post('/users/' + str(user_id) + '/notifications', data=json.dumps({"text": "test"}), content_type=content_type.JSON) assert response.status_code == 200 notifications_id = json.loads(response.data) response = test_app.get('/users/' + str(user_id) + '/notifications') assert response.status_code == 200 notification = json.loads(response.data) assert notification[0]['id'] == notifications_id assert notification[0]['to_user'] == user_id assert notification[0]['text'] == 'test'
def test_create(self): time_before = datetime.now() Database.execute_schema() test_app = app.test_client() response = test_app.post('/users', data=json.dumps({"firstname": "john"}), content_type=content_type.JSON) assert response.status_code == 200 user1_id = response.data.decode("utf-8") response = test_app.post('/users', data=json.dumps({"firstname": "jane"}), content_type=content_type.JSON) assert response.status_code == 200 user2_id = response.data.decode("utf-8") response = test_app.post('/messages', data=json.dumps({ "from_user": 1, "to_user": 2, "text": "Hello !" }), content_type=content_type.JSON) assert response.status_code == 200 response = test_app.get('/users/' + user1_id + '/outbox') assert response.status_code == 200 messages = json.loads(response.data) assert len(messages) == 1 assert messages[0]['text'] == 'Hello !' assert messages[0]['to']['firstname'] == 'jane' time = datetime.strptime(messages[0]['time'], date_format.CLASSIC) assert time > time_before assert time < datetime.now() response = test_app.get('/users/' + user2_id + '/inbox') assert response.status_code == 200 messages = json.loads(response.data) assert len(messages) == 1 assert messages[0]['text'] == 'Hello !' assert messages[0]['from']['firstname'] == 'john' assert messages[0]['type'] == 'USER'
def get(article_id): results = Database.read( """ SELECT * FROM article WHERE id = ? """, [article_id]) if len(results) > 0: return results[0] else: raise ItemNotFoundException()
def test_comment_notification(self): Database.execute_schema() test_app = app.test_client() response = test_app.post('/users', data=json.dumps({"firstname": "john"}), content_type=content_type.JSON) assert response.status_code == 200 user1_id = int(response.data.decode('utf-8')) response = test_app.post('/users', data=json.dumps({"firstname": "jane"}), content_type=content_type.JSON) assert response.status_code == 200 user2_id = int(response.data.decode('utf-8')) response = test_app.post('/articles', data=json.dumps({ "title": "mon article", "text": "blabla", "writer": user1_id }), content_type=content_type.JSON) assert response.status_code == 200 article1_id = int(response.data.decode('utf-8')) response = test_app.post('/articles/' + str(article1_id) + '/comments', data=json.dumps({ "text": "blabla", "writer": user2_id }), content_type=content_type.JSON) assert response.status_code == 200 response = test_app.get('/users/' + str(user1_id) + '/inbox') assert response.status_code == 200 messages = json.loads(response.data) assert len(messages) == 1 assert messages[0]['type'] == message_types.NOTIFICATION
def get_users(current_user): if not db.is_admin(current_user.user_id): return response_message('unauthorized operation', 'Only admin users can view all users', 401) users = Database().get_users() user_list = [] for user in users: user_dict = { "user_id": user[0], "fullname": user[1], "username": user[2], "email": user[3], "phone_number": user[5], "is_admin": user[6], "joined": user[7] } user_list.append(user_dict) return jsonify({"users": user_list}), 200
def __init__(self, launcher, name, shard_ids, max_shards): self.launcher = launcher self.process = None self.kwargs = dict( intents=INTENTS, allowed_mentions=NO_MENTIONS, case_insensitive=True, token=TOKEN, shard_ids=shard_ids, shard_count=max_shards, cluster_name=name, cache=Cache(), db=Database( os.getenv("DB_NAME"), os.getenv("DB_USER"), os.getenv("DB_PASSWORD"), ), theme_color=config.THEME_COLOR, dark_theme_color=config.DARK_THEME_COLOR, error_color=config.ERROR_COLOR, initial_extensions=EXTENSIONS, ) self.name = name self.log = logging.getLogger(f"Cluster#{name}") self.log.setLevel(logging.DEBUG) hdlr = logging.StreamHandler() hdlr.setFormatter( logging.Formatter( "[%(asctime)s %(name)s/%(levelname)s] %(message)s")) fhdlr = logging.FileHandler("logs/cluster-Launcher.log", encoding="utf-8") fhdlr.setFormatter( logging.Formatter( "[%(asctime)s %(name)s/%(levelname)s] %(message)s")) self.log.handlers = [hdlr, fhdlr] self.log.info(f"Initialized with shard ids {shard_ids}, " f"total shards {max_shards}")
def tearDown(self): db = Database() db.drop_tables()
def get_inbox(user_id): return Database.read( """ SELECT * FROM message WHERE to_user = ? """, [user_id])
def check_user(self): db = Database() if db.check_table("users"): query = "insert into users(username, email, password) values (%s, %s, %s)" user_details = (self.username, self.email, sha256.hash(self.password)) db.add_user(self.username, self.email, sha256.hash(self.password)) return ("User added") else: db.create_connection().execute( "create table users(user_id serial primary key,username varchar(25) not null, email varchar(25) not null, password varchar not null)" ) db.create_connection().close db.commit() query = "insert into users(username, email, password) values (%s, %s, %s)" user_details = (self.username, self.email, self.password) db.create_connection().execute(query, user_details) db.create_connection().con.commit() return ("User created")
def get_outbox(user_id): return Database.read( """ SELECT * FROM message WHERE from_user = ? """, [user_id])
import datetime from app.auth.decorator import response_message, token_required from werkzeug.security import generate_password_hash, check_password_hash from flask import Blueprint, request, jsonify from flasgger import swag_from from validate_email import validate_email from app.database.database import Database from app.model.models import User from app.views.parcels import sendemail import os from app.auth.decorator import get_token from flask_cors import CORS auth = Blueprint('auth', __name__) db = Database() CORS(auth) @auth.route('/api/v2/auth/signup', methods=['POST']) @swag_from('../doc/signup.yml') def create_user(): """ User creates an account User sign up details are added to the data base """ if request.content_type != 'application/json': return response_message('Bad request', 'Content-type must be json type', 400) request_data = request.get_json() try:
def create(model): return Database.create(""" INSERT INTO notification(to_user, text, time) VALUES (?, ?, ?); """, [model['to_user'], model['text'], model['time']])
def get_for_user(user_id): return Database.read(""" SELECT * FROM notification WHERE to_user = ? """, [user_id])
#! /usr/bin/env python3 """Script for Database creation. Force to remove database""" from app.database.database import Database import config db = Database(config.DBCONNECT) """CREATE AND FILL IN""" db.cursor = db.mydb.cursor() db.cursor.execute("DROP DATABASE IF EXISTS {};".format(config.DBCONNECT["DATABASE"])) db.cursor.close() db.create_database() db.fill_in_database()