Ejemplo n.º 1
0
 def get(self):
     """This route returns all avalable questions"""
     db = Database()
     questions = db.fetch_all()
     if len(questions) < 1:
         return {"message": "There are no questions Ask"}, 404
     return {"All_Questions": questions}
Ejemplo n.º 2
0
 def setUp(self):
     """Initiates variables to be used in most tests"""
     self.db = Database()
     self.user_data = {
         'key': 1,
         'first_name': 'John',
         'last_name': 'Doe',
         'email': '*****@*****.**',
         'password': '******',
     }
     self.user = User(**self.user_data)
     self.db = Database()
     self.user.save(self.db)
     self.category_data = {
         'key': 1,
         'name': 'Chicken – Combo',
         'description': '2 Pc. Chicken – Combo-20,000Ugshs',
         'user': self.user.key,
     }
     self.category = orderCategory(**self.category_data)
     self.category.save(self.db)
     self.order_data = {
         'key': 1,
         'name': 'Roast Pork',
         'description': 'Roast Pork-30,000Ugshs',
         'category': self.category.key
     }
     self.order = order(**self.order_data)
     self.order_step_data = {
         'text_content': "Waiting for your order ....",
     }
Ejemplo n.º 3
0
    def get(self, questionid):
        """route to get a single question by id and
        all the available answers"""
        db = Database()
        questions = db.get_by_argument('questions', 'question_id', questionid)
        if questions:
            question = {
                "question_id": questions[0],
                "title": questions[2],
                "description": questions[3],
                "date posted": str(questions[4])
            }
            answers = db.query_all_where_id('answers', 'question_id',
                                            questionid)

            answerlist = []
            for ans in answers:
                answerdic = {
                    "answer_id": ans[0],
                    "question_id": ans[1],
                    "user_id": ans[2],
                    "answer": ans[3],
                    "preffered": ans[4],
                    "up_vote": ans[5],
                    "down_vote": ans[6]
                }
                answerlist.append(answerdic)
            return {"question": question, "answers": answerlist}, 200
        return {"message": "no question by that id"}, 400
Ejemplo n.º 4
0
def disp_project(pname):
    #get project by project name
    data = list(Database.getProject(pname))
    updates = []
    tenders = []
    type = 'n'
    try:
        if (current_user.access == "admin"):
            if (data[-1] == 'a'):  #if allocated send updates and specify type
                updates = Database.getUpdate(pname)
                type = 'aa'
            else:  #else send tenders and specify type
                type = 'aw'
                #tenders = Database.
                tenders = (list(Database.getTender(pname)))
                for i in range(len(tenders)):
                    tenders[i] = list(tenders[i])
                tenders = tenders
                print(tenders)
        else:
            if (data[-1] == 'a'
                    and Database.pAllocTo(current_user.username, data[1])):
                #contractor can make updates
                type = 'ca'
            else:
                #contractor can make bid if date is open
                type = 'cw'
            #dont send data but send 'contractor' as type
    except:
        pass
    print(type)
    return render_template('proj_info.html', project = data, type= type,\
                   updates=updates, tenders=tenders)
Ejemplo n.º 5
0
 def setUp(self):
     """Declares variables to be used in most tests"""
     self.db = Database()
     self.user_data = {
         'first_name': 'John',
         'last_name': 'Doe',
         'email': '*****@*****.**',
         'password': '******',
     }
     self.user = User(**self.user_data, key=1)
     self.category_data = {
         'key': 1,
         'name': 'cakes',
         'description': 'all orders cake!',
         'user': self.user.key,
     }
     self.order_data = {
         'key': 1,
         'name': 'breadcake',
         'description': 'yummy',
         'category': self.category_data['key'],
     }
     self.order_step_data = {
         'key': 1,
         'text_content': "Don't do anything",
         'order': self.order_data['key'],
     }
Ejemplo n.º 6
0
    def post(self):
        """user needs email used to signup
        and password to login"""
        valid = Validator()
        db = Database()
        user_data = login_arg.parse_args()
        email = user_data['email']
        password = user_data['password']

        if valid.valid_email(email) is False:
            return {"error": "invalid email"}, 400
        if valid.valid_password(password) is False:
            return {"error": "invalid password:check length"}, 400
        user = db.get_by_argument('users', 'email', email)
        if user == None:
            return{"error": "wrong email address"}, 404
        if(email == user[2] and
           bcrypt.check_password_hash(user[3], password) is False):
            return {"error": "wrong password"}, 400

        if(email != user[2] and
           bcrypt.check_password_hash(user[3], password) is False):
            return {"error": "invalid login credentials"}, 400

        if(email == user[2] and
           bcrypt.check_password_hash(user[3], password) is True):
            access_token = create_access_token(identity=user[0],
            expires_delta=False)
            return {"message": "login successful",
                    "username": user[1],
                    "userid": user[0],
                    "access_token": access_token}, 200
