Beispiel #1
0
def register_profile(data):
    name, email, password = data['name'], data['email'], data['password']
    subscription_type = ProfileType.objects(name__icontains='subscription').first()
    if Profile.objects(email__iexact=email, type__nin=[str(subscription_type.id)]).first():
        raise Exception('Profile already exists')

    type = ProfileType.objects(name__iexact='Enthusiast').first()
    profile = Profile.objects(email__iexact=email).first()
    if not profile:
        profile = Profile.create(name=name, email=email, type=[type], roles=['Basic User'])
    else:
        profile.type = [type]
    profile.password = data['password']
    profile.save()

    if profile and profile.id:
        from app.views import env
        session['user'] = str(profile.id)
        template_path = 'notifications/successfully_registered.html'
        template = env.get_template(template_path)
        context = {}
        context['user']  = profile
        html = template.render(**context)
        send_single_email("[Fitrangi] Successfully registered", to_list=[profile.email], data=html)
    return profile
Beispiel #2
0
        def get_messages(user, initial=None):

            user = Profile.objects(pk=user).first()
            if not user:
                return None
            messages = ChatMessage.get_user_list(user)
            if initial:
                initial = Profile.objects(pk=initial).first()
            _user_list = []
            if initial:
                initial_user = dict(id=str(initial.id), image=initial.cover_image_path, name=initial.name, notifications='')
                _user_list.append(initial_user)

            for m, v in messages.iteritems():
                if initial and m == initial:
                    continue
                data = dict(id=str(m.id), image=m.cover_image_path, name=m.name, notifications=str(v))
                _user_list.append(data)

            user_list = []
            for z in _user_list:
                messages = ChatMessage.get_message_between(user, Profile.objects(pk=z['id']).first(), all=True)
                messages = [dict(my=True if u.author == user else False, image=u.author.cover_image_path, message=u.message, time=u.since) for u in messages]
                all = dict(messages=messages)
                for _k, _v in z.iteritems():
                    all[_k] = _v
                user_list.append(all)
            return user_list
Beispiel #3
0
    def get_or_create_steam_user(steamid):
        """
        If User with steamid already exists return that. If not, create
        new User with linked steam_oid account and profile.

        The user will not have an email yet if new.
        Args:
            steamid: The user's steamid got from steam openid
        Returns:
            The newly created or current steam User
        """
        steam_user = User.get_steam_user(steamid)
        if not steam_user:
            # all steam users also exist in profile table
            profile = Profile.get(steamid)
            if not profile:
                data = get_summaries_and_bans([steamid])[0]
                profile = Profile(**data)
            user = User()
            user.steam_oid = SteamOID()
            user.steam_oid.profile = profile
            db.session.add(user)
            db.session.commit()
            return user
        return steam_user
Beispiel #4
0
def registration():
    if request.method == 'POST':
        name = request.form.get('name', None)
        email = request.form.get('email', None)
        password = request.form.get('password', None)
        confirm = request.form.get('confirm', None)
        if password != confirm:
            return jsonify(dict(status='error', message='Passwords do not match'))
        type = ProfileType.objects(name__icontains='subscription').first()
        if Profile.objects(email__iexact=email, type__nin=[str(type.id)]).first():
            return jsonify(dict(status='error', message='Email already exists, have you forgotten your password?'))
        type = ProfileType.objects(name__iexact='Enthusiast').first()
        profile = Profile(name=name, email=email, type=[type], roles=['Basic User'])
        profile.password  = password
        profile.save()
        if profile and profile.id:
            session['user'] = str(profile.id)
            mail_data = render_template('notifications/successfully_registered.html', user=profile)
            send_single_email("[Fitrangi] Successfully registered", to_list=[profile.email], data=mail_data)
            return jsonify(dict(status='success', message='Profile created and logged in.', node=str(profile.id)))
        return jsonify(dict(status='error', message='Failed to register. Please try again.'))
    if hasattr(g, 'user') and g.user is not None:
        return redirect('/explore')
    from app.views import force_setup_context
    title, card, context = PageManager.get_common_title_and_page('register')
    context = force_setup_context(context)
    context['title'] = title
    context['card']  = card
    context['referrer'] = request.referrer
    return render_template('site/layouts/empty_layout.html', **context)
Beispiel #5
0
def start_app():
    global admin
    from app.models.extra.sessions import MongoSessionInterface
    from app.models.profile import Profile

    app.session_interface = MongoSessionInterface()

    #from app.handlers.views import *
    #from app.handlers.editors import *
    print Profile.objects.count()
    admin_user = Profile.objects(roles__in=['Admin']).first()
    if admin_user is None:
        profile = Profile(name='Arshad Ansari', roles=['Admin'], email='*****@*****.**')
        profile.password = '******'
        profile.save()

    import logging
    if not app.debug:
        logging.basicConfig(filename='fitrangi-flask-error.log',level=logging.DEBUG)
    else:
        logging.basicConfig()
        logging.getLogger().setLevel(logging.DEBUG)

    class MyAdminIndexView(AdminIndexView):

        @expose('/')
        def index(self):
            if not (hasattr(g, 'user') and g.user is not None and 'Admin' in g.user.roles):
                return redirect('/')
            return super(MyAdminIndexView, self).index()


    admin = flask_admin.Admin(app, 'Fitrangi Dashboard',index_view=MyAdminIndexView(), base_template='/admin/base_admin.html')
