Example #1
0
    def post(self, **kwargs):
        res = {}

        u_id = kwargs.get('user_id')
        pw = request.form.get('pw')
        try:
            query = "SELECT cred_value FROM credential " \
                    "WHERE user_id=:u_id AND cred_key = 'local_pw'"
            result = g.db.execute(text(query), u_id=u_id).fetchone()

            if result is None:
                res['e_msg'] = bad_request('User invalid')
            db_pw = result[0]

            if not check_password_hash(db_pw, pw):
                res['e_msg'] = bad_request('User invalid')

            g.db.execute(text("""DELETE FROM user WHERE id=:id"""), id=u_id)
            g.db.execute(text("""DELETE FROM credential WHERE user_id=:id"""),
                         id=u_id)
            res['e_msg'] = success()

        except:
            raise Exception

        return res
Example #2
0
    def post(self, **kwarg):
        service_req = request.form.get('service_id')
        user_req = kwarg.get('user_id')
        res = {}

        # service id가 유효한지 확인
        if not g.db.execute(text('SELECT id FROM service WHERE id = :id'),
                            id=service_req).fetchone():
            res['e_msg'] = bad_request('Service id invalid')
            return res

        if False in validate_all(
                user_id=user_req,
                task_ids=required_tasks(service_req)).values():
            res['e_msg'] = bad_request(
                'Not all requited tasks are done. Please check again.')
            return res

        data = {
            'service_id': service_req,
            'user_id': user_req,
            'status': 'waiting'
        }

        try:
            # job table 업데이트
            query = text("""
            INSERT INTO job (user_id,service_id,status)
            VALUES (:user_id,:service_id,:status)
            """)
            cursor = g.db.execute(query, **data)
            id = str(cursor.lastrowid)

            # job_log table 업데이트
            query = text("""
            INSERT INTO job_log (step_id, job_id, step_co_name)
            VALUES (:step_id,:job_id,:step_co_name)""")
            g.db.execute(query, step_id=1, job_id=id, step_co_name='preparing')

            # 방금 업데이트 한 내역 불러오기
            row = g.db.execute(
                text("""SELECT id,user_id,service_id FROM job WHERE id=:id"""),
                id=id).fetchone()

        except:
            raise Exception

        res['e_msg'] = success()
        res['data'] = dict(row.items())

        return res
Example #3
0
    def get(self, **kwargs):

        # TODO: order_id and job_id need convention unity

        order_id = request.args.get('order_id')
        user_id = kwargs.get('user_id')
        res = {}

        # user_id 와 order_id가 매칭되는지 확인
        try:
            query = text("""SELECT user_id FROM job WHERE id=:id""")
            cursor = g.db.execute(query, id=order_id)
            row = dict(cursor.fetchone().items())

            if not int(row['user_id']) is int(user_id):
                res['e_msg'] = bad_request('User, order id mismatched')

            # 매칭되면 job_log 테이블에서 데이터 가져오기
            query = text(
                """SELECT job_id,step_id,step_co_name,step_class_name,e_msg,tb_msg
                            FROM job_log WHERE job_log.job_id=:order_id""")
            rows = g.db.execute(query, order_id=order_id).fetchall()

        except:
            raise Exception

        res['e_msg'] = success()
        res['data'] = [dict(i.items()) for i in rows]
        return res
Example #4
0
    def get(self, **kwargs):

        # TODO: order_id should be changed to 'report_id'
        # TODO: report template for EAV table should be made

        job_id = request.args.get('job_id')
        user_id = kwargs.get('user_id')
        res = {}

        # user_id와 order_id(report_id)가 매칭되는지 비교
        try:
            query = text("SELECT user_id FROM job WHERE id=:job_id")
            cursor = g.db.execute(query, job_id=job_id)
            row = dict(cursor.fetchone().items())

            if not int(row['user_id']) is int(user_id):
                res['e_msg'] = bad_request('User, order id mismatched')

            # 매칭되면 report 데이터 불러오기
            cursor = g.db.execute(text("SELECT big_json FROM report_json WHERE job_id=:job_id"), job_id=job_id)
            row = cursor.fetchone()

            if len(row) == 0:
                res['e_msg'] = not_found('Data not found')

        except:
            raise Exception

        res['e_msg'] = success()
        res['data'] = dict(row.items())
        return res