Ejemplo n.º 7
0
 def setUp(self):
     """Initiates variables to be used in most tests"""
     self.db = Database()
     self.user_data = {
         'key': 1,
         'first_name': 'John',
         'last_name': 'Doe',
         'email': '*****@*****.**',
         'password': '******',
     }
     self.user = User(**self.user_data)
     self.db = Database()
     self.user.save(self.db)
     self.category_data = {
         'key': 1,
         'name': 'cakes',
         'description': 'all orders cake!',
         'user': self.user.key,
     }
     self.category = orderCategory(**self.category_data)
     self.category.save(self.db)
     self.order_data = {
         'key': 1,
         'name': 'Banana cake',
         'description': 'yummy!',
         'category': self.category.key
     }
     self.order = order(**self.order_data)
     self.order.save(self.db)
     self.order_step_data = {
         'key': 1,
         'text_content': "Don't do anything",
         'order': self.order.key
     }
     self.order_step = orderStep(**self.order_step_data)
Ejemplo n.º 8
0
def migrate_meta():
    from app.models import User, Role, Permission, \
    IUCNStatus, OrganismType, GrowthFormRaunkiaer, ReproductiveRepetition, \
    DicotMonoc, AngioGymno, SpandExGrowthType, SourceType, Database, Purpose, MissingData, ContentEmail, Ecoregion, Continent, InvasiveStatusStudy, InvasiveStatusElsewhere, StageTypeClass, \
    TransitionType, MatrixComposition, StartSeason, StudiedSex, Captivity, Species, Taxonomy, Trait, \
    Publication, AuthorContact, AdditionalSource, Population, Stage, StageType, Treatment, \
    MatrixStage, MatrixValue, Matrix, Interval, Fixed, Small, CensusTiming, PurposeEndangered, PurposeWeed, Institute, Version, \
    PublicationsProtocol, DigitizationProtocol, Protocol, CommonTerm

    print "Migrating Meta Tables..."
    Role.insert_roles()
    Species.migrate()
    Taxonomy.migrate()
    Trait.migrate()
    Publication.migrate()
    AuthorContact.migrate()
    Population.migrate()
    StageType.migrate()
    MatrixValue.migrate()
    Matrix.migrate()
    Fixed.migrate()
    Version.migrate()
    Institute.migrate()
    User.migrate()
    Database.migrate()
    Status.migrate()
    PublicationsProtocol.migrate()
    DigitizationProtocol.migrate()
    CommonTerm.migrate()

    return
Ejemplo n.º 9
0
 def post(self, answerid):
     """this route will upvote an answer"""
     db = Database()
     votes = db.get_by_argument("answers", "answer_id", answerid)
     if votes:
         upvote = votes[5] + 1
         db.update_answer_record("answers", "up_vote", upvote, "answer_id",
                                 answerid)
         return {"message": "answer upvoted"}, 201
     return {"message": "No answer by that answer_id"}, 404
Ejemplo n.º 10
0
def checkbid():
    data = {
        'tender_id': 5,
        'vender_id': 6,
        'date': "c",
        'cost': 10,
        'project_id': 10
    }
    Database.addBid(data)
    return "asda"
Ejemplo n.º 11
0
    def put(self, questionid, answerid):
        """modify answer or mark it as preffered"""
        db = Database()
        valid = Validator()
        user_id = get_jwt_identity()
        answer = db.get_by_argument("answers", "question_id", questionid)
        if answer:
            if user_id == answer[2]:
                preffered = modify_arg.parse_args()
                preffer = preffered['preffered']
                if preffer != "True":
                    return {"message": "preffered has no value True"}, 400
                db.update_answer_record("answers", "preffered", preffer,
                                        "answer_id", answerid)
                return {"message": "answer marked as preffered"}, 200

            answer1 = db.get_by_argument("answers", "answer_id", answerid)
            if answer1:
                if user_id == answer1[2]:
                    modifyans = modify_arg.parse_args()
                    eddited_ans = modifyans["answer"]
                    if valid.q_validate(eddited_ans) is False:
                        return {"message": "answer should contain letters"}
                    db.update_answer_record("answers", "reply", eddited_ans,
                                            "answer_id", answerid)
                    return {"message": "answer updated sucessfully"}, 200
        return {"message": "warning you are not authorized"}, 403
