Пример #1
0
 def send_shuttle_request_path(self):
     self.sc.check_roles_and_route(['Administrator', 'Driver', 'User'])
     json_data = request.get_json()
     response = db.commit_shuttle_request(json_data['pick-up-location'],
                                          json_data['drop-off-location'])
     if response == 'success':
         self.sc.set_alert('success', 'Your request has been submitted')
     elif response == 'same location':
         self.sc.set_alert('danger',
                           'Please select two different locations')
     elif response == 'no location':
         self.sc.set_alert('danger', 'Please select a location')
     elif response == 'bad time':
         self.sc.set_alert(
             'danger',
             'You cannot request a shuttle at this time. Refer to the On Call Shuttle '
             'Information below to see when the On Call Shuttle is available'
         )
     elif response == 'bad location':
         self.sc.set_alert(
             'danger',
             'You can only request off campus locations at this time. Refer to the On Call '
             'Shuttle Information below to see when the On Call Shuttle is available '
         )
     else:
         self.sc.set_alert(
             'danger', 'Something went wrong. Please call the ITS Help '
             'Desk at 651-638-6500 for support')
     return response
Пример #2
0
 def send_driver_check_in_info(self):
     self.sc.check_roles_and_route(['Administrator', 'Driver'])
     json_data = request.get_json()
     response = db.commit_driver_check_in(json_data['location'])
     if response == 'Success':
         self.sc.set_alert('success', 'Your departure from ' + json_data['location'] + ' has been recorded')
     elif response == 'bad location':
         self.sc.set_alert('danger', 'Please select a location')
     return response
Пример #3
0
 def check_unique(self):
     data = request.get_json(force=True)
     unique = None
     if 'username' in data:
         unique = User.query.filter_by(username=data['username']).first()
     elif 'email' in data:
         unique = User.query.filter_by(email=data['email']).first()
     if not unique:
         return '', 200
     return '', 404
Пример #4
0
 def delete_request(self):
     json_data = request.get_json()
     username = json_data['username']
     results = db.driver_deleted_request(username)
     if results == 'success':
         self.sc.set_alert('success', 'The request has been deleted')
     else:
         self.sc.set_alert('danger', 'Something went wrong. Please call the ITS Help '
                                     'Desk at 651-638-6500 for support')
     return results
Пример #5
0
    def selected_shuttle_logs(self):
        json_data = request.get_json()
        date = json_data['date']
        name_sort = json_data['sort']
        selected_logs = self.dlc.grab_selected_logs(date, name_sort)

        shuttle_logs = selected_logs[0]
        break_logs = selected_logs[1]
        completed_requests = selected_logs[2]
        deleted_requests = selected_logs[3]
        return render_template('driver_logs/load_logs.html', **locals())
Пример #6
0
 def patch(self, id):
     r = Repeats.query.get(int(id))
     s = Sets.query.get(r.set_id)
     if not s.user_id == current_user.id:
         return return_response(404, jsonify(error='Отказано в доступе'))
     form = RepeatForm(data=request.get_json(force=True))
     if form.validate():
         r.set_id = form.set.data
         r.weight = form.weight.data
         r.repeat = form.repeats.data
         db.session.commit()
         return '', 200
     return '', 409
Пример #7
0
 def patch(self, id):
     form = EditExercise(data=request.get_json(force=True))
     try:
         if form.validate():
             s = Sets.query.get(int(id))
             if not s.user_id == current_user.id:
                 return return_response(404, jsonify(error='Отказано в доступе'))
             s.exercise_id = form.exercise.data
             db.session.commit()
             return '', 200
     except SQLAlchemyError as e:
         return return_response(500, jsonify(error='Произошлка ошибка во время запроса.'))
     return '', 404
Пример #8
0
 def login(self):
     form = LoginForm(data=request.get_json(force=True))
     if form.validate():
         try:
             user = User.query.filter_by(username=form.username.data).first()
         except SQLAlchemyError as e:
             # TODO: loging exeption e
             return return_response(500, jsonify(error='Произошлка ошибка во время запроса.'))
         if user is None:
             return return_response(404, jsonify(error='Пользователь не найден'))
         if bcrypt.check_password_hash(user.password, form.password.data):
             login_user(user)
             return '', 200
         return return_response(404, jsonify(error='Не правильно введен логин или пароль'))
Пример #9
0
 def change_password(self):
     data = request.get_json(force=True)
     if not bcrypt.check_password_hash(current_user.password, data['old']):
         return return_response(404, jsonify(error='Старый пароль введен не верно'))
     if not data['new'] == data['confirm']:
         return return_response(404, jsonify(error='Новый пароль и подтверждение пароля не совпадают'))
     try:
         User.query.filter_by(id=current_user.id).update({
             'password': bcrypt.generate_password_hash(data['new'])
         })
         db.session.commit()
     except SQLAlchemyError as e:
         return return_response(500, jsonify(error='Произошлка ошибка во время запроса.'))
     return '', 200
