Exemplo n.º 1
0
def update_email():
	req_data = request.get_json()
	form_values = {
		"email": {
			'required': True,
			'default': None,
			'type': str,
			'validator': None
		},
		"password": {
			'required': True,
			'default': None,
			'type': str,
			'validator': None
		}
	}
	current_app.logger.debug(f"[update email] the request is: {req_data}")
	check_fields(req_data, form_values)
	current_user = g.current_user

	if current_user.check_password(req_data["password"]):
		if getattr(current_user, 'email') != req_data['email']:
			if User.get_by_email(req_data['email']):
				abort(http.HTTPStatus.CONFLICT)  # If another user has this email

			# Send activation email
			token = serializer.create_token(req_data['email'], 'activate_email')
			send_token_email(current_app.config.get('FRONTEND_URL'), 'activate_email', req_data['email'], token)

		return jsonify({"ok": True})
	abort(http.HTTPStatus.FORBIDDEN)
Exemplo n.º 2
0
def edit_password():
	req_data = request.get_json()
	form_values = {
		"old_password": {
			'required': True,
			'default': None,
			'type': str,
			'validator': None
		},
		"new_password": {
			'required': True,
			'default': None,
			'type': str,
			'validator': None
		}
	}
	current_app.logger.debug(f"[update pwd] the request is: {req_data}")
	check_fields(req_data, form_values)
	current_user = g.current_user

	if current_user.check_password(req_data["old_password"]):
		if not current_user.check_password_strength(req_data["new_password"]):
			abort(http.HTTPStatus.BAD_REQUEST)
		current_user.set_password(req_data["new_password"])
		current_user.update()

		return jsonify({"ok": True})
	abort(http.HTTPStatus.FORBIDDEN)
Exemplo n.º 3
0
def update_location():
	req_data = request.get_json()
	form_values = {
		"latitude": {
			'required': False,
			'default': None,
			'type': float,
			'validator': None
		},
		"longitude": {
			'required': False,
			'default': None,
			'type': float,
			'validator': None
		}
	}
	current_app.logger.debug(f"[update location], the request is: {req_data}")
	check_fields(req_data, form_values)
	current_user = g.current_user

	if getattr(current_user, 'latitude') != req_data['latitude']:
		current_user.latitude = str(req_data['latitude'])
	if getattr(current_user, 'longitude') != req_data['longitude']:
		current_user.longitude = str(req_data['longitude'])

	current_user.update()
	return jsonify({"ok": True})
Exemplo n.º 4
0
def login():
    req_data = request.get_json()
    form_values = {
        "username": {
            'required': True,
            'default': None,
            'type': str,
            'validator': None
        },
        "password": {
            'required': True,
            'default': None,
            'type': str,
            'validator': None
        }
    }
    current_app.logger.debug(f"Here we are, the request is: {req_data}")
    check_fields(req_data, form_values)

    current_user = User.get_by_username(req_data["username"])

    if current_user and current_user.check_password(req_data["password"]):
        if current_user.activated is not True:
            abort(http.HTTPStatus.FORBIDDEN)

        session['user_id'] = current_user.id
        return jsonify({'status': 'ok'})
    abort(http.HTTPStatus.UNAUTHORIZED)