Ejemplo n.º 12
0
 def delete(self, questionid):
     """this routes delete a question and all answers provided"""
     db = Database()
     user_id = get_jwt_identity()
     questions = db.get_by_argument('questions', 'question_id', questionid)
     if questions:
         if user_id in questions:
             db.delete_question(questionid)
             return {
                 'message': 'Question deleted successfully and answers'
             }, 200
         return {
             'Warning': 'You have no rights to delete this question'
         }, 403
     return {'message': 'No question by that id'}, 404
Ejemplo n.º 13
0
	def setUp(self):
		self.db=Database()
		self.user_data={
			'first_name':'Wamula',
			'last_name':'Bashir',
			'email':'*****@*****.**',
			'password':'******',
			}

		self.user =User(**self.user_data,key=1)
		self.category_data={
			'key':1,
			'name':'hello',
			'description':'hello world',
			'user':self.user.key,
			}
Ejemplo n.º 14
0
def getBid(cname):
    if current_user.access == "admin" or current_user.username == cname:
        data = Database.getBid(cname)
        if len(data) == 0:
            return jsonify([])
        return jsonify(data)
    return "Invalid access",401
Ejemplo n.º 15
0
def contractor(uname):
    if current_user.access == "admin" or  current_user.username == uname:
        data = Database.getContractor(uname)
        if len(data)==0:
            return "User not found",404
        return render_template("contractor.html",data = json.dumps(data))
    return "Invalid access",401
Ejemplo n.º 16
0
def search_by():
	method = request.json['method']
	text = request.json['text']
	print(method,text)
	data = Database.search_by({'method':method, 'data':text})
	print(data)
	if len(data)==0:
	    return "No Entries found",401
	return data
Ejemplo n.º 17
0
def addProject():
	if current_user.access == "admin":
		projDetails = request.get_json()
		#verify Data parameters
		if Database.addProject(data):
		#if successful
			return "Data saved successfully"
		else:
			return "Error saving data"
	return "Access denied" 
Ejemplo n.º 18
0
 def post(self):
     """user needs username, valid email and
        password to signup"""
     valid = Validator()
     db = Database()
     user_data = signup_arg.parse_args()
     username = user_data['username']
     email = user_data['email']
     password = user_data['password']
     if valid.valid_username(username) is False:
         return {"error": "invalid username"}, 400
     if valid.valid_email(email) is False:
         return {"error": "invalid email"}, 400
     if valid.valid_password(password) is False:
         return {"error": "invalid password"}, 400
     if db.get_by_argument('users', 'email', email):
         return {'message': 'user already exists'}, 409
     hashed_pass = bcrypt.generate_password_hash(password).decode('utf-8')
     db.insert_user_data(username, email, hashed_pass)
     return{"message": "Account created"}, 201
Ejemplo n.º 19
0
def register_db():
    if current_user.is_anonymous or current_user.department not in ["admin"]:
        return redirect(url_for('main.index'))
    form = DBRegistrationForm()

    if form.validate_on_submit():
        new_db = Database(driver=form.driver.data,
                          host=form.host.data,
                          db_name=form.db_name.data,
                          login=form.login.data,
                          remark=form.remark.data)
        new_db.set_password(form.password.data)
        db.session.add(new_db)
        db.session.commit()
        flash('Congratulations, you have successfully registered a database!')
        return redirect(url_for('admin.db_management'))

    return render_template('admin/register_db.html',
                           title='Register DB',
                           form=form)
Ejemplo n.º 20
0
def login():
	data = request.get_json()
	username = data['username']
	password = data['password']
	#verify user
	if Database.login(username, password):
		user = load_user(username)
		login_user(user)
		return redirect("/user/"+username)
	else:
		return "Incorrect credentials. Please try again.",401
Ejemplo n.º 21
0
def signup():
	if request.method == 'GET':
		return render_template("register.html")
	else:
		#verify details
		data = request.get_json()
		print(data)
		if Database.addUser(data):
			return "User added successfully"
		else:
			return "Error",401
Ejemplo n.º 22
0
def add():
    form = DatabaseForm()
    if form.validate_on_submit():
        database_active = form.active.data
        database_name = re.sub('[^A-Za-z0-9_]+', '', form.dbname.data)

        database = Database(name=database_name, active=database_active)

        db.session.add(database)
        db.session.commit()

    return redirect(url_for('database.index'))
