Exemplo n.º 1
0
def get_user_profile():
    try:
        payload = get_payload()
    except jwt.exceptions.PyJWTError:
        # TODO: explain the error more obviously
        return format_response(data=None,
                               success=False,
                               message=_('You are not authorized'),
                               status_code=401)

    user_id = payload['id']
    connect_db()
    user = g.db.execute(sa.select([User
                                   ]).where(User.c.id == user_id)).fetchone()

    result = {
        'username':
        user.username,
        'name':
        user.name,
        'email':
        user.email,
        'referral_code':
        user.referral_code,
        'registered_at':
        user.created.strftime('%Y-%m-%d %H:%M:%S')
        if user.created is not None else None
    }

    return format_response(data=result)
Exemplo n.º 2
0
def update_user_profile():
    try:
        payload = get_payload()
    except jwt.exceptions.PyJWTError:
        # TODO: explain the error more obviously
        return format_response(data=None,
                               success=False,
                               message=_('You are not authorized'),
                               status_code=401)

    user_id = payload['id']
    connect_db()
    user = g.db.execute(sa.select([User
                                   ]).where(User.c.id == user_id)).fetchone()

    form = ProfileForm(context={'user': user}, partial=True)
    data = form.load(request.json or {})

    values_to_update = {'modified': sa.func.NOW()}
    for key in data:
        if key in ['username', 'name', 'email']:
            values_to_update.update({key: data[key]})
        elif key == 'password':
            values_to_update.update(
                {'password': generate_password_hash(data[key])})

    transaction = g.db.begin()
    g.db.execute(
        User.update().values(**values_to_update).where(User.c.id == user_id))
    transaction.commit()

    return format_response(data=None)
Exemplo n.º 3
0
    def validate_referral_code(self, referral_code):
        connect_db()
        check = g.db.execute(
            sa.select([
                User.c.id
            ]).where(User.c.referral_code == referral_code)).scalar()

        if not check:
            raise ValidationError(_('Invalid referral code'))
Exemplo n.º 4
0
    def validate_email(self, email):
        connect_db()
        check = g.db.execute(
            sa.select([User.c.id]).where(User.c.email == email)).scalar()

        if check:
            raise ValidationError(
                _('Email %(email)s already exists. Please input another email.',
                  email=email))
Exemplo n.º 5
0
    def validate_username(self, username):
        connect_db()
        check = g.db.execute(
            sa.select([User.c.id
                       ]).where(User.c.username == username)).scalar()

        if check:
            raise ValidationError(
                _('Username %(username)s already exists. Please input another username.',
                  username=username))
Exemplo n.º 6
0
    def validate_username(self, data, **kwargs):
        connect_db()
        user = g.db.execute(
            sa.select(
                [User]).where(User.c.username == data['username'])).fetchone()

        if not user:
            raise ValidationError(_('Invalid username'), 'username')

        if not check_password_hash(user.password, data['password']):
            raise ValidationError(_('Invalid password'), 'password')

        self.context['user'] = user
Exemplo n.º 7
0
    def validate_email(self, email):
        user = self.context.get('user')
        connect_db()
        check = g.db.execute(
            sa.select([User.c.id]).where(
                sa.and_(
                    User.c.email == email,
                    User.c.id != user.id
                )
            )
        ).scalar()

        if check:
            raise ValidationError(_('Email %(email)s already exists. Please input another email.', email=email))
Exemplo n.º 8
0
    def validate_username(self, username):
        user = self.context.get('user')
        connect_db()
        check = g.db.execute(
            sa.select([User.c.id]).where(
                sa.and_(
                    User.c.username == username,
                    User.c.id != user.id
                )
            )
        ).scalar()

        if check:
            raise ValidationError(_('Username %(username)s already exists. Please input another username.', username=username))