Exemplo n.º 5
0
def create_user():
    req_data = request.get_json()
    form_values = {
        "first_name": {
            'required': True,
            'default': None,
            'type': str,
            'validator': None
        },
        "last_name": {
            'required': True,
            'default': None,
            'type': str,
            'validator': None
        },
        "email": {
            'required': True,
            'default': None,
            'type': str,
            'validator': lambda x: '@' in x[1:-1]
        },
        "username": {
            'required': True,
            'default': None,
            'type': str,
            'validator': None
        },
        "password": {
            'required': True,
            'default': None,
            'type': str,
            'validator': None
        }
    }
    current_app.logger.debug(f"Here we are, the request is: {req_data}")
    check_fields(req_data, form_values)

    if User.get_by_email(req_data['email']):
        abort(http.HTTPStatus.CONFLICT)  # If another user has this email
    if User.get_by_username(req_data['username']):
        abort(http.HTTPStatus.CONFLICT)  # If another user has this username

    new_user = User.from_dict(req_data)
    if not new_user.check_password_strength(req_data["password"]):
        abort(http.HTTPStatus.BAD_REQUEST)
    new_user.set_password(req_data["password"])
    new_user.create()

    # Send activation email
    token = serializer.create_token(req_data['email'], 'activate_user')
    send_token_email(current_app.config.get('FRONTEND_URL'), 'activate_user',
                     new_user.email, token)

    return jsonify({"ok": True, "user": new_user.get_view("personal")})
Exemplo n.º 6
0
def send_token(token_type):
    req_data = request.get_json()
    form_values = {
        "email": {
            'required': True,
            'default': None,
            'type': str,
            'validator': lambda x: '@' in x[1:-1]
        }
    }
    check_fields(req_data, form_values)

    current_user = User.get_by_email(req_data['email'])
    if not current_user:
        abort(
            http.HTTPStatus.NOT_FOUND)  # If user with this email doesn't exist

    # Send activation email
    token = serializer.create_token(req_data['email'], token_type)
    send_token_email(current_app.config.get('FRONTEND_URL'), token_type,
                     req_data['email'], token)
    return jsonify({"ok": True})
Exemplo n.º 7
0
def create_message():
    req_data = request.get_json()
    print(req_data)
    form_values = {
        "text": {
            'required': False,
            'default': None,
            'type': str,
            'validator': None
        },
        "receiver_id": {
            'required': False,
            'default': None,
            'type': int,
            'validator': None
        }
    }
    check_fields(req_data, form_values)
    sender_id = g.current_user.id
    receiver_id = int(req_data["receiver_id"])
    if (Like.is_liked(sender_id, receiver_id) and Like.is_liked(receiver_id, sender_id)) \
      and (not User.user_is_blocked(sender_id, receiver_id) and not User.user_is_blocked(receiver_id, sender_id)):
        message = Message.from_dict({
            "sender_id": sender_id,
            "receiver_id": receiver_id,
            "text": req_data["text"]
        })
        message.create()
        text = Notification.notification_text('message', g.current_user)
        notification = Notification.from_dict({
            "user_id": receiver_id,
            "text": text,
            "type": "message"
        })
        notification.create()

        return jsonify(ok=True)
    abort(http.HTTPStatus.FORBIDDEN)
Exemplo n.º 8
0
def update_name():
	req_data = request.get_json()
	form_values = {
		"first_name": {
			'required': False,
			'default': None,
			'type': str,
			'validator': None
		},
		"last_name": {
			'required': False,
			'default': None,
			'type': str,
			'validator': None
		},
		"username": {
			'required': False,
			'default': None,
			'type': str,
			'validator': None
		}
	}
	current_app.logger.debug(f"[update name], the request is: {req_data}")
	check_fields(req_data, form_values)
	current_user = g.current_user

	if getattr(current_user, 'first_name') != req_data['first_name'] and len(req_data['first_name']) > 0:
		current_user.first_name = req_data['first_name']
	if getattr(current_user, 'last_name') != req_data['last_name'] and len(req_data['last_name']) > 0:
		current_user.last_name = req_data['last_name']
	if getattr(current_user, 'username') != req_data['username'] and len(req_data['username']) > 0:
		if User.get_by_username(req_data['username']):
			abort(http.HTTPStatus.CONFLICT)  # If another user has this username
		current_user.username = req_data['username']
	current_user.update()

	return jsonify({"ok": True})