Ejemplo n.º 23
0
 def get(self):
     """all questions by the current user"""
     db = Database()
     user_id = get_jwt_identity()
     questions = db.query_all_where_id("questions", "user_id", user_id)
     if questions:
         user_qst = []
         for qst in questions:
             question = {
                 "question_id": qst[0],
                 "user_id": qst[1],
                 "title": qst[2],
                 "description": qst[3],
                 "date": str(qst[4])
             }
             user_qst.append(question)
         return {
             "total_questions": len(user_qst),
             "questions": user_qst
         }, 200
     return {"total_questions": 0}, 200
Ejemplo n.º 24
0
 def get(self):
     """all answers by the current user"""
     db = Database()
     user_id = get_jwt_identity()
     answers = db.query_all_where_id("answers", "user_id", user_id)
     if answers:
         ans_list = []
         for ans in answers:
             answerdic = {
                 "answer_id": ans[0],
                 "question_id": ans[1],
                 "user_id": ans[2],
                 "answer": ans[3],
                 "preffered": ans[4],
                 "up_vote": ans[5],
                 "down_vote": ans[6]
             }
             ans_list.append(answerdic)
         return {
             "total_answers": len(ans_list),
             "user_answers": ans_list
         }, 200
     return {"total_answers": 0}, 200
 def setUp(self):
     """Initiates variables to be used in most tests"""
     self.db = Database()
     self.user_data = {
         'key': 1,
         'first_name': 'John',
         'last_name': 'Doe',
         'email': '*****@*****.**',
         'password': '******',
     }
     self.user = User(**self.user_data)
     self.db = Database()
     self.user.save(self.db)
     self.category_data = {
         'key': 1,
         'name': 'cakes',
         'description': 'all orders cake!',
         'user': self.user.key,
     }
     self.category = orderCategory(**self.category_data)
     self.order_data = {
         'name': 'Banana cake',
         'description': 'yummy!',
     }
Ejemplo n.º 26
0
class DatabaseTest(unittest.TestCase):

	def setUp(self):
		self.db=Database()
		self.user_data={
			'first_name':'Wamula',
			'last_name':'Bashir',
			'email':'*****@*****.**',
			'password':'******',
			}

		self.user =User(**self.user_data,key=1)
		self.category_data={
			'key':1,
			'name':'hello',
			'description':'hello world',
			'user':self.user.key,
			}

	def test_get_next_key(self):
		self.assertEqual(self.db.get_next_key(User),1)
		self.db._user_keys +=[1,2,3]
		self.assertEqual(self.db.get_next_key(User),4)
		self.assertRaises(TypeError, self.db.get_next_key,2)
Ejemplo n.º 27
0
 def setUp(self):
     """
     Set up variables that will be used in most tests
     """
     self.user_data = {
         'key': 1,
         'first_name': 'John',
         'last_name': 'Doe',
         'email': '*****@*****.**',
         'password': '******',
     }
     self.user = User(**self.user_data)
     self.db = Database()
     self.category_data = {
         'name': 'cakes',
         'description': 'all orders cake!',
     }
Ejemplo n.º 28
0
def disp_project(pname):
	#get project by project name
	data = list(Database.getProject(pname))
	updates=[]
	tenders=[]
	print(data)
	if (current_user.access == "admin"):
		if(data[-1]=='a'):#if allocated send updates and specify type
			type='a'
		else:#else send tenders and specify type
			type='w'
			#tenders = Database.
			
	else:
		#dont send data but send 'contractor' as type
		type='c'
	print(type)
	return render_template('proj_info.html', project = data, type= type, updates=updates, tenders=tenders)
Ejemplo n.º 29
0
def index():
    form = DatabaseForm()
    databases = Database.query.order_by(Database.id.desc()).all()

    db = Database()
    columns = db.serialize_columns()

    dbs = []
    for db in databases:
        dbs.append(db.as_dict())

    base_url = url_for('database.index')
    action_url = url_for('database.add')
    return render_template('database.html',
                           title='Databases',
                           rows=dbs,
                           columns=columns,
                           base_url=base_url,
                           action_url=action_url,
                           per_page=current_app.config['ROWS_PER_PAGE'],
                           form=form)
Ejemplo n.º 30
0
 def post(self, questionid):
     """method to post a question answer
     anybody can post an answer to a question"""
     valid = Validator()
     db = Database()
     user_id = get_jwt_identity()
     ans_input = ans_arg.parse_args()
     user_answer = ans_input['answer']
     if valid.q_validate(user_answer) is False:
         return {"message": "answer must contain leters"}, 400
     if db.get_by_argument("questions", "question_id", questionid):
         if db.get_by_argument('answers', 'reply', user_answer):
             return {'message': 'That answer already exists'}, 409
         db.insert_answer_data(questionid, user_answer, user_id)
         return {"message": "Your answer was posted successfully"}, 201
     return {"message": "question id does not exist"}, 404