Пример #10
0
 def post(self):
     form = RepeatForm(data=request.get_json(force=True))
     if form.validate():
         repeats = Repeats(
             set_id=form.set.data,
             weight=form.weight.data,
             repeat=form.repeats.data,
         )
         try:
             db.session.add(repeats)
             db.session.commit()
         except SQLAlchemyError as e:
             return return_response(500, jsonify(error='Произошлка ошибка во время запроса.'))
         return '', 201
     return '',  409
Пример #11
0
 def send_driver_break_info(self):
     self.sc.check_roles_and_route(['Administrator', 'Driver'])
     json_data = request.get_json()
     response = db.commit_break(json_data['break'])
     if response == 'on break success':
         self.sc.set_alert('success', 'Clock out recorded successfully')
     elif response == 'off break success':
         self.sc.set_alert('success', 'Clock in recorded successfully')
     elif response == 'error: not on break':
         self.sc.set_alert('danger', 'Can\'t clock in because you are not on break')
     elif response == 'error: already on break':
         self.sc.set_alert('danger', 'Can\'t clock out because you are already on break')
     else:
         self.sc.set_alert('danger', 'Something went wrong. Please try again or '
                                     'call the ITS Help Desk at 651-638-6500')
     return response
Пример #12
0
    def post(self, *args, **kwargs):
        """Obtain an auth token"""
        resp = {"user" : "unknown"}
        body = request.get_json()
        if not _input_valid(body=body, schema=self.POST_SCHEMA):
            resp['error'] = 'Invalid HTTP body supplied'
            return ujson.dumps(resp), 400
        elif not body['username']:
            resp['error'] = 'No username supplied',
            return ujson.dumps(resp), 400
        elif not body['password']:
            resp['error'] = 'No password supplied',
            return ujson.dumps(resp), 400
        else:
            username = body['username']
            password = body['password']
        resp['user'] = username
        try:
            client_ip = request.headers.getlist("X-Forwarded-For")[-1]
        except IndexError:
            client_ip = request.remote_addr

        conn, status, bind_error = _bind_ldap(username, password)
        if not conn:
            resp['error'] = bind_error
            return ujson.dumps(resp), status

        email, error = _user_ok(conn, body['username'])
        conn.unbind()
        if error:
            resp['error'] = error
            resp['content'] = {'token' : ''}
            status = 403
        else:
            token = generate_v2_token(username=body['username'],
                                      version=self.version,
                                      client_ip=client_ip,
                                      issued_at_timestamp=time.time(),
                                      email=email)
            if _added_token_to_redis(token, body['username']):
                resp['content'] = {'token' : token}
            else:
                resp['error'] = 'Unable to persist token record'
                resp['content'] = {'token' : ''}
                status = 503
        return ujson.dumps(resp), status
Пример #13
0
 def registration(self):
     form = RegistrationForm(data=request.get_json(force=True))
     if form.validate():
         user = User(
             username=form.username.data,
             email=form.email.data,
             password=bcrypt.generate_password_hash(form.password.data)
         )
         try:
             db.session.add(user)
             db.session.commit()
             return '', 201
         except SQLAlchemyError as e:
             # TODO: loging exeption e
             db.session.rollback()
             return return_response(500, jsonify(error='Произошлка ошибка во время запроса.'))
     return return_response(404, jsonify(error='Не вверно введены данные.'))
Пример #14
0
 def load_driver_view(self):
     json_data = request.get_json()
     load = ''
     session['DRIVER-SELECT'] = json_data['view']
     if json_data['view'] == 'Location Check In':
         load = 'locations'
         locations = db.get_db_locations()
         next_check_in = self.hc.grab_current_route()
         next_location = next_check_in['location']
         next_time = next_check_in['time']
         if next_location == 'No more stops today' or next_location == 'No stops on the weekend':
             next_location = 'North'
         return render_template('driver_check_in/load_driver_check_locations.html', **locals())
     if json_data['view'] == 'Active Requests':
         load = 'requests'
         requests = db.get_requests()
         active_requests = db.number_active_requests()['waitlist-num']
         return render_template('driver_check_in/load_driver_check_requests.html', **locals())
Пример #15
0
 def inner(*args, **kwargs):
     resp = {'user': kwargs['token']['username']}
     body = request.get_json()
     if body is None:
         resp['error'] = 'No JSON content body sent in HTTP request'
         return ujson.dumps(resp), 400
     else:
         try:
             validate(body, schema)
         except ValidationError as doh:
             logger.error(doh)
             resp[
                 'error'] = 'Input does not match schema.\nInput: {}\nSchema: {}'.format(
                     body, schema)
             return ujson.dumps(resp), 400
         else:
             kwargs['body'] = body
     return func(*args, **kwargs)