Exemplo n.º 9
0
def reset_password(token):
    req_data = request.get_json()
    form_values = {
        "password": {
            'required': True,
            'default': None,
            'type': str,
            'validator': None
        }
    }
    check_fields(req_data, form_values)

    try:
        email = serializer.verify_token(token, 'reset_pwd').get('email')
        current_user = User.get_by_email(email)
        if not current_user:
            abort(http.HTTPStatus.UNAUTHORIZED)
        if not current_user.check_password_strength(req_data["password"]):
            abort(http.HTTPStatus.BAD_REQUEST)
        current_user.set_password(req_data["password"])
        current_user.update()
        return jsonify({"ok": True})
    except (itsdangerous.BadData, AssertionError):
        abort(http.HTTPStatus.UNAUTHORIZED)
Exemplo n.º 10
0
def users_filter(page_number):
    """
	:param page_number: page number
	:request -> {
		"filter": {
			"age": {"min": 0, "max": 99},
			"rating": {"min": 0, "max": 10},
			"distance": {"min": 0, "max": 100}
		},
		"sort": {
			"order_by": "asc" (def) | "desc",
			"sort_by": "id" (def) | "age", "rating", "distance"
		}
	}
	:return:
	"""
    per_page = 5
    count_users = 0
    if page_number < 0:
        page_number = 0
    req_data: dict = request.get_json()
    if not req_data:
        abort(http.HTTPStatus.BAD_REQUEST)
    # Filter
    filter_validation = {
        "min": {
            'required': False,
            'default': 0,
            'type': int,
            'validator': None
        },
        "max": {
            'required': False,
            'default': 0,
            'type': int,
            'validator': None
        },
    }

    req_data.setdefault("filter", {})
    req_data["filter"].setdefault("age", {})
    req_data["filter"].setdefault("rating", {})
    req_data["filter"].setdefault("distance", {})
    req_data["filter"].setdefault("tags", [])
    # Age
    filter_validation["max"]["default"] = 99
    check_fields(req_data["filter"]["age"], filter_validation)
    # Rating
    filter_validation["max"]["default"] = 10
    check_fields(req_data["filter"]["rating"], filter_validation)
    # Distance
    filter_validation["max"]["default"] = 10000
    check_fields(req_data["filter"]["distance"], filter_validation)
    # Set location based on ip_location if user doesn't have
    g.current_user: User
    req_data.setdefault("ip_location", {})
    location_from_ip = False
    if (not getattr(g.current_user, 'latitude') or not getattr(g.current_user, 'longitude')) \
     and req_data['ip_location'].get('ip_lat') and req_data['ip_location'].get('ip_lon'):
        location_from_ip = True
        g.current_user.latitude = req_data['ip_location'].get('ip_lat')
        g.current_user.longitude = req_data['ip_location'].get('ip_lon')
        g.current_user.update()
    # Sort
    req_data.setdefault("sort", {})
    req_data["sort"].setdefault("order_by", "desc")
    req_data["sort"].setdefault("sort_by", "my_tags")
    req_data["sort"]["order_by"] = req_data["sort"]["order_by"].upper()
    if req_data["sort"]["order_by"] not in ("ASC", "DESC"):
        abort(http.HTTPStatus.BAD_REQUEST)
    if req_data["sort"]["sort_by"] not in ("id", "age", "distance", "rating",
                                           "tags", "my_tags"):
        abort(http.HTTPStatus.BAD_REQUEST)
    # Here we are with all data valid

    search_users: [User] = []
    payload = {
        'age_min': int(req_data['filter']['age']['min']),
        'age_max': int(req_data['filter']['age']['max']),
        'rating_min': int(req_data['filter']['rating']['min']),
        'rating_max': int(req_data['filter']['rating']['max']),
        'dist_min': int(req_data['filter']['distance']['min']),
        'dist_max': int(req_data['filter']['distance']['max']),
        'selected_tags': req_data['filter']['tags'],
        'my_tags': g.current_user.tags,
        'order_by_field': req_data['sort']['sort_by'],
        'order_by': req_data['sort']['order_by'],
        'limit': per_page,
        'offset': per_page * page_number
    }

    if g.current_user.sex_pref == 'bi':
        payload['gender'] = (g.current_user.gender, )
        payload['sex_pref'] = ('h**o', 'bi')

        result = g.current_user.get_filtered(**payload)
        if result:
            search_users = result
            count_users = g.current_user.count_filtered(**payload)
        payload['gender'] = (g.current_user.opposite_gender, )
        payload['sex_pref'] = ('hetero', 'bi')

        result = g.current_user.get_filtered(**payload)
        if result:
            search_users += result
            count_users += g.current_user.count_filtered(**payload)

        def get_sort_key(u: User):
            if req_data["sort"]["sort_by"] == 'tags':
                return len(getattr(u, req_data["sort"]["sort_by"]))
            elif req_data["sort"]["sort_by"] == 'my_tags':
                return -len(set(u.tags) & set(g.current_user.tags))
            value = getattr(u, req_data["sort"]["sort_by"])
            if value is None:
                if req_data["sort"]["sort_by"] == 'distance':
                    return (math.inf,
                            -math.inf)[req_data["sort"]["order_by"] == 'DESC']
                return 0
            return value

        search_users.sort(key=get_sort_key,
                          reverse=req_data["sort"]["order_by"] == 'DESC')

    elif g.current_user.sex_pref == 'h**o':
        payload['gender'] = (g.current_user.gender, )
        payload['sex_pref'] = ('h**o', 'bi')

        result = g.current_user.get_filtered(**payload)
        if result:
            search_users = result
            count_users = g.current_user.count_filtered(**payload)
    else:
        payload['gender'] = (g.current_user.opposite_gender, )
        payload['sex_pref'] = ('hetero', 'bi')

        result = g.current_user.get_filtered(**payload)
        if result:
            search_users = result
            count_users = g.current_user.count_filtered(**payload)
    if location_from_ip:
        g.current_user.latitude = None
        g.current_user.longitude = None
        g.current_user.update()
    search_users = [u.get_view(with_attr={"distance"}) for u in search_users]
    return jsonify(users=search_users,
                   total_users=count_users,
                   per_page=per_page)