Beispiel #6
0
def register_user(registration_data, ignore_token=False) -> User:
    """
    Зарегистровать пользователя по данным формы (сгенерированной get_registration_form()
    :param ignore_token: Указывает, игнорировать ли токен. Полезно, если в БД нет пользователей
    или при тестировании
    :param registration_data: Данные формы
    :return: Пользователь
    """
    token_ok, token = auth_user_registration(registration_data, ignore_token)
    if not token_ok:
        raise Exception("Токен неверен")
    registration_data = dict(registration_data)
    user = User(login=registration_data['login'])
    user.set_password(registration_data['password'])
    del registration_data['login']
    del registration_data['password']
    if 'token' in registration_data:
        del registration_data['token']
    profile = Profile(user=user, **registration_data)
    user.save()
    try:
        profile.save()
    except:
        user.delete()
        raise
    activate_token(token)
    return user
Beispiel #7
0
def test_user_untrack_profile_not_tracking(setup, mock_steam_single, steamid):
    u = User()
    db.session.add(u)
    db.session.commit()
    with mock_steam_single:
        Profile.get_profiles([steamid])
        is_untracked = u.untrack_profile(steamid)
    assert not is_untracked
Beispiel #8
0
def test_user_get_tracking_single(setup, mock_steam_multiple, steamids):
    u = User()
    db.session.add(u)
    db.session.commit()
    with mock_steam_multiple:
        Profile.get_profiles(steamids)
    u.track_profile(steamids[0])
    assert u.tracking.first() == u.get_tracking([steamids[0]])[0]
Beispiel #9
0
def subscribe(data):
    email = data.get('email', None)
    assert email is not None
    node = Profile.objects(email__iexact=email).first()
    if not node:
        type = ProfileType.objects(name__iexact='Subscription Only').first()
        node = Profile(email=email, type=[type])
        node.save()
    return node
Beispiel #10
0
def switch_profile(node, profile):
    from flask import g
    user = g.user if hasattr(g, 'user') else None
    if not user: raise Exception('Invalid user')
    node = Profile.objects(pk=node).first()
    profile = Profile.objects(pk=profile).first()
    assert node.id == user.id
    from flask import session
    session['user'] = str(profile.id)
    return node
Beispiel #11
0
def test_user_get_tracking_all(setup, mock_steam_multiple, steamids):
    u = User()
    db.session.add(u)
    db.session.commit()
    with mock_steam_multiple:
        Profile.get_profiles(steamids)
    for steamid in steamids:
        u.track_profile(steamid)
    assert len(u.tracking.all()) == len(u.get_tracking(steamids))
    assert len(u.tracking.all()) == len(u.get_tracking())
Beispiel #12
0
def follow_profile(action, profile, profile2):
    node = Profile.objects(pk=profile).first()
    other = Profile.objects(pk=profile2).first()
    print '[*] Follow command', node, other
    if not node or not other:
        raise Exception("Invalid id")
    if action == 'follow':
        RelationShips.follow(node, other)
    else:
        RelationShips.un_follow(node, other)
    return node
Beispiel #13
0
        def create_message(user, to_user, message):
            author = Profile.objects(pk=user).first()
            recipient = Profile.objects(pk=to_user).first()
            message = ChatMessage.create_message(author, recipient, message)

            data = dict(id=to_user, image=author.cover_image_path, name=author.name, notifications=1, messages=[dict(my=True, author=user, recipient=to_user, message=message.message, image=author.cover_image_path, time=message.since)])
            data2 = dict(id=str(author.id), image=author.cover_image_path, name=author.name, notifications=1, messages=[dict(my=False, author=user, recipient=to_user, message=message.message, image=author.cover_image_path, time=message.since)])
            if CONCURRENT_USERS.has_key(to_user) and (datetime.datetime.now() - CONCURRENT_USERS[to_user]).seconds < 30:
                self.publish('com.fitrangi.messaging.listener.%s' % to_user, data2)

            return data
async def get_profile_for_user(
        conn: Connection,
        target_username: str,
        current_username: Optional[str] = None) -> Profile:
    user = await get_user(conn, target_username)
    if not user:
        raise HTTPException(status_code=HTTP_404_NOT_FOUND,
                            detail=f"User {target_username} not found")

    profile = Profile(**user.dict())
    profile.following = await is_following_for_user(conn, current_username,
                                                    target_username)

    return profile
