Ejemplo n.º 1
0
    def delete(self, card_id):
        claims = get_jwt_claims()

        # Check permission of the card
        try:
            result = app.database.execute(
                text('''
                SELECT count(card_id) AS counts, user_id
                FROM card
                WHERE card_id= :card_id;
            '''), {
                    'card_id': card_id
                }).fetchone()
            if int(result['counts']) == 0:
                return error_response(404, '존재하지 않는 결제 수단입니다.')
            if str(result['user_id']) != str(claims['id']):
                return error_response(403, '해당 결제 수단에 접근할 권한이 없습니다.')
        except Exception as exc:
            return error_response(500, str(exc))

        # Querying
        try:
            app.database.execute(
                text('''
                DELETE FROM card WHERE card_id= :card_id;
            '''), {'card_id': card_id})
        except Exception as exc:
            return error_response(500, str(exc))

        return ok_response(None)
Ejemplo n.º 2
0
    def post(self):
        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        # Handle body parameters
        try:
            pw = request.json.get('pw', None)
            email = request.json.get('email', None)
            name = request.json.get('name', None)
            if (not pw) or (not email) or (not name):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))

        # Password Encryption
        hashed = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())

        # Querying
        try:
            app.database.execute(
                text('''
                INSERT INTO user (user_pw, user_name, user_email) 
                VALUES (:pw, :name, :email)
            '''), {
                    'name': name,
                    'email': email,
                    'pw': hashed
                })
        except Exception as exc:
            return error_response(500, str(exc))

        return ok_response(None)
Ejemplo n.º 3
0
    def post(self):
        claims = get_jwt_claims()

        try:
            title = request.json.get('title', None)
            content = request.json.get('content', None)
            if (not title) or (not content):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'Json 파싱 에러가 발생했습니다 : ' + str(exc))

        user_id = claims['id']
        
        try:
            app.database.execute(text('''
                INSERT INTO posts (title, content, author_id)
                VALUES (:title, :content, :author_id) 
            '''), {
                'title': title,
                'content': content,
                'author_id': user_id
            })
        except Exception as exc:
            return error_response(500, str(exc))
        
        return ok_response(None)
Ejemplo n.º 4
0
    def post(self):

        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        try:
            user_id = request.json.get('id', None)
            password = request.json.get('password', None)
            name = request.json.get('name', None)
            if (not user_id) or (not password) or (not name):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))

        hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

        try:
            app.database.execute(
                text('''
                INSERT INTO users (id, password, name)
                VALUES (:id, :password, :name)
            '''), {
                    'id': user_id,
                    'password': hashed,
                    'name': name
                })
        except Exception as exc:
            return error_response(500, str(exc))

        return ok_response(None)
Ejemplo n.º 5
0
    def put(self):
        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        claims = get_jwt_claims()

        # Handle body parameters
        try:
            face = request.json.get('face', None)
            if (not face):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))

        # Send to websocket server
        payload = json.dumps({
            'action': 'register',
            'user_id': claims['id'],
            'image': face
        })
        ws_url = 'ws://{}:{}'.format(
            app.config['WEBSOCKET_SERVER']['server_name'],
            app.config['WEBSOCKET_SERVER']['port'])
        ws = create_connection(ws_url)
        ws.send(payload)
        resp = ws.recv()
        ws.close()

        return ok_response(resp)
Ejemplo n.º 6
0
    def get(self):
        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        # Handle body parameters
        try:
            email = request.json.get('email', None)
            if (not email):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))

        # Querying
        try:
            result = app.database.execute(
                text('''
                SELECT count(user_email) AS count
                FROM user WHERE user_email= :email
            '''), {
                    'email': email
                }).fetchone()
        except Exception as exc:
            return error_response(500, str(exc))

        if result['count'] == 0:
            return ok_response({'available': True})
        else:
            return ok_response({'available': False})
Ejemplo n.º 7
0
    def get(self):
        claims = get_jwt_claims()

        # Querying
        try:
            result = app.database.execute(
                text('''
                SELECT card_id, card_number, card_network, card_issuer, registered_at
                FROM card WHERE user_id= :id;
            '''), {
                    'id': claims['id']
                }).fetchall()
        except Exception as exc:
            return error_response(500, str(exc))

        cards = []
        for row in result:
            cards.append({
                'card_id': row['card_id'],
                'card_number': row['card_number'],
                'card_network': row['card_network'],
                'card_issuer': row['card_issuer'],
                'registered_at': str(row['registered_at'])
            })
        return ok_response({'cards_count': len(cards), 'cards': cards})
