Ejemplo n.º 1
0
def get_action():
    date_time = request.args.get('datetime')
    user = g.current_user
    if date_time is None:
        return bad_request('args error.')
    if not user:
        return bad_request('Unauth...')

    action_lib_presets_dic = {}
    for action in action_lib_presets:
        name = action['name']
        label = action['label']
        action_lib_presets_dic[name] = label

    date_time_formatted = datetime.datetime.strptime(date_time, r'%Y-%m-%d')
    mydata = user.mydata.filter_by(
        timestamp=date_time_formatted).first_or_404()
    mydata_json = json.loads(mydata.data)
    for data in mydata_json:
        name = data.get('name')
        if name in action_lib_presets_dic:
            data['label'] = action_lib_presets_dic[name]

    message = {"mydata": mydata_json}
    return message
Ejemplo n.º 2
0
def dashboard():
	print('entered dashboard')
	try:
		data = request.get_json()
		token = data['token']
		if token:
			if jwt.decode(token, secret_key, algorithm='HS256'):
				return jsonify({"auth": True})
			return jsonify({"auth": False})
		return jsonify({"auth": False})
	except KeyError:
		return bad_request("Wrong arguments.")
	return bad_request("There is an internal server error. Please contact the IT support.")
Ejemplo n.º 3
0
def user_login():
    login_data = json.loads(request.get_data())
    user = User.query.filter_by(
        username=login_data['user']['username'].lower()).first()
    if user:
        if user.password == login_data['user']['password']:
            return jsonify({'user_id': user.id})
        else:
            return bad_request(
                "Your username or password was incorrect, try again.")
    else:
        return bad_request(
            "Your username or password was incorrect, try again.")
Ejemplo n.º 4
0
def update_user(id):
    user = User.query.get_or_404(id)
    data = request.get_json() or {}
    if 'username' not in data:
        return bad_request('错误的参数')
    setattr(user, 'username', data['username'])
    db.session.commit()
    return jsonify(user.to_dict())
Ejemplo n.º 5
0
def get_days_have_actions():
    month = request.args.get('date_month')
    if not month:
        return bad_request()
    response = []
    user = g.current_user
    if not user:
        return bad_request()
    data = MyData.query.filter(
        MyData.user == user,
        extract('month', MyData.timestamp) == int(month)).all()
    for item in data:
        day = item.timestamp.day
        content = json.loads(item.data)
        if day not in response and len(content):
            response.append(day)
    # response = list(set([item.timestamp.day for item in data if item.data and len(item.data)]))
    return jsonify(response)
Ejemplo n.º 6
0
def add_user():
    data = request.get_json() or {}
    if 'username' not in data:
        return bad_request('错误的参数')
    user = User()
    user.from_dict(**data)
    db.session.add(user)
    db.session.commit()
    return jsonify(user.to_dict())
Ejemplo n.º 7
0
def create_user():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    if not data:
        return bad_request('bad request')
    if not username or not password:
        return bad_request('bad request')
    user = User.query.filter_by(username=username).first()
    if user is not None:
        return bad_request("user existed.")

    user = User()
    user.username = username
    user.set_password(password)
    db.session.add(user)
    db.session.commit()

    return 'create success', 201
Ejemplo n.º 8
0
def login():
	try:
		print('\n\n\n')
		print('sfsdfgsgsdfgfdgsgsdfgsdgsd')
		print('\n\n\n')
		data = request.get_json()
		username, password = data["username"], data["password"]
		user = User.query.filter_by(username=username).first()
		if user is None or not user.check_password(password):
			return bad_request("Username or password incorrect")
		payload = {'username': username, 'id': user.id, 'exp': time() + 300}
		token = jwt.encode(payload, secret_key, algorithm='HS256').decode('utf-8')
		print(token)
		print(type(token))
		return jsonify({
			"token": token,
			"avatar": user.avatar(128)
		})
	except KeyError:
		return bad_request("Wrong arguments.")
	return bad_request("There is an internal server error. Please contact the IT support.")
Ejemplo n.º 9
0
def add_user():
    user_data = json.loads(request.get_data())
    if 'username' not in user_data or 'email' not in user_data or 'password' not in user_data:
        return bad_request("Username, email and password are required.")
    if User.query.filter_by(username=user_data['username']).first():
        return bad_request("A username must be unique.")
    if User.query.filter_by(email=user_data['email']).first():
        return bad_request("An email must be unique.")
    else:
        user = User(user_data)
        db.session.add(user)
        db.session.commit()
        response = {
            'user': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'avatar': user.avatar
            }
        }
        return jsonify(response)
Ejemplo n.º 10
0
def get_token():
    user = g.current_user
    if not user:
        return bad_request('Unauthorized...')
    now = datetime.datetime.utcnow()
    payload = {
        'user_id': user.id,
        'username': user.username,
        'exp': now + datetime.timedelta(seconds=EXPIRES_IN),
        'iat': now
    }
    token = jwt.encode(payload,
                       current_app.config['SECRET_KEY'],
                       algorithm='HS256').decode('utf-8')

    return jsonify({'token': token})
Ejemplo n.º 11
0
def add_post():
    post_data = json.loads(request.get_data())
    if 'title' not in post_data:
        return bad_request("A post title is required.")
    else:
        if 'muscle_group' in post_data:
            post = Post(post_data)
            db.session.add(post)
            db.session.commit()
            exercise = Exercise(post_data, post.id)
            db.session.add(exercise)
            db.session.commit()
            response = {
                'post': {
                    'id': post.id,
                    'title': post.title,
                    'description': post.description,
                    'image_url': post.image_url,
                    'user_id': post.user_id,
                    'date': post.date,
                    'post_type': 'exercise',
                    'exercise': {
                        'id': exercise.id,
                        'muscle_group': exercise.muscle_group,
                        'name': exercise.name,
                        'reps': exercise.reps,
                        'weight': exercise.weight,
                        'time': exercise.time,
                        'distance': exercise.distance
                    }
                }
            }
            return jsonify(response)
        elif 'meal' in post_data:
            post = Post(post_data)
            db.session.add(post)
            db.session.commit()
            meal = Meal(post_data, post.id)
            db.session.add(meal)
            db.session.commit()
            foods = post_data['meal']['foods']
            food_obs = []
            for i, x in enumerate(foods, start=0):
                food = Food(foods[i])
                food_obs.append(food)
                db.session.add(food)
                db.session.commit()
                meal.foods.append(food)
                db.session.commit()
            response = {
                'post': {
                    'id': post.id,
                    'title': post.title,
                    'description': post.description,
                    'image_url': post.image_url,
                    'user_id': post.user_id,
                    'date': post.date,
                    'post_type': 'meal',
                    'meal': {
                        'id': meal.id,
                        'name': meal.name,
                        'post_id': meal.post_id,
                        'foods': get_foods(food_obs)
                    }
                }
            }

            return jsonify(response)
        else:
            return bad_request("AHHH! Something went wrong!")