Beispiel #15
0
def logout():
    """Logout view"""
    if current_user.is_authenticated:
        user_id = current_user.id
        logout_user()
        if request.args.get('clear') == 'true':
            Friend.delete().where(Friend.user == user_id).execute()
            Friend.delete().where(Friend.friend == user_id).execute()
            Position.delete().where(Position.profile == user_id).execute()
            Profile.delete().where(Profile.id == user_id).execute()
            FlaskStorage.user.delete().where(
                FlaskStorage.user.user == user_id).execute()
            User.delete().where(User.id == user_id).execute()
    return redirect('/')
Beispiel #16
0
    def get(self):
        logger.log_python_api_get(SuggestedProfilesResource.api_url)
        current_user_profile = Profile.get(id=current_user.id)
        skills_list = safe_split_strip_remove_empty(
            current_user_profile.skills)
        location_part_list = safe_split_strip_remove_empty(
            current_user_profile.location)
        position_title_list = [p.title for p in current_user_profile.positions]

        clauses = [Profile.id != current_user.id]

        or_clauses = []
        for skill in skills_list:
            or_clauses.append(Profile.skills.contains(skill))
        for location_part in location_part_list:
            or_clauses.append(Profile.location.contains(location_part))
        if any(position_title_list):
            subquery = Position.select(Param('1')).where(
                Position.profile == Profile.id,
                Position.title << position_title_list)
            or_clauses.append(Clause(SQL('EXISTS'), subquery))
        if any(or_clauses):
            clauses.append(reduce(operator.or_, or_clauses))

        friends = Friend.select(
            Friend.friend).where(Friend.user == current_user.id).execute()
        clauses.append(~(Profile.id << [f.friend.id for f in friends]))

        profiles = Profile.select().where(reduce(
            operator.and_, clauses)).order_by(fn.Rand()).limit(100)
        for profile in profiles:
            profile.score = 0
            for skill in skills_list:
                if profile.skills and skill in profile.skills:
                    profile.score += 10
            for part in location_part_list:
                if profile.location and part in profile.location:
                    profile.score += 10
            if any(position_title_list):
                profile.position_fetch = profile.positions.execute()
                for position_title in position_title_list:
                    if any(position.title == position_title
                           for position in profile.position_fetch):
                        profile.score += 10

        suggested_profiles = sorted(profiles,
                                    key=lambda profile: -profile.score)[:2]

        return list(map(lambda p: self.profile_to_dict(p), suggested_profiles))
Beispiel #17
0
def submit_profile():
    age = None
    gender = None
    gen_pres = None
    style = None
    fav_color = None
    loc = None

    if request.method == 'POST':
        age = str(request.form['age'])
        gender = str(request.form['gender'])
        gen_pres = str(request.form['gen_pres'])
        style = str(request.form['style'])
        fav_color = str(request.form['fav_color'])
        loc = str(request.form['loc'])

        try:
            reg = Profile(age, gender, gen_pres, style, fav_color, loc)
            db.session.add(reg)
            db.session.commit()
            return redirect(url_for('home.index'))
        except:
            flash('something\'s amiss')


    return render_template('home/profile.html')
Beispiel #18
0
 def notification_counts(user):
     print("Notification count request by user [{}]".format(user))
     profile = Profile.objects(pk=user).first()
     if not profile:
         return {}
     CONCURRENT_USERS[str(profile.id)] = datetime.datetime.now()
     return dict(public_activity_count=profile.public_activity_count, private_activity_count=profile.private_activity_count)
Beispiel #19
0
def messages_list(all):
    user = Profile.objects(pk=request.args.get('user')).first()
    logged_in_user = g.user
    messages = list(ChatMessage.get_message_between(user, logged_in_user, all=all))
    response = dict(result=[dict(my=True if u.author == logged_in_user else False, image=u.author.cover_image_path, message=u.message, time=u.since) for u in messages])
    print 'Messages: ', logged_in_user, len(response['result'])
    return jsonify(response)
Beispiel #20
0
def forgot_password():
    email = request.form.get('email', None)
    if not email:
        return jsonify(dict(status='error', message='No email provided.'))
    try:
        profile = Profile.objects(email__iexact=email).first()
        if profile is None or profile.id is None or 'Subscription Only' in [u.name for u in profile.type]:
            return jsonify(dict(status='error', message='User does not exists.'))
        else:
            import random
            u, v, w = list('ABCEFGHIJKLMNOPQRSTUVWXYZ'), list('abcefghijklmnopqrstuvwxyz'), range(0, 10)
            random.shuffle(u), random.shuffle(v), random.shuffle(w)
            old_password = profile.password
            password = "******" % (''.join(u[0:5]), ''.join(v[0:5]), ''.join(str(x) for x in w[0:3]))
            profile.password = password
            profile.save()
            from app.handlers.messaging import send_single_email
            flash("Successfully sent email with new password.", category='success')
            mail_data = render_template('notifications/password_reset.html', user=profile, password=password)
            send_single_email("[Fitrangi] Password reset on Fitrangi.com", to_list=[profile.email], data=mail_data)
            return jsonify(dict(status='success', message='Password has been reset, please check  your email.', node=str(profile.id)))
    except Exception,e:
        print e
        if profile and old_password:
            profile.password = old_password
            profile.save()
