def read(ride_id, request_id): """ A method to get the details of a ride request. :param ride_id: An int, the unique identifier of a ride. :param request_id: An int, the unique identifier of a ride request. :return: ride request details """ connection = connectDB() cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) RideRequest.abort_if_ride_offer_doesnt_exist(ride_id) RideRequest.abort_if_ride_request_doesnt_exist(request_id) try: cursor.execute('SELECT * FROM ride_request WHERE id = %s ;', ([request_id])) except (Exception, psycopg2.DatabaseError) as error: connection.rollback() return {'status': 'failed', 'data': error}, 500 results = cursor.fetchone() cursor.close() connection.close() if results is None: abort(404, message='The ride request with id {} does not exist'.format( request_id)) request = { 'id': results['id'], 'ride_id': results['ride_id'], 'requestor': User.read(results['requestor_id'])['fullname'], 'request_status': results['request_status'], } return request
def read_students_csv(filename, course_id): """ Reads in a csv file and creates a user if the there is no user yet with the gived id. Adds the user to the specified course if its not yet active. This will probably be removed when the integration with lti works. If not, add some better error handeling and exiting. """ f = open(filename, 'r') reader = csv.reader(f, delimiter=',') course = Course.query.get(course_id) if course is None: f.close() return False for row in reader: if len(row) != 3: continue stud_id = int(row[0]) user = User.query.get(stud_id) if user is None: user = User(id=int(row[0]), name=row[1], email=row[2]) if not database.addItemSafelyToDB(user): continue if user not in course.student_courses: print("APPENDING USER") course.student_courses.append(user) database.get_db().session.commit() f.close() return True
def ensure_user_exists(self): """ Function that ensures the user exists. """ user_id = int(self.lti_instance.user_id) print(user_id) user = User.query.get(user_id) if user is None: user = User() user.create(id=user_id, name=self.lti_instance.user_full_name, email=self.lti_instance.user_primary_email, password="******") if not database.addItemSafelyToDB(user): user = None self.cache['user'] = user
def read(ride_id): """ A method to get the details of a ride. :param ride_id: An int, the unique identifier of the ride. :return: ride details """ connection = connectDB() cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) try: cursor.execute('SELECT * FROM ride WHERE id = %s ;', ([ride_id])) except (Exception, psycopg2.DatabaseError) as error: connection.rollback() return {'status': 'failed', 'data': error}, 500 results = cursor.fetchone() cursor.close() connection.close() if results is None: abort(404, message='The ride with id {} does not exist'.format(ride_id)) ride = { 'id': results['id'], 'time': results['time'], 'date': results['date'], 'pickup': results['pickup'], 'dropoff': results['dropoff'], 'capacity': results['capacity'], 'seats_available': results['seats_available'], 'driver': User.read(results['driver_id'])['fullname'], 'price': results['price'], 'status': results['status'] } return ride
def read_tas_csv(filename, course_id): """ Add teaching assistants from uploaded file. """ f = open(filename, 'r') reader = csv.reader(f, delimiter=',') course = Course.query.get(course_id) if course is None: f.close() return False for row in reader: if len(row) != 3: continue stud_id = int(row[0]) user = User.query.get(stud_id) if user is None: user = User(id=int(row[0]), name=row[1], email=row[2]) if not database.addItemSafelyToDB(user): continue if user not in course.ta_courses: print("ADDING TA") course.ta_courses.append(user) database.get_db().session.commit() f.close() return True
def fake_command(): from faker import Factory fake = Factory.create() users = [] db.drop_all() db.create_all() for i in range(100): name = fake.name() password = fake.pystr(min_chars=6, max_chars=20) email = fake.email() username = fake.user_name() sign_up_time = fake.date_time_this_year(before_now=True, after_now=False, tzinfo=None) avatar_img = pagan.Avatar(username, pagan.SHA512) avatar = 'static/avatar/' + username + '.png' avatar_img.save(os.path.join(app.root_path, 'static/avatar/'), username) u = User() u._create(username, password, name, email, sign_up_time, avatar) db.session.add(u) db.session.commit() users.append(u) # create 10 posts every user for _ in range(10): p = Post() title = fake.sentence(nb_words=6, variable_nb_words=True) content = fake.paragraph(nb_sentences=5, variable_nb_sentences=True) published_time = fake.date_time_this_year(before_now=True, after_now=False, tzinfo=None) p._create(title, content, published_time, u) db.session.add(p) db.session.commit() for user in users: count = 0 while count < 10: i = random.randint(0, len(users) - 1) if users[i] != user and not users[i] in user.following: user.following.append(users[i]) count += 1 #users[0].following.append(users[1]) #users[1].following.append(users[0]) db.session.commit()
def put(self, user_id): """ Endpoint for user profile update --- tags: - User security: - Bearer: [] parameters: - name: user_id in: path required: true type: integer - name: firstname in: formData required: true description: The user's firstname. type: string - name: lastname in: formData required: true description: The user's lastname. type: string - name: password in: formData required: true description: The user's password. type: string format: password - name: car_registration in: formData description: The user's car licence plate. type: string - name: phone_number in: formData description: The user's phone number. type: string responses: 500: description: Internal server error 200: description: Update successful 404: description: The user does not exist """ args = self.reqparse.parse_args() check_for_empty_fields(args) if len(args['password']) >= 8: return User.edit(user_id, args['firstname'], args['lastname'], args['password'], args['phone_number'], args['car_registration']) return { 'status': 'failed', 'message': 'Password is too short. At least 8 characters required' }, 202
def login(): error = None if request.method == 'POST': db_user = g.mongo.users.find_one({ 'username': request.form['username'], }) if db_user: user = User(db_user) else: user = None if not user: error = 'Invalid username' elif not user.check_password(request.form['password']): error = 'Invalid password' else: login_user(user) flash('You are logged in') return redirect(url_for('entries.list')) return render_template('login.html', error=error)
def fill_new_course_with_canvas_data(headers, course_id): """ A function that fills a new course with data from canvas. This function is only called if a new course is created. It then fills the course with students, tas and teachers. When using the api canvas has different names for roles, so we use a different function for filling a course with canvas data. """ request_url = lti_base_route + lti_api_route request_url += '/courses/{}/users?'.format(course_id) request_url += 'include[]=enrollments&include[]=email' user_req = requests.get(request_url, headers=headers) users = user_req.json() if user_req.status_code != 200: return for user in users: user_id = user.get('sis_user_id') if user_id is None: return existing_user = User.query.get(user_id) if existing_user is None: name = user.get('name') email = user.get('email') existing_user = User() existing_user.create(id=user_id, name=name, email=email, password="******") if not database.addItemSafelyToDB( existing_user, fill_new_course_with_canvas_data): continue course = Course.query.filter_by(canvas_unique_id=course_id).first() if course is None: return ensure_user_couples_to_course(existing_user, course, user)
def create_user(app, id): new_user = User() psw = b'$2b$12$1Y21IaNbwu357bI4ipaZO.GVvzouAEvnrAy80TGCBRtX5q8OUlIr2' new_user.id = id new_user.name = "test" new_user.email = str(id) + "@mail.com" new_user.password = psw database.addItemSafelyToDB(new_user) return new_user
def edit(date, time, pickup, dropoff, driver_id, price, status, ride_id): """ A method to edit a ride's details. :param date: A string, the date the ride is to be taken. :param time: A string, the time the ride is to start. :param pickup: A string, the place where the ride starts. :param dropoff: A string, the destination of the ride. :param driver_id: An int, the unique identifier of the driver of the ride. :param price: A string, the price of the ride. :param status: A string, the status of the ride. :param ride_id: An int, the unique identifier of the ride. :return: Http Response """ if status in Ride.STATUS_OPTIONS: car = User.get_car(driver_id) car_capacity = car['capacity'] connection = connectDB() cursor = connection.cursor( cursor_factory=psycopg2.extras.DictCursor) Ride.abort_if_ride_offer_doesnt_exist(ride_id) try: cursor.execute( """UPDATE ride SET date = %s, time = %s, pickup = %s, dropoff = %s, capacity = %s, driver_id = %s, price = %s, status = %s WHERE id = %s;""", (date, time, pickup, dropoff, car_capacity, driver_id, price, status, ride_id)) connection.commit() except (Exception, psycopg2.DatabaseError) as error: connection.rollback() return {'status': 'failed', 'data': error}, 500 cursor.close() connection.close() return { 'status': 'success', 'data': 'Ride offer successfully updated' }, 200 return { 'status': 'failed', 'message': 'You entered an invalid ride status' }, 404
def __init__(self, date, time, pickup, dropoff, driver_id, price, status=STATUS_IN_OFFER): car = User.get_car(driver_id) car_capacity = car['capacity'] self.date = date self.time = time self.pickup = pickup self.dropoff = dropoff self.capacity = car_capacity self.seats_available = car_capacity self.driver_id = driver_id self.price = price self.status = status
def browse(): """A method to get all rides. :return: A list of dictionaries with all rides """ connection = connectDB() cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) try: cursor.execute('SELECT * FROM ride;') except (Exception, psycopg2.DatabaseError) as error: connection.rollback() return {'status': 'failed', 'data': error}, 500 ride_list = cursor.fetchall() cursor.close() connection.close() if len(ride_list) == 0: return { 'status': 'success', 'message': 'There are no rides offers yet' }, 404 else: data = [] for ride in ride_list: item = { 'id': ride['id'], 'time': ride['time'], 'date': ride['date'], 'pickup': ride['pickup'], 'dropoff': ride['dropoff'], 'capacity': ride['capacity'], 'seats_available': ride['seats_available'], 'driver': User.read(ride['driver_id'])['fullname'], 'price': ride['price'], 'status': ride['status'] } data.append(item) return { 'status': 'success', 'message': 'Fetch successful', 'data': data }, 200
def get(self, user_id): """ Endpoint for viewing a user's details --- tags: - User security: - Bearer: [] parameters: - name: user_id in: path required: true type: integer responses: 500: description: Internal server error 200: description: Fetch successfull 404: description: The user does not exist """ return User.read(user_id)
def delete(self, user_id): """ Endpoint for deleting a user's profile --- tags: - User security: - Bearer: [] parameters: - name: user_id in: path required: true type: integer responses: 500: description: Internal server error 200: description: User successfully deleted 404: description: The user does not exist """ return User.delete(user_id)
def register_user(json_data): email = escape(json_data["email"]) name = escape(json_data["name"]) studentid = int(escape(json_data["studentid"])) password = escape(json_data["password"]) repassword = escape(json_data["password_confirmation"]) validated = validate_userdata(email, name, studentid, password, repassword) if validated != '': return Iresponse.create_response({"status": validated}, 200) # Backend check if email/studentid already exists user = User.query.filter_by(email=email).first() if user: return Iresponse.create_response({"status": "Email is taken"}, 200) studentid = json_data["studentid"] user = User.query.filter_by(id=studentid).first() if user: return Iresponse.create_response({"status": "Studentid taken"}, 200) new_user = User() salt = bcrypt.gensalt() hashedpsw = bcrypt.hashpw(password.encode('utf-8'), salt) new_user.password = hashedpsw new_user.id = studentid new_user.name = name new_user.email = email new_user.level = 1 new_user.experience = 1 if not database.addItemSafelyToDB(new_user): return Iresponse.internal_server_error() return Iresponse.create_response({"status": "OK"}, 201)
def browse(ride_id): """A method to get all ride requests. :return: A list of dictionaries with all ride requests """ connection = connectDB() cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) RideRequest.abort_if_ride_offer_doesnt_exist(ride_id) try: cursor.execute( 'SELECT id, ride_id, requestor_id, request_status FROM ride_request WHERE ride_id = %s ;', ([ride_id])) except (Exception, psycopg2.DatabaseError) as error: connection.rollback() return {'status': 'failed', 'data': error}, 500 ride_offer_requests = cursor.fetchall() cursor.close() connection.close() if len(ride_offer_requests) == 0: return { 'status': 'success', 'message': 'No requests available for this ride yet' }, 404 else: data = [] for request in ride_offer_requests: item = { 'id': request['id'], 'ride_id': request['ride_id'], 'requestor': User.read(request['requestor_id'])['fullname'], 'request_status': request['request_status'], } data.append(item) return { 'status': 'success', 'message': 'Fetch successful', 'data': data }
def post(self): """ Endpoint for user log in --- tags: - User security: - Bearer: [] parameters: - name: email in: formData required: true description: The user's email. type: string - name: password in: formData required: true description: The user's password. type: string format: password responses: 500: description: Internal server error 200: description: Login successful 202: description: Wrong password, please try again. 404: description: The user with email string does not exist """ args = self.reqparse.parse_args() check_for_empty_fields(args) if match_email(args['email']): return User.login(args['email'], args['password']) return { 'status': 'failed', 'message': 'Invalid email address, try again' }, 202
def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] error = None if not username or not password: error = "Username or password is required" else: user = User.query.filter(User.username == username).first() if user is not None: error = 'User {} is already registered.'.format(username) if error == None: user = User(username=username, password=my_encode(password)) db.session.add(user) db.session.commit() return redirect(url_for('auth.login')) flash(error) current_app.logger.debug("what's up") try: return render_template('auth/register.html') except TemplateNotFound: abort(404)
def index(self): users = User.find_all() return self.render('admin/users/index.html', users=users)
def create_user(params): user = User(username=params['username'], password=generate_password_hash(params['password'])) db.session.add(user) db.session.commit() return user
def load_user(userid): db_user = mongo.db.users.find_one({'_id': ObjectId(str(userid))}) user = User(db_user) return user
def post(self): """ Endpoint for user sign up --- tags: - User parameters: - name: firstname in: formData required: true description: The user's firstname. type: string - name: lastname in: formData required: true description: The user's lastname. type: string - name: email in: formData required: true description: The user's email. type: string - name: password in: formData required: true description: The user's password. type: string format: password - name: confirm_password in: formData required: true description: Confirmation of the password entered. type: string format: password responses: 500: description: Internal server error 201: description: Account creation successful 202: description: Password is too short. At least 8 characters required """ args = self.reqparse.parse_args() check_for_empty_fields(args) if match_email(args['email']): if args['password'] == args['confirm_password']: if len(args['password']) >= 8: user = User(args['firstname'], args['lastname'], args['email'], args['password'], args['phone_number'], args['car_registration']) return user.add() return { 'status': 'failed', 'message': 'Password is too short. At least 8 characters required' }, 202 return { 'status': 'failed', 'message': 'Password and confirm password do not match, try again' }, 202 return { 'status': 'failed', 'message': 'Invalid email address, try again' }, 202