Example #5
0
    def get(self, **kwargs):
        res = {}
        user_id = kwargs.get('user_id')

        print "user_id : %s" % user_id

        member_type = member_type_check(user_id)
        if member_type == 'vc':
            query = text(
                "SELECT firm_name, status, runway, avg_burn_mon, cash_remaining \
                        FROM overview inner join firm_info on overview.firm_id = firm_info.firm_id"
            )
            res['data'] = g.db.execute(query).fetchall()

            if res is None or len(res['data']) <= 0:
                res['e_msg'] = not_found('Portfolio is not found')
                return res

            else:
                res['data'] = [dict(i.items()) for i in res['data']]
                res['e_msg'] = success()

        else:
            res['e_msg'] = bad_request('This page is only for VC')

        return res
Example #6
0
    def post(self):
        name = request.form.get('id')
        pw = request.form.get('pw')
        res = {}

        if len(pw) < 4:
            res['e_msg'] = bad_request('Password too short')
            return res

        try:
            db_id = g.db.execute(text('''SELECT user.id, credential.cred_value
                                         FROM credential JOIN user ON user_id=id
                                         WHERE customer_user_cred=:name AND cred_key=:key '''),
                                 name=name, key="local_pw").fetchone()
        except:
            raise Exception

        if db_id is not None:
            res['e_msg'] = bad_request('User already exists')

        else:
            try:
                g.db.execute(text("INSERT INTO user (customer_user_cred) VALUES (:name)"), name=name)
                index = g.db.execute(text("SELECT id FROM user WHERE customer_user_cred=:name"), name=name).fetchone()[0]

                g.db.execute(text("INSERT INTO credential (user_id, cred_key, cred_value) VALUES (:index, :key, :pw)"),
                             index=index, key='local_pw',
                             pw=generate_password_hash(pw))

                refresh_token = jwt_refresh_token(index, 'master', app.config['SECRET_KEY'])
                g.db.execute(text('''INSERT INTO credential (user_id, cred_key, cred_value)
                                     VALUES (:user_id, :cred_key, :cred_value)'''),
                             user_id=index, cred_key='login_refresh_token', cred_value=refresh_token)

                res['e_msg'] = success()

            except:
                raise Exception

        return res
Example #7
0
    def post(self):
        name = request.form.get('id')
        pw = request.form.get('pw')
        # name = request.args.get('id')
        # pw = request.args.get('pw')
        res = {}

        try:
            db_info = g.db.execute(text('''SELECT user.id, credential.cred_value
                                   FROM credential JOIN user ON user_id=id
                                   WHERE customer_user_cred=:name AND cred_key=:key'''),
                                   name=name, key="local_pw").fetchone()
        except:
            raise Exception

        if db_info is None:
            res['e_msg'] = bad_request('User not found')

        else:
            db_user_id = db_info[0]
            db_pw = db_info[1]

            # member type
            mem_type_query = 'SELECT member_type FROM user JOIN firm_info ON firm_info.firm_id=user.firm_id \
                       where user.customer_user_cred=:name'
            mem_type = g.db.execute(text(mem_type_query), name=name).fetchone()[0]
            res['member_type'] = mem_type


            # If user matched, get refresh token
            if check_password_hash(db_pw, pw):
                query = "SELECT cred_value FROM credential WHERE cred_key='login_refresh_token' AND user_id=:id"
                refresh_token = g.db.execute(text(query), id=db_user_id).fetchone()[0]
                res['refresh_token'] = refresh_token

                # If scope verified, get access token
                if jwt_scope_verify(str(refresh_token), app.config['SECRET_KEY']):
                    access_token = jwt_access_token(db_user_id, 31536000, app.config['SECRET_KEY'], 'master')
                    res['access_token'] = access_token

                res['e_msg'] = success()

            else:
                res['e_msg'] = unauthorized('User id or password invalid, please try again')
        return res
Example #8
0
    def get(self):
        res = {}
        service_id = request.args.get('service_id')

        try:
            info = g.db.execute(text("SELECT * FROM service WHERE id=:id"),
                                id=service_id).fetchall()

        except:
            raise Exception

        if info is None or len(info) <= 0:
            res['e_msg'] = bad_request('Service id not found')

        info = [dict(i.items()) for i in info]
        res['data'] = info[0]
        res['e_msg'] = success()

        return res
Example #9
0
    def get(self, **kwargs):
        res = {}
        pf_id = request.args.get('pf_id')
        job_id = request.args.get('job_id')

        try:
            info = g.db.execute(text("SELECT * FROM portfolios WHERE id=:id"),
                                id=pf_id).fetchall()

        except:
            raise Exception

        if info is None or len(info) <= 0:
            res['e_msg'] = bad_request('Portfolio id not found')

        info = [dict(i.items()) for i in info]
        res['data'] = info[0]
        res['e_msg'] = success()

        return res