Beispiel #21
0
def create_admin():
    profile_type = ProfileType.objects(name__iexact='Enthusiast').first()
    roles = ['Admin', 'Basic User']
    is_business_profile = False
    size = Profile.objects(roles__in=['Admin']).count()
    if size>0:
        return
    else:
        p = Profile(name='Arshad Ansari', email='*****@*****.**',
                    is_business_profile=is_business_profile,
                    website='', facebook='', linked_in='',
                    type=[profile_type], roles=roles, phone='')

        p.password = '******'
        p.save()
        print 'Profile: %s' % (p.name)
Beispiel #22
0
 def change_password(self):
     form = ProfileForm()
     profile = Profile.objects(pk=g.user.id).first()
     if request.method == 'POST':
         profile.name = request.form.get('name', '')
         profile.about = request.form.get('about', '')
         profile.phone = request.form.get('phone', '')
         profile.website = request.form.get('website', '')
         profile.facebook = request.form.get('facebook', '')
         profile.twitter = request.form.get('twitter', '')
         profile.google_plus = request.form.get('google_plus', '')
         profile.linked_in= request.form.get('linked_in', '')
         profile.youtube_channel = request.form.get('youtube_channel', '')
         profile.blog_channel = request.form.get('blog_channel', '')
         profile.save()
         flash('Profiled updated successfully', category='success')
     form.name.data = profile.name
     form.about.data = profile.about
     form.phone.data = profile.phone
     form.website.data = profile.website
     form.facebook.dta = profile.facebook
     form.twitter.data = profile.twitter
     form.google_plus.data = profile.google_plus
     form.linked_in.data = profile.linked_in
     form.youtube_channel.data = profile.youtube_channel
     form.blog_channel.data = profile.blog_channel
     return self.render('/admin/my_custom/settings.html', form=form, action_name='Edit Your Profile', settings='profile')
Beispiel #23
0
def init_data_db():
    fp = ''
    with profile_session_scope() as session:
        profile_obj = Profile.get_active(session)
        if profile_obj is None:
            raise RuntimeError('cannot init data db without active profile')
        fp = profile_obj.data_db_filepath

    log.debug('init data db at: {}'.format(fp))
    engine = sqlalchemy.create_engine('sqlite:///{}'.format(fp))
    data_db.configure(bind=engine)
    engine.execute("PRAGMA journal_mode=WAL")

    log.debug("check data-db schema")
    reset_blocks = False
    for table_name, table in data_base.metadata.tables.items():
        log.debug("check {}-db schema".format(table.name))
        if not check_table_ddl_against_model(data_db, table):
            log.debug("{}-db schema outdated, resetting".format(table.name))
            reset_blocks = True
            if engine.dialect.has_table(engine, table_name):
                table.drop(engine)

        else:
            log.debug("{}-db schema up to date".format(table.name))

    data_base.metadata.create_all(engine)
    if reset_blocks:
        data_db().query(Block).delete()
    return data_db
Beispiel #24
0
    def track_profile(user, steamid, note=None):
        """
        Add profile for User to 'Track'
        Args:
            profile: The Profile to track
            note: An optional note for user to better track a profile
        Returns:
            True if user successfully tracks profile else False
        """
        profile = Profile.get(steamid)

        if user.steam_oid:
            if profile.steamid == user.steam_oid.profile.steamid:
                return False

        profile_data = dict(x_personaname=profile.personaname,
                            x_community_banned=profile.community_banned,
                            x_days_since_last_ban=profile.days_since_last_ban,
                            x_economy_ban=profile.economy_ban,
                            x_num_game_bans=profile.num_game_bans,
                            x_num_vac_bans=profile.num_vac_bans,
                            x_vac_banned=profile.vac_banned)
        tracking = Tracking(note=note, profile=profile, **profile_data)
        try:
            user.tracking.append(tracking)
            db.session.add(user)
            db.session.commit()
            return True
        except IntegrityError:
            return False
Beispiel #25
0
def register_user(registration_data) -> User:
    registration_data = dict(registration_data)
    user = User(
        login=registration_data['login']
    )
    user.set_password(registration_data['password'])
    del registration_data['login']
    del registration_data['password']
    profile = Profile(user=user, **registration_data)
    user.save()
    try:
        profile.save()
    except:
        user.delete()
        raise
    return user
Beispiel #26
0
def is_first_start(profile_db):
    from app.models.profile import Profile
    """Check if the applications needs to be configured"""
    if not Profile.get_active(profile_db):
        return True
    else:
        return False
Beispiel #27
0
def edit(username):
    form = EditProfileForm(request.form)
    user = User.query.filter_by(username=username).first()
    if request.method == 'POST' and form.validate():
        profile = Profile(location=form.location.data)
        db.session.add(profile)
        db.session.commit()
    return render_template('patient/edit.html', users=user, form=form)
