Exemple #1
0
def update_user(user):
    try:
        user = User(user)
    except KeyError:
        abort(404)
    user.update(request.form.get('email'), request.form.get('permissions'))
    return jsonify(**user.json())
Exemple #2
0
def remove_availability(user):
    try:
        user = User(user)
    except KeyError:
        abort(404)
    user.remove_availability()
    return jsonify(user.get_availability())
Exemple #3
0
def add_availability(user):
    try:
        user = User(user)
    except KeyError:
        abort(404)
    user.add_availability(request.form.get("day"), request.form.get("start"),
                          request.form.get("type"))
    return jsonify(**user.json())
Exemple #4
0
def register():
    """
    ---
    post:
      summary: register user
      requestBody:
        required: true
        content:
            application/json:
                schema: Register
      responses:
        '200':
          description: registration successful
          content:
            application/json:
              schema: AuthResponse
      tags:
          - user
    """
    data = request.get_json()
    required_keys = ["username", "password", "email", "currency"]
    if not all([rqkey in data for rqkey in required_keys]):
        return jsonify(status=error, message="Sorry missing JSON field!"), 400
    try:
        if User.query.filter_by(username=data["username"]).first() is not None:
            return jsonify(status=error,
                           message="Sorry username already Taken!"), 400
        if User.query.filter_by(username=data["username"]).first() is not None:
            return jsonify(status=error,
                           message="Sorry username already Taken!"), 400

        if not CurrencyUtils.iscurrency_valid(data["currency"]):
            return jsonify(
                sattus=error,
                message="Sorry Please Enter a Valid currency code!"), 400
        isadmin = data.get("isadmin", False)
        user = User(username=data["username"],
                    password=data["password"],
                    email=data["email"],
                    currency=data["currency"].lower(),
                    isadmin=isadmin)
    except Exception as e:
        logging.error(e)
        return jsonify(status=error, message=str(e)), 400

    db.session.add(user)
    db.session.commit()
    if not isadmin:
        default_wallet = Wallet(currency=data["currency"], user_id=user.id)
        db.session.add(default_wallet)
        db.session.commit()
        user.wallet.append(default_wallet)

    return jsonify(status=ok,
                   token=user.generate_web_token(),
                   user=user.serialize), 201
Exemple #5
0
  def test_email_case_insensative(self):
    user = User(account=self.account, email='*****@*****.**')
    user.set_password('test123')
    self.session.add(user)
    self.session.commit()

    authed = self.users.authenticate('*****@*****.**', 'test123')
    self.assertTrue(authed is not None)

    self.assertEquals(user.id, authed.id)
Exemple #6
0
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')
    if username is None or password is None:
        abort(400)  # missing arguments
    if User.query.filter_by(username=username).first() is not None:
        abort(400)  # existing user
    user = User(username=username)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return jsonify({'username': user.username}), 201
Exemple #7
0
  def test_get_by_email(self):
    user = User(account=self.account, email='*****@*****.**')
    user.set_password('pants')
    self.session.add(user)
    self.session.commit()

    user1 = self.users.filter_by(email='*****@*****.**').first()
    user2 = self.users.filter_by(email='*****@*****.**').first()

    self.assertTrue(user1 is not None)
    self.assertTrue(user2 is None)

    self.assertEquals(user.id, user1.id)
  def setUp(self, users, res):
    super(TestSessionResource, self).setUp()

    self.users = users
    self.res   = res

    account = Account(name='Default')
    user = User(account=account, email='*****@*****.**')
    user.set_password('tiger')

    self.session.add(user)
    self.session.commit()
    self.user = user
Exemple #9
0
  def test_simple_authentication(self):
    user = User(account=self.account, email='*****@*****.**')
    user.set_password('test123')

    self.session.add(user)
    self.session.commit()

    authed = self.users.authenticate('*****@*****.**', 'test123')
    unauthed = self.users.authenticate('*****@*****.**', 'TEST123')

    self.assertTrue(authed is not None)
    self.assertTrue(unauthed is None)

    self.assertEquals(user.id, authed.id)
Exemple #10
0
def add_area():
    json = request.get_json()
    name = json['name']
    crops_type = json['crops_type']
    square = float(json['square'])
    points = json['points']
    user = User.verify_auth_token(json['token'])
    area = Area(name=name,
                crops_type=crops_type,
                square=square,
                user_id=user.id)
    db.session.add(area)
    db.session.commit()
    db.session.refresh(area)
    for p in points:
        db.session.add(
            RectanglePoint(area_id=area.id,
                           latitude=float(p['lat']),
                           longitude=float(p['lng'])))
    db.session.commit()

    return jsonify({
        'status': 'created',
        "area": {
            "id": area.id,
            "name": area.name,
            'crops_type': crops_type,
            'square': square,
            'points': points
        }
    }), 200