Ejemplo n.º 8
0
    def get(self):
        claims = get_jwt_claims()

        # Querying
        try:
            result = app.database.execute(
                text('''
                SELECT t.transaction_id, t.transaction_type, t.user_id, t.price, t.location_id, t.timestamp, u.user_email, u.user_name
                FROM transaction AS t, user AS u
                WHERE t.user_id= u.user_id
                    AND t.user_id= :id
                ORDER BY transaction_id DESC;
            '''), {
                    'id': claims['id']
                }).fetchall()
        except Exception as exc:
            return error_response(500, str(exc))

        transactions = []
        for row in result:
            transactions.append({
                'transaction_id': row['transaction_id'],
                'transaction_type': row['transaction_type'],
                'user_id': row['user_id'],
                'user_name': row['user_name'],
                'user_email': row['user_email'],
                'price': row['price'],
                'location_id': row['location_id'],
                'timestamp': str(row['timestamp'])
            })

        return ok_response({
            'transactions_count': len(transactions),
            'transactions': transactions
        })
Ejemplo n.º 9
0
    def get(self):
        claims = get_jwt_claims()

        try:
            result = app.database.execute(text('''
                SELECT id, title, content, published_at, author_id 
                FROM posts
            ''')).fetchall()
        except Exception as exc:
            return error_response(500, str(exc))
        
        
        posts = []
        for row in result:  
            posts.append({
                'id': row['id'],
                'title': row['title'],
                'content': row['content'],
                'published_at': row['published_at'],
                'author_id': row['author_id']
            })

        return ok_response({
            'posts_count': len(posts),
            'posts': posts 
        })


        return ok_response(None)
Ejemplo n.º 10
0
    def get(self):
        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        claims = get_jwt_claims()

        # Querying
        try:
            result = app.database.execute(text('''
                SELECT user_credit
                FROM user WHERE user_id= :id;
            '''),{
                'id': claims['id']
            }).fetchone()
        except Exception as exc:
            return error_response(500, str(exc))
        
        return ok_response({'remaining_credit': int(result['user_credit'])})
Ejemplo n.º 11
0
    def post(self):
        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        claims = get_jwt_claims()

        # Handle body parameters
        try:
            card_id = request.json.get('card_id', None)
            amount = request.json.get('amount', None)
            if (not card_id) or (not amount):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))
        
        if amount < 1000 or amount > 1000000:
            return error_response(400, '1회 충전 한도는 최소 1,000원, 최대 1,000,000원입니다.')

        # Check permission of the card
        try:
            result = app.database.execute(text('''
                SELECT count(card_id) AS counts
                FROM user AS u, card AS c
                WHERE c.user_id=u.user_id
                    AND u.user_id= :id
                    AND c.card_id= :card_id;
            '''), {
                'id': claims['id'],
                'card_id': card_id
            }).fetchone()
            if int(result['counts']) == 0:
                return error_response(403, '해당 결제 수단에 대한 접근 권한이 부족합니다.')
        except Exception as exc:
            return error_response(500, str(exc))

        # Querying
        try:
            app.database.execute(text('''
                UPDATE user SET user_credit=user_credit+ :amount WHERE user_id= :id;
            '''), {
                'id': claims['id'],
                'amount': amount
            })
        except Exception as exc:
            return error_response(500, str(exc))

        # Logging
        app.database.execute(text('''
            INSERT INTO
                transaction (user_id, price, transaction_type, location_id)
                VALUES (:user_id, :price, :type, :location_id);
        '''), {
            'user_id': claims['id'],
            'price': amount,
            'type': 'charge',
            'location_id': 0
        })

        return ok_response(None)
Ejemplo n.º 12
0
    def post(self):
        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        # Handle body parameters
        try:
            pw = request.json.get('pw', None)
            email = request.json.get('email', None)
            if (not pw) or (not email):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))

        # Querying
        try:
            result = app.database.execute(text('''
                SELECT count(user_email) AS counts, user_name, user_email, user_pw, user_id
                FROM user WHERE user_email= :email
            '''),{
                'email' : email,
            }).fetchone()
            if int(result['counts']) == 0:
                return error_response(401, '이메일이 잘못되었습니다.')
        except Exception as exc:
            return error_response(500, str(exc))

        # Compare the password
        try:
            if not bcrypt.checkpw(pw.encode('utf-8'), result['user_pw'].encode('utf-8')):
                return error_response(401, '비밀번호가 잘못되었습니다.')
        except Exception as exc:
            return error_response(401, '비밀번호가 잘못되었습니다 : ' + str(exc))

        user_claims = {
            'id': result['user_id'],
            'email': result['user_email'],
            'name': result['user_name']
        }
        access_token = create_access_token(
            identity=email,
            expires_delta=timedelta(hours=24),
            user_claims=user_claims
        )
        refresh_token = create_refresh_token(
            identity=email,
            user_claims=user_claims
        )

        return ok_response({
            'access_token': access_token,
            'refresh_token': refresh_token
        })

        return ok_response(None)