Beispiel #28
0
def get_profile_by_user_id(id: DocId) -> Union[Profile, None]:
    """
    Получить профиль (Profile), привязанный к пользователю
    :param id: Идентификатор пользователя
    :return: Профиль (или None)
    """
    for c_user in Profile.objects(user=id):
        return c_user
Beispiel #29
0
def accomplish_adventure(action, profile, adventure):
    node = Profile.objects(pk=profile).first()
    adventure = Adventure.objects(pk=adventure).first()
    if action == 'add':
        RelationShips.accomplish(node, adventure)
    else:
        RelationShips.unaccomplish(node, adventure)
    return node
Beispiel #30
0
def edit_profile_preference(profile, data):
    node = Profile.objects(pk=profile).first()
    email_enabled = data.get('email_enabled', True)
    email_frequency = data.get('email_frequency', 'daily')
    node.email_enabled = email_enabled
    node.email_frequency = email_frequency
    node.save()
    return node
Beispiel #31
0
def wish_list_adventure(action, profile, adventure):
    node = Profile.objects(pk=profile).first()
    adventure = Adventure.objects(pk=adventure).first()
    if action == 'add':
        RelationShips.wishlist(node, adventure)
    else:
        RelationShips.unwishlist(node, adventure)
    return node
Beispiel #32
0
def favorite_activity(action, profile, activity):
    node = Profile.objects(pk=profile).first()
    activity = Activity.objects(pk=activity).first()
    if (action == 'add'):
        RelationShips.favorite(node, activity)
    else:
        RelationShips.un_favorite(node, activity)
    return node
Beispiel #33
0
def get_available_profiles(user: User) -> List[Profile]:
    profile = get_profile_by_user_id(user.id)
    res = []
    if profile.type == 'Администратор' or profile.type == 'Менеджер':
        for prof in Profile.objects():
            res.append(prof)
    else:
        res = [profile]
    return res
Beispiel #34
0
 def push_content_to_stream(cls, content):
     activity = ActivityStream(profile=content.author, action='added content', object=content, view_html='', view_text='', view_json='')
     activity.save()
     if content.author:
         author = Profile.objects(pk=content.author.id).first()
         author.increment_public_activity_count()
         for u in author.followers:
             u.increment_public_activity_count()
     return activity
Beispiel #35
0
def init_profile_db():
    fp = app.PROFILE_DB_FILEPATH
    log.debug('init profile db at {}'.format(fp))
    engine = sqlalchemy.create_engine('sqlite:///{}'.format(fp))

    profile_db.configure(bind=engine)
    engine.execute("PRAGMA journal_mode=WAL")

    log.debug("check {}-db schema".format(Profile.__table__.name))
    backup_profiles = []
    if not check_table_ddl_against_model(profile_db, Profile.__table__):
        log.debug("{}-db schema outdated, resetting".format(
            Profile.__table__.name))
        if engine.dialect.has_table(engine, "profiles"):
            for profile in profile_db().execute(
                    'SELECT * FROM profiles').fetchall():
                backup_profiles.append(profile)

            Profile.__table__.drop(engine)
        elif engine.dialect.has_table(engine, "profile"):
            for profile in profile_db().execute(
                    'SELECT * FROM profile').fetchall():
                backup_profiles.append(profile)
    else:
        log.debug("{}-db schema up to date".format(Profile.__table__.name))

    # create the database
    Profile_Base.metadata.create_all(engine)

    with profile_session_scope() as session:
        for profile in backup_profiles:
            session.add(
                Profile(
                    name=profile.name if 'name' in profile else '',
                    rpc_host=profile.rpc_host
                    if 'rpc_host' in profile else '127.0.0.1',
                    rpc_port=profile.rpc_port
                    if 'rpc_port' in profile else '9719',
                    rpc_user=profile.rpc_user
                    if 'rpc_user' in profile else 'multichainrpc',
                    rpc_password=profile.rpc_password
                    if 'rpc_password' in profile else '',
                    rpc_use_ssl=profile.rpc_use_ssl
                    if 'rpc_use_ssl' in profile else 0,
                    manage_node=profile.manage_node
                    if 'manage_node' in profile else 1,
                    exit_on_close=profile.exit_on_close
                    if 'exit_on_close' in profile else 1,
                    active=profile.active if 'active' in profile else 0,
                    alias=profile.alias if 'alias' in profile else '',
                    address=profile.address if 'address' in profile else '',
                    balance=profile.balance if 'balance' in profile else 0,
                    is_admin=profile.is_admin if 'is_admin' in profile else 0,
                    is_miner=profile.is_miner if 'is_miner' in profile else 0,
                ))

    return profile_db