Exemple #11
0
def execute_algorithm():
    users = request.form.get('users').split("\n")
    classes = json.loads(request.form['classes'].replace(
        "'", '"'))  # {session name: [day, start, end]}

    availabilities = {}

    app.logger.info("Classes: {}".format(classes))

    for user in users:
        user = User.by_email(user)
        avail = user.get_availability()
        availabilities[user.email] = {
            "Mon": [],
            "Tue": [],
            "Wed": [],
            "Thu": [],
            "Fri": []
        }
        for day, start, type in avail:
            availabilities[user.email][day].append([start, type])
        # {user: [[day, start, type]]}
    print(availabilities)

    app.logger.info("Classes 2: {}".format(classes))
    results = backend.backend_run.run(availabilities, classes)

    return jsonify(results)
Exemple #12
0
def get_flights():
    json = request.get_json()
    token = json['token']
    user = User.verify_auth_token(token)
    user_flights = user.flights
    user_fights = sorted(user_flights, key=lambda f: f.id)
    data = []
    for flight in user_flights:
        data.append({
            'id': flight.id,
            'name': flight.name,
            'interval': flight.day_interval,
            'time': flight.begin_at.strftime("%H:%M"),
            'active': flight.active,
            'area': {
                'id': flight.area.id,
                'name': flight.area.name
            },
            'drone': {
                'id': flight.drone.id,
                'name': flight.drone.name
            }
        })

    return jsonify(data), 200
Exemple #13
0
def verify_password(username_or_token, password):
    user = User.verify_auth_token(username_or_token)
    if not user:
        user = User.query.filter_by(username=username_or_token).first()
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True
Exemple #14
0
def change_password():
    json = request.get_json()
    token = json['token']
    user = User.verify_auth_token(token)
    if user.password != json['password_old']:
        return jsonify({"error": "Wrong password"})
    user.password = json['password']
    db.session.commit()
    return jsonify({"status": "Password updated"})
 def setUp(self):
     self.app = self.create_app().test_client()
     db.create_all()
     user = User(self.default_user['first_name'],
                 self.default_user['last_name'], self.default_user['email'],
                 self.default_user['password'],
                 self.default_user['access_token'])
     db.session.add(user)
     db.session.commit()
Exemple #16
0
def verify_password(username_or_token, password):
    if not (username_or_token or password):
        return False
    user = User.verify_web_token(username_or_token)
    if not user:
        user = User.query.filter_by(username=username_or_token).first()
        if (not user) or (not user.validate_password(password)):
            return False
    g.user = user
    return True
Exemple #17
0
 def token_check(*args, **kwargs):
     json = request.json
     token = json['token']
     user = User.verify_auth_token(token)
     if user is None:
         return jsonify({
             'status': 'error',
             'error': 'token not valid'
         }), 401
     return func(*args, **kwargs)
Exemple #18
0
def profile():
    json = request.get_json()
    token = json['token']
    user = User.verify_auth_token(token)

    return jsonify({
        'login': user.login,
        'email': user.email,
        'status': 'done'
    })
Exemple #19
0
def delete_flight():
    json = request.get_json()
    user = User.verify_auth_token(json['token'])
    flight = Flight.query.filter(Flight.id == int(json['id']),
                                 Flight.user_id == user.id).first()
    if not flight:
        return jsonify({'status': "error", "error": 'flight not found'}), 400
    db.session.delete(flight)
    db.session.commit()
    return jsonify({'status': "deleted"}), 200
Exemple #20
0
def update_flight():
    json = request.get_json()
    name = json['name']
    area_id = int(json['area_id'])
    drone_id = int(json['drone_id'])
    active = bool(json['active'])
    interval = int(json['interval'])
    time_obj = time()
    try:
        flight_time = json['time'].split(':')
        time_obj = time(hour=int(flight_time[0]),
                        minute=int(flight_time[1]),
                        second=0)
    except:
        return jsonify({'status': 'error', 'error': 'wrong time format'}), 400

    user = User.verify_auth_token(json['token'])
    flight = Flight.query.filter(Flight.user_id == user.id,
                                 Flight.id == int(json['id'])).first()
    if not flight:
        return jsonify({'status': 'error', 'error': 'flight not found'}), 400
    area = Area.query.filter(Area.id == area_id,
                             Area.user_id == user.id).first()
    if not area:
        return jsonify({'status': 'error', 'error': 'area not found'})
    drone = Drone.query.filter(Drone.id == drone_id,
                               Drone.user_id == user.id).first()
    if not drone:
        return jsonify({'status': 'error', 'error': 'drone not found'})

    flight.name = name
    flight.area_id = area.id
    flight.drone_id = drone.id
    flight.begin_at = time_obj
    flight.day_interval = interval
    flight.active = active
    db.session.commit()

    return jsonify({
        'status': 'updated',
        "flight": {
            "id": flight.id,
            "name": flight.name,
            'interval': flight.day_interval,
            'time': f'{flight.begin_at.strftime("%H:%M")}',
            'area': {
                'id': area.id,
                'name': area.name
            },
            'drone': {
                'id': drone.id,
                'name': drone.name
            }
        }
    }), 200
