Beispiel #1
0
def new(*args, **kwargs):
    currentUser = User.get().filter_by(
        name=kwargs['token']['name']).first_or_404()

    if not currentUser.role.permissions.add_post:
        return make_response(
            jsonify({
                'operation': 'error',
                'error': 'Missing permissions'
            }), 401)

    if not request.form['data']:
        return make_response(
            jsonify({
                'operation': 'error',
                'error': 'Missing data'
            }), 401)

    data = json.loads(str(request.form['data']))

    if not data['title'] or not data['content'] or not data['tags']:
        return make_response(
            jsonify({
                'operation': 'error',
                'error': 'Missing data'
            }), 401)

    index = str(db.session.execute(Sequence('post_id_seq')))
    thumbnail_link = None
    if data['image']:
        thumbnail = SaveImage(index)
        thumbnail_link = url_for('static',
                                 filename='thumbail_post/{}'.format(thumbnail))
    else:
        thumbnail_link = 'none'

    lang = translate.getLanguageForText(
        str(cleanhtml(data['content'])).encode('utf-8-sig'))

    langQuery = Languages.get().filter_by(code=lang.iso_tag).first()

    if langQuery is None:
        new_lang = Languages(name=lang.language, code=lang.iso_tag)
        new_lang.add()
        langQuery = new_lang

    tags_ids = []
    tags = []

    for tag in data['tags']:
        check = Post_Tag.get().filter_by(name=tag).first()

        if check is None:
            new_tag = Post_Tag(name=tag, count=1)
            new_tag.add()
            check = new_tag
        else:
            setattr(check, 'count', Post_Tag.count + 1)
            check.save()

        tags_ids.append(check.id)

    for tag_id in tags_ids:
        tags.append({"post": index, "tag_id": tag_id})

    nPost = NewPostSchema().load({
        "id":
        int(index),
        "title":
        data['title'],
        "read_time":
        str(readtime.of_html(data['content'])),
        "author_id":
        currentUser.id,
        "language_id":
        langQuery.id,
        "info": {
            "thumbnail": thumbnail_link,
            "text": data['content'],
            "tags": tags
        },
        "link":
        '/post/' + (str(data['title']).replace(' ', '-')).replace('?', '') +
        '-' + str(index)
    })

    nPost.add()

    for user in currentUser.followed:
        not_id = str(db.session.execute(Sequence('notification_id_seq')))
        notification = Notification(
            id=int(not_id),
            author=currentUser.id,
            user=user.user,
            type=5,
            title=nPost.title,
            body='{} shared a new post'.format(currentUser.name),
            link=nPost.link + '?notification_id=' + str(not_id))
        send_notification(
            user.user, {
                'text': '{} shared a new post'.format(currentUser.name),
                'link': nPost.link + '?notification_id=' + str(not_id),
                'icon': currentUser.info.avatar_img,
                'id': int(not_id)
            })
        notification.add()

    return make_response(jsonify({
        'operation': 'success',
        'link': nPost.link
    }), 200)
Beispiel #2
0
def register():
    data = request.json

    if data is None or data['username'] is None or data[
            'email'] is None or data['first_name'] is None or data[
                'last_name'] is None or data['password'] is None:
        return jsonify({'register': 'Error'}), 401

    check = User.get().filter_by(name=data['username']).first()

    if check is not None:
        return jsonify({'register': 'Username taken'}), 401

    check = User.get().filter_by(email=data['email']).first()

    if check is not None:
        return jsonify({'register': 'Email taken'}), 401

    token = serializer.dumps(data['email'], salt='register-confirm')

    if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
        userIP = request.environ['REMOTE_ADDR']
    else:
        userIP = request.environ['HTTP_X_FORWARDED_FOR']

    userIP = userIP.split(',')[0]

    if userIP == "127.0.0.1":
        userIP = "86.123.189.180"

    resp = requests.get(
        ('https://www.iplocate.io/api/lookup/{}').format(userIP))
    userLoc = resp.json()
    iso_code = userLoc['country_code']
    api_2 = requests.get(
        ("https://restcountries.eu/rest/v2/alpha/{}").format(iso_code))
    result_2 = api_2.json()

    index = str(db.session.execute(Sequence('users_id_seq')))

    msg = Message('Confirm Email Registration',
                  sender='*****@*****.**',
                  recipients=[data['email']])
    link = 'https://new-app.dev/?email={}&token={}'.format(
        data['email'], token)
    msg.html = render_template('email_register.html',
                               register=link,
                               email='*****@*****.**')
    mail.send(msg)

    check_loc = Ip_Location.get().filter_by(ip=userIP).first()
    check_lang = Languages.get().filter_by(
        code=result_2['languages'][0]['iso639_1']).first()

    os.umask(0)
    os.mkdir(config.get('ROOT_PATH') + '/static/users/' + index)

    if check_loc is None:
        ip_loc_index = str(db.session.execute(Sequence('ip_location_id_seq')))
        loc_index = str(db.session.execute(Sequence('location_id_seq')))

    new_user_json = {
        "id": index,
        "confirmed": False,
        "email": data['email'],
        "info": {
            "avatar_img":
            CreateAvatar({
                "id": index,
                "first_name": data['first_name'],
                "last_name": data['last_name']
            }),
            "user":
            index,
            "first_name":
            data['first_name'],
            "last_name":
            data['last_name']
        },
        "pers": {
            "user": index
        },
        "name": data['username'],
        "role_id": 2,
        "status_id": 2,
        "password": data["password"]
    }

    if check_lang is None:
        new_user_json["language"] = {
            "code": result_2['languages'][0]['iso639_1'],
            "name": result_2['languages'][0]['name'],
        }
    else:
        new_user_json["language"] = NewLanguageSchema().dump(check_lang)

    if check_loc is None:
        new_user_json["location"] = {
            "ip": userIP,
            "id": ip_loc_index,
            "location": {
                "id": loc_index,
                "city": userLoc['city'],
                "country": userLoc['country'],
                "flag": result_2['languages'][0]['iso639_1'],
                "iso": userLoc['country_code'],
                "latitude": str(userLoc['latitude']),
                "longitude": str(userLoc['longitude']),
            }
        }
    else:
        new_user_json["location"] = NewLocationSchema().dump(check_loc)

    new_user = NewUserSchema().load(new_user_json)
    new_user.add()

    return make_response(jsonify({'register': 'success'}), 200)