Exemplo n.º 9
0
def get_user_list():
    # TODO: pagination
    try:
        get_payload()
    except jwt.exceptions.PyJWTError:
        # TODO: explain the error more obviously
        return format_response(data=None, success=False, message=_('You are not authorized'), status_code=401)
    
    redis = connect_redis()
    q = ''
    if request.method == 'POST':
        try:
            params = request.json or {}
            q = params.get('q', '')
        except:
            # TODO: except more correctly
            q = ''
    redis_key = f'user-list:q-{q}'
    if redis.exists(redis_key):
        result = redis.get(redis_key)
    else:
        connect_db()
        sql = sa.select([User]).order_by(sa.desc(User.c.created))
        if q:
            sql = sql.where(
                sa.or_(
                    User.c.name.like(f'%%{q}%%'),
                    User.c.username.like(f'%%{q}%%')
                )
                
            )
        
        user_list = g.db.execute(sql).fetchall()

        result = []
        for user in user_list:
            result.append({
                'id': user.id,
                'username': user.username,
                'name': user.name,
                'registered_at': user.created.strftime('%Y-%m-%d %H:M:S') if user.created is None else None
            })
        
        redis.set(redis_key, result)
    
    return format_response(data=result)
Exemplo n.º 10
0
def get_user_detail(username):
    try:
        get_payload()
    except jwt.exceptions.PyJWTError:
        # TODO: explain the error more obviously
        return format_response(data=None,
                               success=False,
                               message=_('You are not authorized'),
                               status_code=401)

    # TODO: redis
    redis = connect_redis()
    redis_key = f'user-detail-{username}'
    if redis.exists(redis_key):
        result = redis.get(redis_key)
    else:
        connect_db()
        user = g.db.execute(
            sa.select([User]).where(User.c.username == username)).fetchone()

        if not user:
            return format_response(data=None,
                                   success=False,
                                   message=_('User not found'),
                                   status_code=404)

        result = {
            'username':
            user.username,
            'name':
            user.name,
            'email':
            user.email,
            # 'referral_code': user.referral_code,
            'registered_at':
            user.created.strftime('%Y-%m-%d %H:%M:%S') if user.created
            is not None else None  # TODO: may other users see this?
        }

        redis.set(redis_key, result)

    return format_response(data=result)
Exemplo n.º 11
0
def register():
    form = RegistrationForm()
    data = form.load(auto_trim(request.json or {}))

    connect_db()
    transaction = g.db.begin()
    referral_code = generate_referrral_code()
    password = generate_password_hash(data['password'])
    user_id = g.db.execute(User.insert().values(
        username=data['username'],
        password=password,
        name=data['name'],
        email=data['email'],
        referral_code=referral_code).returning(User.c.id)).scalar()

    # save referral code
    # get user_id by referral code
    referral_code = data.get('referral_code')
    if referral_code:
        redeemed_user_id = g.db.execute(
            sa.select([
                User.c.id
            ]).where(User.c.referral_code == data['referral_code'])).scalar()

        g.db.execute(UserHasReferralCodes.insert().values(
            redeemed_referral_code=data['referral_code'],
            redeemed_user_id=redeemed_user_id,
            redeemer_user_id=user_id))

    transaction.commit()

    result = {
        'id': user_id,
        'username': data['username'],
        'name': data['name'],
        'email': data['email'],
        'referral_code': referral_code
    }

    return format_response(data=result)
Exemplo n.º 12
0
    def validate_referral_code(self, referral_code):
        # check if user has redeemed referral code before
        user_id = self.context.get('user_id')
        uhrc = UserHasReferralCodes.alias('uhrc')
        connect_db()
        user_has_redeemed = g.db.execute(
            sa.select([uhrc.c.id]).where(uhrc.c.redeemer_user_id == user_id)
        ).fetchone()

        if user_has_redeemed:
            raise ValidationError(_('You already redeemed referral code'))

        # check the owner of referral code
        user_referral_code = g.db.execute(
            sa.select([User.c.id]).where(User.c.referral_code == referral_code)
        ).scalar()

        if not user_referral_code:
            raise ValidationError(_('Invalid referral code'))

        if user_id == user_referral_code:
            raise ValidationError(_('You cannot redeem your own referral code'))

        self.context['user_referral_code'] = user_referral_code
Exemplo n.º 13
0
#! /usr/bin/env python3

from app import app
import sys

if __name__ == '__main__':
    args = sys.argv
    if len(args) > 1:
        if args[1] == 'create-table':
            from app.models import meta_db
            from app.utils.connect_db import connect_db
            from flask import g
            with app.app_context():
                connect_db()
                meta_db.create_all(g.db)
    else:
        app.run(host='0.0.0.0', port=app.config['PORT'])