Ejemplo n.º 13
0
    def put(self, card_id):
        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        # Handle body parameters
        try:
            card_number = request.json.get('card_number', None)
            card_network = request.json.get('card_network', None)
            card_issuer = request.json.get('card_issuer', None)
            if (not card_number) or (not card_network) or (not card_issuer):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))

        claims = get_jwt_claims()

        # Check permission of the card
        try:
            result = app.database.execute(
                text('''
                SELECT count(card_id) AS counts, user_id
                FROM card
                WHERE card_id= :card_id;
            '''), {
                    'card_id': card_id
                }).fetchone()
            if int(result['counts']) == 0:
                return error_response(404, '존재하지 않는 결제 수단입니다.')
            if str(result['user_id']) != str(claims['id']):
                return error_response(403, '해당 결제 수단에 접근할 권한이 없습니다.')
        except Exception as exc:
            return error_response(500, str(exc))

        # Querying
        try:
            app.database.execute(
                text('''
                UPDATE card SET
                    card_number= :card_number, card_issuer= :card_issuer, card_network= :card_network
                    WHERE card_id= :card_id
            '''), {
                    'card_number': card_number,
                    'card_issuer': card_issuer,
                    'card_network': card_network,
                    'card_id': card_id
                })
        except Exception as exc:
            return error_response(500, str(exc))

        return ok_response(None)
Ejemplo n.º 14
0
    def post(self):
        print(request.data)
        if not request.is_json:
            print('json아님')
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        try:
            user_id = request.json.get('id', None)
            password = request.json.get('password', None)
            if (not user_id) or (not password):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))
        print(user_id)
        print(password)

        try:
            result = app.database.execute(
                text('''
                SELECT count(id) AS counts, id, password, name
                FROM users WHERE id = :user_id
            '''), {
                    'user_id': user_id
                }).fetchone()

            if int(result['counts']) == 0:
                return error_response(401, 'id가 잘못되었습니다.')
        except Exception as exc:
            return error_response(500, str(exc))

        print(type(result['id']), result['password'])

        try:
            if not bcrypt.checkpw(password.encode('utf-8'),
                                  result['password'].encode('utf-8')):
                return error_response(401, '비밀번호가 잘못되었습니다.')
        except Exception as exc:
            return error_response(401, '비밀번호가 잘못되었습니다 : ' + str(exc))

        user_claims = {'id': result['id'], 'name': result['name']}
        print(user_claims)
        access_token = create_access_token(identity=user_id,
                                           expires_delta=timedelta(hours=24),
                                           user_claims=user_claims)
        refresh_token = create_refresh_token(identity=user_id,
                                             user_claims=user_claims)
        return ok_response({
            'access_token': access_token,
            'refresh_token': refresh_token
        })
Ejemplo n.º 15
0
    def post(self):
        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        # Handle body parameters
        try:
            card_number = request.json.get('card_number', None)
            card_network = request.json.get('card_network', None)
            card_issuer = request.json.get('card_issuer', None)
            if (not card_number) or (not card_network) or (not card_issuer):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))

        claims = get_jwt_claims()

        # Check permission of the card
        try:
            result = app.database.execute(
                text('''
                SELECT count(card_id) AS counts
                FROM card
                WHERE card_number= :card_number
                    AND card_network= :card_network
                    AND card_issuer= :card_issuer
            '''), {
                    'card_number': card_number,
                    'card_issuer': card_issuer,
                    'card_network': card_network
                }).fetchone()
            if int(result['counts']) == 1:
                return error_response(500, '이미 등록된 카드 정보입니다.')
        except Exception as exc:
            return error_response(500, str(exc))

        # Querying
        try:
            app.database.execute(
                text('''
                INSERT INTO card
                    (card_number, card_network, card_issuer, user_id)
                    VALUES (:card_number, :card_network, :card_issuer, :user_id)
            '''), {
                    'card_number': card_number,
                    'card_issuer': card_issuer,
                    'card_network': card_network,
                    'user_id': claims['id']
                })
        except Exception as exc:
            return error_response(500, str(exc))

        return ok_response(None)