Пример #16
0
 def patch(self, id):
     form = BodySizeForm(data=request.get_json(force=True))
     try:
         bs = BodySize.query.filter_by(id=int(id)).first()
         if not bs.user_id == current_user.id:
             return return_response(404, jsonify(error='Отказано в доступе'))
         if form.validate():
             bs.date = datetime.strptime(form.date.data, '%Y-%m-%d')
             bs.hip = form.hip.data
             bs.waist = form.waist.data
             bs.chest = form.chest.data
             bs.arm = form.arm.data
             bs.weight = form.weight.data
             db.session.commit()
             return '', 200
     except SQLAlchemyError as e:
         return return_response(500, jsonify(error='Произошлка ошибка во время запроса.'))
     response = jsonify(error='Не верно введенеы данные. Попробуйте снова.')
     response.status_code = 409
     return response
Пример #17
0
 def post(self):
     form = BodySizeForm(data=request.get_json(force=True))
     if form.validate():
         body_size = BodySize(
             date=form.date.data,
             chest=form.chest.data,
             waist=form.waist.data,
             hip=form.hip.data,
             arm=form.arm.data,
             weight=form.weight.data,
             user_id=current_user.id
         )
         try:
             db.session.add(body_size)
             db.session.commit()
             return '', 201
         except SQLAlchemyError as e:
             db.session.rollback()
             return return_response(500, jsonify(error='Произошлка ошибка во время запроса.'))
     return return_response(409, jsonify(error='Не верно введенеы данные. Попробуйте снова.'))
Пример #18
0
 def delete(self, *args, **kwargs):
     """Delete a token"""
     resp = {'user' : 'unknown'}
     status = 200
     body = request.get_json()
     if not _input_valid(body=body, schema=self.DELETE_SCHEMA):
         resp['error'] = 'Invalid HTTP body supplied'
         status = 400
     else:
         try:
             redis_server = StrictRedis(host=const.AUTH_REDIS_HOSTNAME, port=const.AUTH_REDIS_PORT)
             if redis_server.delete(body['token']):
                 logger.info("Token delete: %s" % body['token'])
             else:
                 logger.info("Attempt to delete non-existing token %s" % body['token'])
         except RedisError as doh:
             logger.exception(doh)
             resp['error'] = "unable to delete token"
             status = 503
     return ujson.dumps(resp), status
Пример #19
0
    def post(self, *args, **kwargs):
        """Obtain an auth token"""
        resp = {"user" : "unknown"}
        body = request.get_json()
        if not _input_valid(body=body, schema=self.POST_SCHEMA):
            resp['error'] = 'Invalid HTTP body supplied'
            return ujson.dumps(resp), 400
        else:
            resp['user'] = body['username']

        conn, status = _bind_ldap(body['username'], body['password'])
        if not conn:
            if status == 401:
                resp['error'] = 'Invalid username or password'
            elif status == 503:
                resp['error'] = 'Unable to connect to LDAP server'
            return ujson.dumps(resp), status

        memberOf, error = _user_ok(conn, body['username'])
        conn.unbind()
        if not memberOf:
            status = 500
            resp['error'] = error
            resp['content'] = {'token' : ''}
        elif error:
            resp['error'] = error
            resp['content'] = {'token' : ''}
            status = 403
        else:
            token = generate_token(username=body['username'],
                                   version=self.version,
                                   memberOf=memberOf,
                                   issued_at_timestamp=time.time())
            if _added_token_to_redis(token, body['username']):
                resp['content'] = {'token' : token}
            else:
                resp['error'] = 'Unable to persist token record'
                resp['content'] = {'token' : ''}
                status = 503
        return ujson.dumps(resp), status
Пример #20
0
 def post(self):
     t_set = t.Dict({
         t.Key('date') >> 'date': t.String,
         t.Key('exercise') >> 'exercise': t.Int,
         t.Key('exercise_name', optional=True) >> 'exercise_name': t.String,
         t.Key('repeats') >> 'repeats': t.List(
             t.Mapping(
                 t.String, t.Float
             )
         )
     })
     data = request.get_json(force=True)
     for day in data:
         try:
             day_check = t_set.check(day)
             sets = Sets(
                 date=datetime.strptime(day_check['date'], '%Y-%m-%d'),
                 exercise_id=day_check['exercise'],
                 user_id=current_user.id
             )
             db.session.add(sets)
             db.session.flush()
             for repeat in day_check['repeats']:
                 repeat_instance = Repeats(
                     set_id=sets.id,
                     weight=repeat['weight'],
                     repeat=repeat['repeats'],
                 )
                 db.session.add(repeat_instance)
                 db.session.flush()
         except t.DataError as e:
             return '', 404
     try:
         db.session.commit()
     except SQLAlchemyError as e:
         db.session.rollback()
         return return_response(500, jsonify(error='Произошлка ошибка во время запроса.'))
     return '', 201
Пример #21
0
 def load_request(self):
     json_data = request.get_json()
     username = json_data['username']
     return render_template('driver_check_in/requests_modal.html', **locals())