Exemple #21
0
def delete_drone():
    json = request.get_json()
    user = User.verify_auth_token(json['token'])
    drone = Drone.query.filter(Drone.id == int(json['id']),
                               Drone.user_id == user.id).first()
    if len(drone.flights) != 0:
        return jsonify({'status': 'error', 'error': 'delete forbidden'}), 400
    if not drone:
        return jsonify({'status': "error", "error": 'drone not found'}), 400
    db.session.delete(drone)
    db.session.commit()
    return jsonify({'status': "deleted"}), 200
Exemple #22
0
def update_user():
    json = request.get_json()
    user = User.verify_auth_token(json['token'])
    check_users = User.query.filter(User.email == json['email']).all()
    check_users = [
        check_user for check_user in check_users if check_user.id != user.id
    ]
    if check_users:
        return jsonify({"error": "Email is already taken"})
    user.email = json['email']
    db.session.commit()
    return jsonify({"status": "Information updated"})
Exemple #23
0
def login():
    email = request.form.get('email')
    password = request.form.get('password')

    user = User.login(email, password)

    if user is None:
        return "Error occurred logging in"

    login_user(user)
    next_url = request.form.get('next')

    return redirect(next_url or url_for('index'))
Exemple #24
0
def signup_api():
    email = request.form.get('email')
    password = request.form.get('password')

    user = User.create(email, password, 0)

    if user is None:
        return "Error occurred signing up"

    login_user(user)
    next_url = request.form.get('next')

    return redirect(next_url or url_for('index'))
Exemple #25
0
def delete_area():
    json = request.get_json()
    user = User.verify_auth_token(json['token'])
    area = Area.query.filter(Area.id == int(json['id']),
                             Area.user_id == user.id).first()
    if not area:
        return jsonify({'status': "error", "error": 'area not found'}), 400
    if len(area.flights) != 0:
        return jsonify({'status': 'error', 'error': 'delete forbidden'}), 400
    for point in area.points:
        db.session.delete(point)
    db.session.delete(area)
    db.session.commit()
    return jsonify({'status': "deleted"}), 200
Exemple #26
0
def user_signup():
    json = request.json
    login = json['login']
    email = json['email']
    password = json['password']

    user = User.query.filter_by(login=login).first()
    if user:
        return jsonify({'error': 'Login is taken', "status": "error"}), 200
    user = User.query.filter_by(email=email).first()
    if user:
        return jsonify({'error': 'Email is taken', "status": "error"}), 200
    user = User(login=login, email=email, password=password)
    db.session.add(user)
    db.session.commit()

    return jsonify({
        'login': login,
        'email': email,
        'password': password,
        'token': user.generate_auth_token(),
        "status": "done"
    }), 200
Exemple #27
0
def add_drone():
    json = request.get_json()
    name = json['name']
    code = int(json['code'])
    model_id = int(json['model_id'])
    user = User.verify_auth_token(json['token'])
    model = db.session.query(Model).filter(Model.id == model_id).first()
    drone_code = Drone.query.filter(Drone.user_id == user.id,
                                    Drone.code == code).first()
    if drone_code:
        return jsonify({"error": "duplicate code"}), 400
    drone = Drone(name=name, model_id=model.id, code=code, user_id=user.id)
    db.session.add(drone)
    db.session.commit()

    return jsonify({'status': 'created'}), 200
Exemple #28
0
def registration():
    if current_user.is_authenticated:
        return redirect(url_for('.index'))
    form = registrationForm()
    if form.validate_on_submit():
        paswd = hashlib.sha224(form.password.data.encode())
        paswd = str(paswd.hexdigest())
        user = User(username=form.username.data,
                    email=form.email.data,
                    password=paswd)
        db.session.add(user)
        db.session.commit()
        flash('Your account has been created! You are now able to log in',
              'success')
        return redirect(url_for(".login"))
    return render_template('registration.html',
                           title='registration',
                           form=form)