Beispiel #36
0
def change_password(profile, data):
    node = Profile.objects(pk=profile).first()
    old = hashlib.md5(data.get('old')).hexdigest()
    new = data.get('new')
    if (old != node.passwd):
        raise Exception("Invalid Password")
    node.password = new
    node.save()
    return node
Beispiel #37
0
    def push_vote_to_stream(cls, post_vote):
        activity = ActivityStream(profile=post_vote.voter, action= 'voted on', object=post_vote.post, view_html='', view_text='', view_json='')
        activity.save()
        if post_vote.voter:
            voter = Profile.objects(pk=post_vote.voter.id).first()
            voter.increment_public_activity_count()
            for u in voter.followers:
                u.increment_public_activity_count()

        if post_vote.post.author is not None:
            post = post_vote.post
            activity2 = ActivityStream(profile=post.author, action='received vote on', object=post, view_html='', view_text='', view_json='')
            activity2.save()
            if post.author:
                author = Profile.objects(pk=post.author.id).first()
                author.increment_public_activity_count()

        return activity
Beispiel #38
0
def before_request():
    userid = session.get('user', None)
    if userid is None or len(userid) == 0:
        g.user = None
    else:
        user = Profile.objects(pk=userid).first()
        if user:
            g.user = user
        else:
            g.user = None
Beispiel #39
0
def profile_view(steamid):
    profile = None
    tracking = None
    if current_user.is_authenticated:
        tracking = current_user.get_tracking([steamid])
        if tracking:
            tracking = tracking[0]  # user.get_tracking returns list
    if is_steamid64(str(steamid)):
        profile = Profile.get_profile(steamid)
    return render_template('profile.j2', profile=profile, tracking=tracking)
Beispiel #40
0
    def push_post_to_stream(cls, post, type):
        activity = ActivityStream(profile=post.author, action=type, object=post, view_html='', view_text='', view_json='')
        activity.save()
        if post.author:
            author = Profile.objects(pk=post.author.id).first()
            author.increment_public_activity_count()
            if type == 'stream':
                for u in author.followers:
                    u.increment_public_activity_count()

        if post.parent is not None and isinstance(post.parent, Content):
            content = post.parent
            activity2 = ActivityStream(profile=content.author, action='received comment on', object=content, view_html='', view_text='', view_json='')
            activity2.save()
            if content.author:
                author = Profile.objects(pk=content.author.id).first()
                author.increment_public_activity_count()

        return activity
Beispiel #41
0
def book_trip(action, name, email, phone, message, trip):
    node = Profile.objects(email__iexact=email).first()
    if not node:
        type = ProfileType.objects(name__iexact='Subscription Only').first()
        node = Profile(name=name, email=email, phone=phone, type=[type]).save()
    trip = Trip.objects(pk=trip).first()
    if not node or not trip:
        raise Exception('Invalid profile or event')
    trip.add_enquiry(node, message)
    return node
Beispiel #42
0
def edit_role(action, profile, role):
    node = Profile.objects(pk=profile).first()
    if action == 'add':
        node.roles.append(role)
    elif action == 'remove':
        node.roles.remove(role)
    else:
        raise Exception("Invalid action")
    node.save()
    return node
Beispiel #43
0
def edit_type(action, profile, type):
    node = Profile.objects(pk=profile).first()
    type = ProfileType.objects(name__iexact=type).first()
    if action == 'add':
        node.type.append(type)
    elif action == 'remove':
        node.type.remove(type)
    else:
        raise Exception("Invalid action")
    node.save()
    return node
Beispiel #44
0
    def test_valid_token(self):
        """
        WHEN a user changes his or her password with a valid token
        THEN the new password is set
        """
        token = self.a_user.profile.generate_token(TokenType.RESET)
        is_password_changed = Profile.reset_password(token, OTHER_PASSWORD)

        user = User.objects.get(pk=self.a_user.pk)
        self.assertTrue(is_password_changed)
        self.assertTrue(user.check_password(OTHER_PASSWORD))
Beispiel #45
0
def join_trip(action, profile, trip):
    node = Profile.objects(pk=profile).first()
    trip = Trip.objects(pk=trip).first()
    if not node or not trip:
        raise Exception('Invalid profile or event')
    if action == 'add':
        RelationShips.join(node, trip)
    elif action == 'remove':
        RelationShips.unjoin(node, trip)
    else:
        raise Exception("Invalid action")
    return node
Beispiel #46
0
    def test_expired_token(self):
        """
        WHEN a user changes his or her password with an invalid token
        THEN the password remains the same
        """
        token = self.a_user.profile.generate_token(TokenType.RESET, 0.5)
        time.sleep(1)
        is_password_changed = Profile.reset_password(token, OTHER_PASSWORD)

        user = User.objects.get(pk=self.a_user.pk)
        self.assertFalse(is_password_changed)
        self.assertFalse(user.check_password(OTHER_PASSWORD))