Exemplo n.º 11
0
def update_personal_details():
	req_data = request.get_json()
	form_values = {
		"gender": {
			'required': False,
			'default': None,
			'type': str,
			'validator': None
		},
		"sex_pref": {
			'required': False,
			'default': 'bi',
			'type': str,
			'validator': None
		},
		"bio_text": {
			'required': False,
			'default': None,
			'type': str,
			'validator': None
		},
		"tags": {
			'required': False,
			'default': None,
			'type': [],
			'validator': None
		},
		"dob": {
			'required': False,
			'default': None,
			'type': str,
			'validator': None
		}
	}
	current_app.logger.debug(f"[update profile] the request is: {req_data}")
	check_fields(req_data, form_values)
	current_user = g.current_user

	if getattr(current_user, 'gender') != req_data['gender']:
		current_user.gender = req_data['gender']
	if getattr(current_user, 'sex_pref') != req_data['sex_pref']:
		current_user.sex_pref = req_data['sex_pref']
	if req_data.get('dob') and type(req_data['dob']) == str:
		try:
			dob = datetime.datetime.strptime(req_data['dob'][:10], '%Y-%m-%d')
			if not (datetime.date.today() - datetime.timedelta(365 * 99) < dob.date() < datetime.date.today()):
				abort(http.HTTPStatus.BAD_REQUEST)
			current_user.dob = dob
		except ValueError:
			abort(http.HTTPStatus.BAD_REQUEST)

	if getattr(current_user, 'bio_text') != req_data['bio_text']:
		current_user.bio_text = req_data['bio_text']

	allowed_tags = {'42', 'eco', 'geek', 'veggie', 'music', 'travel'}
	for tag in req_data['tags']:
		if tag not in allowed_tags:
			abort(http.HTTPStatus.BAD_REQUEST)

	current_user.tags = req_data['tags']

	current_user.update()

	return jsonify({"ok": True})