Exemple #29
0
def get_drones():
    json = request.get_json()
    token = json['token']
    user = User.verify_auth_token(token)
    drones = user.drones
    data = [{
        "id": drone.id,
        "name": drone.name,
        "model": {
            "id": drone.model.id,
            "name": drone.model.name
        },
        "code": drone.code,
        "sync": drone.synced,
        "last_synced": drone.last_synced
    } for drone in drones]
    response = jsonify(data)
    return response, 200
Exemple #30
0
def get_areas():
    json = request.get_json()
    token = json['token']
    user = User.verify_auth_token(token)
    user_areas = user.areas
    data = []
    for area in user_areas:
        points = []
        for point in area.points:
            points.append({'lat': point.latitude, 'lng': point.longitude})
        data.append({
            'id': area.id,
            'name': area.name,
            'crops_type': area.crops_type,
            'square': area.square,
            'points': points
        })

    response = jsonify(data)
    return response, 200
Exemple #31
0
def register():
    username = request.get_json().get('username')
    password = request.get_json().get('password')
    message = None

    if not username:
        message = 'Username is required.'
    elif not password:
        message = 'Password is required.'
    elif User.query.filter(User.username == username).first() is not None:
        message = 'User {} is already registered.'.format(username)

    if message is None:
        user = User(username, generate_password_hash(password))
        db.session.add(user)
        db.session.commit()
        inserted_user = User.query.filter(User.username == username).first()

        return jsonify({'id': inserted_user.id}), 201

    return jsonify({'message': message}), 400
Exemple #32
0
def update_area():
    json = request.get_json()
    user = User.verify_auth_token(json['token'])
    area = Area.query.filter(Area.user_id == user.id,
                             Area.id == int(json['id'])).first()
    if not area:
        return jsonify({'status': 'error', 'error': 'area not found'}), 400
    area.name = json['name']
    area.crops_type = json['crops_type']
    area.square = float(json['square'])
    db.session.query(RectanglePoint).filter(
        RectanglePoint.area_id == area.id).delete()
    db.session.commit()
    for point in json['points']:
        p = RectanglePoint(area_id=area.id,
                           latitude=float(point['lat']),
                           longitude=float(point['lng']))
        db.session.add(p)
    db.session.commit()
    area.name = json['name']
    db.session.commit()
    return jsonify({
        "status": "updated",
        "area": {
            "id":
            area.id,
            "name":
            area.name,
            'crops_type':
            area.crops_type,
            'square':
            area.square,
            "points": [{
                "lat": p.latitude,
                'lng': p.longitude
            } for p in area.points]
        }
    }), 200
Exemple #33
0
def update_drone():
    json = request.get_json()
    user = User.verify_auth_token(json['token'])
    drone = Drone.query.filter(Drone.user_id == user.id,
                               Drone.id == int(json['id'])).first()
    if not drone:
        return jsonify({
            'status': 'error',
            'error': 'drone by id not found'
        }), 400
    drone_code = Drone.query.filter(Drone.user_id == user.id,
                                    Drone.code == int(json['code'])).all()
    drone_code = [drone for drone in drone_code if drone.id != int(json['id'])]
    if drone_code:
        return jsonify({"status": 'error', 'error': 'duplicate code'}), 400
    if drone.code != int(json['code']):
        drone.synced = False
    drone.code = int(json['code'])
    drone.name = json['name']
    model_id = int(json['model_id'])
    model = db.session.query(Model).filter(Model.id == model_id).first()
    drone.model_id = model.id
    db.session.commit()
    return jsonify({
        "status": "updated",
        "drone": {
            "id": drone.id,
            "name": drone.name,
            "model": {
                "id": drone.model.id,
                "name": drone.model.name
            },
            "code": drone.code,
            "sync": drone.synced,
            "last_synced": drone.last_synced
        }
    }), 200
Exemple #34
0
def delete_user(username):
    user = User.objects(user_name=username).first()
    if user:
        user.delete()
    else:
        raise DatabaseError('No such user!')
Exemple #35
0
def update_user(username, password):
    user = User.objects(user_name=username).first()
    if user:
        user.update(set__user_passwd=password)
    else:
        raise DatabaseError('No such user!')
Exemple #36
0
def create_user(username, password):
    user = User.objects(user_name=username).first()
    if user:
        raise DatabaseError('User already exists!')
    else:
        User(user_name=username, user_passwd=password).save()