def _wrap(*args, **kwargs):
        if 'Authorization' not in request.headers:
            # Unauthorized
            print("No token in header")
            return unauthorized('lol')

        print("Checking token...")
        user_id = validate_token(request.headers['Authorization'])
        if user_id is None:
            print("Check returned FAIL!")
            # Unauthorized
            return unauthorized('lol')

        return fn(user_id=user_id, *args, **kwargs)
Beispiel #2
0
def edit_hat(username):
    hat = Hat.query.filter_by(username=username).first()
    if hat is None:
        return not_found()
    if g.current_user not in hat.users:
        logger.info(
            '{} попытался отредактировать {}, но не входит в список носителей шляпы'
            .format(g.current_user, hat))
        return unauthorized()

    try:
        hat.display_name = request.json['display_name']
        if request.json.get('add_user', '') is not '':
            u = User.query.filter_by(username=request.json['add_user']).first()
            if u is not None:
                hat.users.append(user)
        hat.about_me = request.json['about_me']
        db_session.add(hat)
        db_session.commit()
        logger.info('{u} обновил шляпу {h}: {d}, {a}, {us}'.format(
            u=g.current_user,
            d=hat.display_name,
            a=hat.about_me,
            us=hat.users,
            h=hat))
    except Exception as exc:
        logging.warn('Не получилось отредактировать шляпу {}: {}'.format(
            hat, exc))
        return bad_request()
    return jsonify(hat=hat_schema.dump(hat))
Beispiel #3
0
def delete_hat(username):
    hat = Hat.query.filter_by(username=username).first()
    if hat is None:
        return not_found()
    if not g.current_user.can(Permission.Admin) and not hat.is_wearable_by(
            g.current_user):
        return unauthorized()
    db_session.delete(hat)
    db_session.commit()
    return jsonify(hat=hat_schema.dump(hat))  # FIXME: test?
Beispiel #4
0
def get_token():
    try:
        p = pass_auth_schema.load(request.json)
    except ValidationError as exc:
        return bad_request()
    u = User.query.filter_by(username=p['username']).first()
    if u is None:
        return unauthorized('Не получилось залогиниться')
    if u.check_password(p['password']):
        token = u.get_token()
        token.expire_in_2_weeks()
        db_session.add(token)
        db_session.add(u)
        db_session.commit()

        return jsonify(token=token_schema.dump(token),
                       username=u.username,
                       user=user_schema.dump(u))
    return unauthorized('Не получилось залогиниться')
Beispiel #5
0
def edit_post(id):
    p = Post.query.filter_by(id=id).first()
    if p is None:
        abort(404)
    if p.user != g.current_user:
        return unauthorized()
    update = post_schema.load(request.json)
    p.body = update['body']
    db_session.add(p)
    db_session.commit()
    return jsonify(post=post_schema.dump(p))
 def post() -> Response:
     """POST request method for retrieving user web token.."""
     data = request.get_json()
     try:
         Users(**data).validate()
         user = Users.objects.get(email=data.get('email'))
         correct_pwd = user.check_pwd_hash(data.get('password'))
         if correct_pwd:
             expires = datetime.timedelta(days=5)
             access_token = create_access_token(identity=str(user.id),
                                                expires_delta=expires)
             refresh_token = create_refresh_token(identity=str(user.id))
             output = {
                 'access_token': access_token,
                 'user_id': str(user.id),
                 'refresh_token': refresh_token
             }
             return jsonify({'result': output})
         else:
             return unauthorized()
     except DoesNotExist:
         return unauthorized()
     except (FieldDoesNotExist, TypeError, ValidationError):
         return wrong_value()
 def post() -> Response:
     """
     POST response method for retrieving user web token.
     :return: JSON object
     """
     data = request.get_json()
     user = Users.objects.get(email=data.get('email'))
     auth_success = user.check_pw_hash(data.get('password'))
     if not auth_success:
         return unauthorized()
     else:
         expiry = datetime.timedelta(days=5)
         access_token = create_access_token(identity=str(user.id), expires_delta=expiry)
         refresh_token = create_refresh_token(identity=str(user.id))
         return jsonify({'result': {'access_token': access_token,
                                    'refresh_token': refresh_token,
                                    'logged_in_as': f"{user.email}"}})
Beispiel #8
0
def create_post():
    p = new_post_schema.load(request.json)
    hat = Hat.query.filter_by(username=request.json['username']).first()
    if hat is None:
        hat = g.current_user.hats[0]
    if not hat.is_wearable_by(g.current_user):
        logger.info('Пользователь {} пытался запостить со шляпой {}'.format(
            g.current_user, hat))
        return unauthorized('Не твоя шляпа')
    if p is not None:
        p.author = hat
        p.user = g.current_user
        p.writer_feed = hat.writer_feed
        db_session.add(p)
        db_session.commit()
        logger.info('Created post {}'.format(p))
        notify_readers.delay(p.writer_feed.id, p.id)
        return jsonify(post=post_schema.dump(p))
    return bad_request('Не тот формат')
Beispiel #9
0
def login():
    data = request.get_json()
    user = Users.objects.get(email=data.get('email'))
    auth_success = user.check_pw_hash(data.get('password'))

    if not auth_success:
        return unauthorized()
    else:
        expiry = datetime.timedelta(days=5)
        access_token = create_access_token(identity=str(user.id),
                                           expires_delta=expiry)
        refresh_token = create_refresh_token(identity=str(user.id))
        return jsonify({
            'result': {
                'access_token': access_token,
                'refresh_token': refresh_token,
                'logged_in_as': f"{user.email}"
            }
        })
Beispiel #10
0
def create_hat():
    if not g.current_user.can(Permission.CreateHats):
        return unauthorized()

    h = hat_schema.load(request.json)
    users = [g.current_user]

    writer_feed = WriterFeed()
    hat = Hat(username=h['username'],
              users=users,
              writer_feed=writer_feed,
              display_name=h['display_name'],
              about_me=h['about_me'])
    g.current_user.reader_feed.writer_feeds.append(writer_feed)
    db_session.add(hat)
    db_session.commit()

    logger.info('{} создал шляпу {}'.format(g.current_user, hat))
    return jsonify(hat=hat_schema.dump(hat))
    def post(self) -> Response:
        data = request.get_json(force=True)
        user = UsersModel.find_by_username(data['user']['username'])
        auth_success = user and safe_str_cmp(user.password,
                                             data['user']['password'])
        if not auth_success:
            return unauthorized()
        else:
            expiry = timedelta(days=5)
            access_token = create_access_token(identity=str(user.id),
                                               expires_delta=expiry)

            return jsonify({
                'user': {
                    'token': access_token,
                    'bio': user.bio,
                    'email': user.email,
                    'image': f"{user.image}",
                    'username': f"{user.username}"
                }
            })