Ejemplo n.º 16
0
    def post(self):
        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        claims = get_jwt_claims()

        # Handle body parameters
        try:
            pw = request.json.get('pw', None)
            if (not pw):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))

        # Querying
        try:
            result = app.database.execute(text('''
                SELECT count(user_email) AS counts, user_email, user_pw
                FROM user WHERE user_id= :id
            '''),{
                'id': claims['id']
            }).fetchone()
            if int(result['counts']) == 0:
                return error_response(500, '존재하지 않는 ID입니다.')
        except Exception as exc:
            return error_response(500, str(exc))

        # Compare the password
        try:
            if not bcrypt.checkpw(pw.encode('utf-8'), result['user_pw'].encode('utf-8')):
                return error_response(401, '비밀번호가 잘못되었습니다.')
        except Exception as exc:
            return error_response(401, '비밀번호가 잘못되었습니다 : ' + str(exc))

        # Dropout the account
        result = app.database.execute(text('''
            DELETE FROM user WHERE user_email= :email
        '''), {
            'email': claims['email']
        })
        print(result)
            
        return ok_response(None)
Ejemplo n.º 17
0
    def post(self, transaction_id):
        claims = get_jwt_claims()

        # Get transaction
        try:
            result = app.database.execute(
                text('''
                SELECT count(t.transaction_id) AS counts, t.transaction_type, c.user_id, t.credit_diff, t.card_id
                FROM transaction AS t, card AS c
                WHERE t.card_id=c.card_id
                    AND t.transaction_id= :tid;
            '''), {
                    'tid': transaction_id
                }).fetchone()
            if int(result['counts']) == 0:
                return error_response(404, '해당 트랜잭션이 존재하지 않습니다.')
            if result['transaction_type'] != 'PAYMENT':
                return error_response(500, '환불이 불가능한 트랜잭션입니다.')
            if str(result['user_id']) != str(claims['id']):
                return error_response(403, '해당 트랜잭션에 접근할 권한이 부족합니다.')
        except Exception as exc:
            return error_response(500, str(exc))

        credit = abs(int(result['credit_diff']))
        card_id = int(result['card_id'])

        # Querying
        try:
            app.database.execute(
                text('''
                UPDATE transaction
                SET transaction_type= :type
                WHERE transaction_id= :tid;
            '''), {
                    'type': 'COMPLETE',
                    'tid': transaction_id
                })
        except Exception as exc:
            return error_response(500, str(exc))

        # Querying
        try:
            app.database.execute(
                text('''
                INSERT INTO
                    transaction (card_id, credit_diff, transaction_type)
                    VALUES (:card_id, :credit_diff, :new_type);
            '''), {
                    'card_id': card_id,
                    'credit_diff': credit,
                    'new_type': 'REFUND',
                })
        except Exception as exc:
            return error_response(500, str(exc))

        # Querying
        try:
            app.database.execute(
                text('''
                UPDATE user
                SET user_credit=user_credit+ :credit_diff
                WHERE user_id= :uid;
            '''), {
                    'credit_diff': credit,
                    'uid': claims['id']
                })
        except Exception as exc:
            return error_response(500, str(exc))

        return ok_response(None)
Ejemplo n.º 18
0
    def post(self):
        if not request.is_json:
            return error_response(400, 'JSON 형식으로 전달해주세요.')

        # Handle body parameters
        try:
            price = request.json.get('price', None)
            if (not price):
                return error_response(400, '파라미터가 부족합니다.')
        except Exception as exc:
            return error_response(400, 'JSON 파싱 에러가 발생했습니다 : ' + str(exc))

        claims = get_jwt_claims()

        # Querying
        try:
            result = app.database.execute(
                text('''
                SELECT u.user_credit, c.card_id
                FROM user AS u, card AS c
                WHERE u.user_id= :id
                    AND c.user_id= :id;
            '''), {
                    'id': claims['id']
                }).fetchone()
        except Exception as exc:
            return error_response(500, str(exc))

        remaining_credit = result['user_credit']
        if price <= 0:
            return error_response(400, '결제할 금액은 0원 이하가 될 수 없습니다.')
        price = abs(price)
        if price > remaining_credit:
            return error_response(500, '크레딧이 부족합니다.')

        # Querying (make transaction)
        try:
            app.database.execute(
                text('''
                INSERT INTO
                    transaction (card_id, credit_diff, transaction_type)
                    VALUES (:card_id, :credit_diff, :new_type);
            '''), {
                    'card_id': result['card_id'],
                    'credit_diff': -1 * price,
                    'new_type': 'PAYMENT',
                })
        except Exception as exc:
            return error_response(500, str(exc))

        # Querying
        try:
            app.database.execute(
                text('''
                UPDATE user
                SET user_credit = user_credit - :amount
                WHERE user_id= :id;
            '''), {
                    'id': claims['id'],
                    'amount': int(price)
                })
        except Exception as exc:
            return error_response(500, str(exc))

        return ok_response(None)