Beispiel #47
0
def join_event(action, profile, event):
    node = Profile.objects(pk=profile).first()
    event = Event.objects(pk=event).first()
    if not node or not event:
        raise Exception('Invalid profile or event')
    if action == 'join':
        RelationShips.join(node, event)
    elif action == 'unjoin':
        RelationShips.unjoin(node, event)
    else:
        raise Exception("Invalid action")
    return node
Beispiel #48
0
    def test_invalid_token(self):
        """
        GIVEN an invalid password reset token
        WHEN resetting the user's password
        THEN the second user's password remains the same
        """
        token = self.a_user.profile.generate_token(TokenType.RESET) + "a"

        is_password_changed = Profile.reset_password(token, OTHER_PASSWORD)

        user = User.objects.get(pk=self.a_user.pk)
        self.assertFalse(is_password_changed)
        self.assertFalse(user.check_password(OTHER_PASSWORD))
Beispiel #49
0
def reset_activity_count(profile, action):
    if not profile:
        from flask import g
        profile = g.user.id
    node = Profile.objects(pk=profile).first()
    if action == 'public':
        node.public_activity_count = 0
    elif action == 'private':
        node.private_activity_count = 0
    else:
        raise Exception('Invalid action')
    node.save()
    return node
Beispiel #50
0
def social_login():
    if request.method != 'POST':
        return render_template('/generic/main/login.html')
    name = request.form['name']
    email = request.form['email']
    profile = Profile.objects(email__iexact=email).first()

    if profile is None or profile.id is None:
        types = [ProfileType.objects(name__icontains='enthusiast').first()]
        assert len(types) > 0
        profile = Profile(name=name, email=email, is_verified=True, roles=['Basic User'], type=types)
        profile.password = ''
        profile.save()

    if profile.is_social_login is None or not profile.is_social_login:
        profile.is_social_login = True
        profile.save()


    if profile.is_social_login and profile.id and hasattr(profile, 'uploaded_image_cover') and not profile.uploaded_image_cover:
        img_uploaded = request.form['file']
        if img_uploaded and len(img_uploaded) > 0:
            try:
                data = img_uploaded
                data = data[data.index(','):]
                s = StringIO(decodestring(data))
                img = Image.open(s)
                buffer = StringIO()
                img.save(buffer, img.format)
                buffer.seek(0)
                profile.cover_image.replace(buffer)
                profile.save()
                path = os.getcwd() + '/app/assets/' + profile.path_cover_image if profile.path_cover_image and len(profile.path_cover_image) > 0 else 'some-non-existent-path'
                if os.path.exists(path):
                    os.remove(path)

            except Exception, e:
                raise e
Beispiel #51
0
def register_business_profile(data):
    name, email= data['name'], data['email']
    _type, about, website, google_plus, linked_in, facebook = data['type'], data['about'], data['website'], data['google_plus'], data['linked_in'], data['facebook']
    logged_in_user = data['logged_in']

    user = Profile.objects(pk=logged_in_user).first()
    if not user:
        raise Exception("Not logged in")



    subscription_type = ProfileType.objects(name__icontains='subscription').first()
    if Profile.objects(email__iexact=email, type__nin=[str(subscription_type.id)]).first():
        raise Exception('Profile already exists')

    type = ProfileType.objects(name__iexact=_type).first()
    profile = Profile.objects(email__iexact=email).first()
    if not profile:
        profile = Profile.create(name=name, email=email, type=[type], roles=['Basic User'], about=about if about else '', website=website if website else '',
                                 facebook=facebook if facebook else '', linked_in=linked_in if linked_in else '', google_plus=google_plus if google_plus else '')
    else:
        raise Exception('Profile already added by someone')
    profile.password = '******'
    profile.is_business_profile = True
    profile.admin_approved = False
    profile.managed_by.append(user)
    profile.save()

    if profile and profile.id:
        from app.views import env
        #session['user'] = str(profile.id)
        template_path = 'notifications/successfully_registered.html'
        template = env.get_template(template_path)
        context = {}
        context['user']  = profile
        html = template.render(**context)
        send_single_email("[Fitrangi] Successfully registered", to_list=[profile.email], data=html)
    return profile
Beispiel #52
0
def seed():
    import json
    from app.models.profile import Profile
    from app.models.position import Position

    profiles = []
    with open('seed_data.json') as data_file:
        data = json.load(data_file)
        profiles = data['profiles']

    for profile in profiles:
        # create profile if not exists
        query = Profile.select().where(Profile.id == profile['id'])
        if query.exists() == True:
            continue
        p = Profile.create(**profile)
        # create positions
        positions = profile.get('positions')
        if positions == None or len(positions) == 0:
            continue
        for position in positions:
            data = {"profile": p, "title": position}
            Position.create(**data)
Beispiel #53
0
def password_reset_view(request, token):
    if request.method == "POST":
        data = request.POST.copy()
        form = ResetPasswordForm(data=data)
        if form.is_valid():
            if Profile.reset_password(token, data["password1"]):
                messages.info(request, "Your password has been updated.")
                return redirect(reverse("app:auth.login"))
            else:
                return redirect(reverse("app:main.index"))

    form = ResetPasswordForm()
    args = dict(title="Reset Your Password", hide_nav=True, form=form)
    return render(request, "auth/reset_password.html", args)