Example #10
0
    def post(self, **kwargs):
        id, credcol = kwargs.get('user_id'), request.form.get('credcol')
        res = {}

        try:
            credcols = g.db.execute(text("SELECT DISTINCT credcol FROM mand_credcol")).fetchall()
            credcols = [i[0] for i in credcols]

            if credcol is None or credcol not in credcols:
                res['e_msg'] = bad_request('Invalid Credcol')
                return res

            rowcounted = g.db.execute(text("""DELETE FROM credential WHERE user_id=:id and cred_key=:cred_key """),
                                      id=id, cred_key=credcol).rowcount
            if rowcounted > 0:
                res['e_msg'] = success()
            else:
                res['e_msg'] = not_found('Token not found')

        except:
            raise Exception()

        return res
Example #11
0
    def get(self):
        code = request.args.get('code')
        scope = request.args.get('scope')
        try:
            referer = request.headers['referer']
            parsed_url = urlparse.urlparse(referer)
            parsed_query = urlparse.parse_qs(parsed_url.query)
        except KeyError:
            parsed_query = {}

        if 'client_info' in parsed_query:
            client_info = json.loads(base64.urlsafe_b64decode(str(parsed_query['client_info'][0])))
        else:
            client_info = json.loads(base64.urlsafe_b64decode(str(request.args.get('client_info'))))

        requester = client_info['requester']

        if requester == 'friskweb':
            data = json.loads(FriskEncrypt(app.config['SECRET_KEY']).decrypt(client_info['data']))
            u_id = data['user_id']
            redirect_uri = 'http://friskweb-react-gateway.s3-website.ap-northeast-2.amazonaws.com/#/service/{}/purchase/1'.format(
                data['service_id']
            )
            now = data['now']
        elif requester == 'friskweb_t':
            data = json.loads(FriskEncrypt(app.config['SECRET_KEY']).decrypt(client_info['data']))
            u_id = data['user_id']
            redirect_uri = 'http://www.frisk.rocks:5505/order/?service_id={}'.format(
                data['service_id']
            )
            now = data['now']

        elif requester == 'test':
            data = json.loads(FriskEncrypt(app.config['SECRET_KEY']).decrypt(client_info['data']))
            u_id = data['user_id']
            now = data['now']

        else:
            return {'e_msg': bad_request('Cannot verify the request')}

        # 정보 기한 만료 시 바로 리다이렉트
        if int(now) + 60 < time.time():
            return redirect(redirect_uri)

        try:
            # KFTC로 code를 보내고 token관련 정보를 얻어옴
            result = KFTCAuth().get_token(code)

            # 응답을 바탕으로 필요한 정보 얻기
            access_token = result['access_token']
            expires = datetime.datetime.now() + datetime.timedelta(seconds=result['expires_in'])
            refresh_token = result['refresh_token']
            user_seq_no = result['user_seq_no']
            cred_key = {
                'login': '******',
                'inquiry': 'kftc_inquiry_access_token'
            }.get(result['scope'])
            cred_key_refresh = {
                'login': '******',
                'inquiry': 'kftc_inquiry_refresh_token'
            }.get(result['scope'])

            res = {}

            # access_token DB에 씀
            query = "INSERT INTO credential (user_id, cred_key, cred_value, expires) " \
                    "VALUES (:id, :cred_key, :cred_value, :expires) " \
                    "ON DUPLICATE KEY UPDATE cred_value=:cred_value, expires=:expires;"
            g.db.execute(text(query), id=u_id, cred_key=cred_key, cred_value=access_token, expires=expires)

            # refresh_token DB에 씀
            query = "INSERT INTO credential (user_id, cred_key, cred_value) " \
                    "VALUES (:id, :cred_key, :cred_value) " \
                    "ON DUPLICATE KEY UPDATE cred_value=:cred_value;"
            g.db.execute(text(query), id=u_id, cred_key=cred_key_refresh, cred_value=refresh_token, expires=expires)

            # user_seq_no(KFTC에서 user를 구분하는 id) DB에 씀
            query = "INSERT INTO credential (user_id, cred_key, cred_value) " \
                    "VALUES (:u_id, :cred_key, :cred_value) " \
                    "ON DUPLICATE KEY UPDATE cred_value=:cred_value"
            g.db.execute(text(query), u_id=u_id, cred_key='kftc_user_seq_no', cred_value=user_seq_no)

            res['e_msg'] = success()

            if result.get('scope') == u'login':
                update_state(u_id, 2, True, u'토큰 받아오기 완료')
            elif result.get('scope') == u'inquiry':
                update_state(u_id, 3, True, u'토큰 받아오기 완료')

        except:
            raise Exception

        if requester == 'test':
            return 'Access Token: {}'.format(access_token)
        else:
            return redirect(redirect_uri)