Beispiel #54
0
    def post(self):
        logger.log_python_api_post(MeResource.api_url)
        # parser = reqparse.RequestParser()
        # parser.add_argument('phone_number', required=True, help="Phone number cannot be blank!")
        # args = parser.parse_args()
        # phone_number = args['phone_number']
        skills = request.json['skills']
        phone_number = request.json['phone_number']

        profile, created = Profile.get_or_create(id=current_user.id)
        profile.skills = skills
        profile.phone_number = phone_number
        profile.save()

        return model_to_dict(profile)
Beispiel #55
0
    def get(self):
        logger.log_python_api_get(ProfilesResource.api_url)
        skills = request.args.get('skills')
        role = request.args.get('role')
        location = request.args.get('location')
        company = request.args.get('company')
        name = request.args.get('name')
        hireable = request.args.get('hireable')

        clauses = []
        if skills:
            skills_clauses = [
                Profile.skills.contains(skill)
                for skill in safe_split_strip_remove_empty(skills)
            ]
            if any(skills_clauses):
                clauses.append(reduce(operator.or_, skills_clauses))
        if role:
            subquery = Position.select(Param('1')).where(
                Position.profile == Profile.id, Position.title.contains(role))
            clauses.append(Clause(SQL('EXISTS'), subquery))
        if company:
            clauses.append(Profile.company.contains(company))
        if location:
            clauses.append(Profile.location.contains(location))
        if name:
            clauses.append(Profile.name.contains(name))
        if hireable:
            hireable_clauses = []
            for value in hireable.split(','):
                value = value.strip().lower()
                if value == 'yes':
                    hireable_clauses.append(Profile.hireable == True)
                elif value == 'no':
                    hireable_clauses.append(Profile.hireable == False)
                elif value == 'unknown':
                    hireable_clauses.append(Profile.hireable >> None)
            if any(hireable_clauses):
                clauses.append(reduce(operator.or_, hireable_clauses))

        profiles = Profile.select()
        if any(clauses):
            profiles = profiles.where(reduce(operator.and_, clauses))
        positions = Position.select()
        profiles_with_positions = prefetch(profiles, positions)

        return list(
            map(lambda p: self.profile_to_dict(p), profiles_with_positions))
Beispiel #56
0
def get_available_profiles(user: User) -> List[Profile]:
    """
    Получить список профилей, к чьим планам данный пользователь имеет доступ
    Администраторы и Менеджеры имеют доступ к планам всех пользователей, Преподаватели -
    только к своим
    :param user: Пользователь
    :return:
    """
    profile = get_profile_by_user_id(user.id)
    res = []
    if profile.type == 'Администратор' or profile.type == 'Менеджер':
        for prof in Profile.objects():
            res.append(prof)
    else:
        res = [profile]
    return res
Beispiel #57
0
def search_view():
    if request.method == 'POST':
        """
        Get all steamids and redirect to a GET request
        where they can be retrieved and presented to user
        """
        steamid_input = request.form.get('steamids')
        steamids = extract_steamids(steamid_input)
        steamids_query = ','.join(steamids)
        url = url_for('search.search_view') + '?steamids=' + steamids_query
        return redirect(url)

    if request.method == 'GET':
        steamids = request.args.get('steamids')
        profiles = None
        tracking = {}
        if steamids:
            steamids = steamids.split(',')
            steamids = list(filter(is_steamid64, steamids))
            profiles = Profile.get_profiles(steamids)

            # if the user is logged in we need to check if they are
            # already tracking any profiles
            if current_user.is_authenticated:
                currently_tracking = current_user.get_tracking(steamids)
                if currently_tracking:
                    tracking = {
                        x.steam_profile.steamid: x
                        for x in currently_tracking
                    }
            # if only 1 steamid in search then redirect to profile page
            if len(profiles) == 1:
                return redirect(
                    url_for('profile.profile_view',
                            steamid=profiles[0].steamid))
        return render_template('search.j2',
                               profiles=profiles,
                               tracking=tracking)
Beispiel #58
0
 def get(self, id):
     logger.log_python_api_get(ProfileResource.api_url)
     profile = Profile.get(id=id)
     d = model_to_dict(profile)
     d['positions'] = [p.title for p in profile.positions]
     return d
Beispiel #59
0
 def get(self):
     logger.log_python_api_get(MeResource.api_url)
     profile, created = Profile.get_or_create(id=current_user.id)
     profile_dict = model_to_dict(profile)
     profile_dict["positions"] = [p.title for p in profile.positions]
     return profile_dict
Beispiel #60
0
def toSummary(summary):
    userProfile, created = Profile.get_or_create(id=summary["from"])
    return MessageSummary(summary["from"], userProfile.name,
                          summary["unread_messages_count"])