Пример #1
0
def check_code(input_code):
    cached = code_cache.get(current_identity.openid)
    if cached.get('code', '') != input_code:
        raise NotFound()
    cached.setdefault('status', 1)
    code_cache.set(current_identity.openid, **cached)
    return Response().json()
Пример #2
0
def get_info():
    with Transaction() as session:
        reg: NovaRegTable = session.query(NovaRegTable).filter(
            NovaRegTable.openid == current_identity.openid).first()
        if not reg or reg.delete:
            raise NotFound('student not registered')
        return Response(**reg.to_dict()).json()
Пример #3
0
def test_route():
    data = {'code': request.args.get('code', '')}
    resp = rq.post('{}/api/token'.format(
        current_app.config['LOCAL_URL']),
        json=data
    ).json()

    return Response(**resp).json()
Пример #4
0
def admin_delete_info(stuid):
    with Transaction() as session:
        reg: NovaRegTable = session.query(NovaRegTable).filter(
            NovaRegTable.stuid == stuid).first()
        if not reg:
            raise NotFound('student not registered')
        reg.delete = True
    return Response().json()
Пример #5
0
def ems_logistics():
    no = request.args.get('no', '')
    if not no:
        raise BadRequest('Request args \"no\" missing')
    header = {'Authorization': 'APPCODE {}'.format(current_app.config['EXPRESS_APP_CODE'])}
    resp = rq.get(current_app.config['EXPRESS_API_URL'], params={'no': no}, headers=header).json()
    if resp.get('msg', '') != 'ok':
        raise InternalServerError('Get express info failed')
    return Response(**resp.get('result')).json()
Пример #6
0
def cancel_register():
    with Transaction() as session:
        reg: NovaRegTable = session.query(NovaRegTable).filter(
            NovaRegTable.openid == current_identity.openid).first()
        if not reg:
            raise NotFound('student not registered')
        reg.delete = True
        send_unregister_msg(reg.name)
        return Response().json()
Пример #7
0
def send_code():
    phone = request.json.get('phone', '')
    if not phone:
        raise BadRequest('Request arg \"phone\" missing')
    gen_code = str(random.randrange(1000, 9999))
    status, msg = send_verify_code(phone, gen_code)
    if not status:
        raise InternalServerError(msg)
    code_cache.set(current_identity.openid, code=gen_code, phone=phone)
    return Response().json()
Пример #8
0
def get_source_student_info():
    with Transaction() as session:
        query = session.query(StudentTable).filter(StudentTable.openid == current_identity.openid)
        student: StudentTable = query.first()
        if not student:
            raise NotFound('Student not registered')
        source: SourceStudentTable = session.query(SourceStudentTable).filter(
            SourceStudentTable.id_card == student.id_card).first()
        if not source:
            raise NotFound('Source student info not found')
        return Response(**source.to_dict()).json()
Пример #9
0
def gen_link(role):
    openid = get_openid(request.args.get('code', ''))
    if not openid:
        raise Unauthorized('code invalid')
    if Permission.ADMIN not in get_roles_of_openid(openid):
        raise Unauthorized('admin privilege need')
    if Permission.loads(role) == Permission.EMPTY:
        return BadRequest('unknown role')
    seq = uuid.uuid4().hex
    link_cache.set(seq, role=role)
    link = '{}{}?seq={}'.format(current_app.config['SERVER_URL'],
                                url_for('admin.auth'), seq)
    return Response(link=gen_redirect_url(link)).json()
Пример #10
0
def check_token():
    with Transaction() as session:
        student: StudentTable = session.query(StudentTable).filter(
            StudentTable.openid == current_identity.openid).first()
        admission_id = stuid = ''
        if student:
            source_student: SourceStudentTable = session.query(
                SourceStudentTable.stuid, SourceStudentTable.admission_id
            ).filter(SourceStudentTable.id_card == student.id_card).first()
            if source_student:
                stuid = source_student.stuid
                admission_id = source_student.admission_id
    return Response(stuid=stuid, admission_id=admission_id).json()
Пример #11
0
def bert():
    q = request.args.get('q', '')
    if not q:
        raise BadRequest('Request arg "q" missing')
    answer = candidate_answer(q)
    if answer is None:
        raise InternalServerError('Bert server error')
    # TODO
    # filter = or_(*(QNA.q.like(a) for a in answer[0]))
    # query = engine.session.query(QNA.q, QNA.a).filter(filter)
    # ret = [{'q': row.q, 'a': row.a} for row in query.all()]
    # q_list, a_list = map(ret, zip(*ret))
    ret = [{'q': answer[0][i], 'a': answer[1][i]} for i in range(len(answer[0]))]
    return Response(answer=ret).json()
Пример #12
0
def student_update():
    expected = ['phone', 'id_card', 'admission_id', 'student_id']
    params = {k: request.json.get(k) for k in expected if k in request.json}
    with Transaction() as session:
        query = session.query(StudentTable).filter(StudentTable.openid == current_identity.openid)
        student: StudentTable = query.first()
        if not student:
            raise NotFound('Student not posted')
        if student.phone != params.get('phone', student.phone):
            cached = code_cache.get(current_identity.openid)
            if not cached.get('status', False):
                raise Unauthorized('Phone not verified')
        query.update(params)
    return Response().json()
Пример #13
0
def candidate_update():
    expected = ['phone', 'name', 'province', 'city', 'score', 'subject']
    params = {k: request.json.get(k) for k in expected if k in request.json}
    with Transaction() as session:
        query = session.query(CandidateTable).filter(CandidateTable.openid == current_identity.openid)
        candidate: CandidateTable = query.first()
        if not candidate:
            raise NotFound('Candidate not posted')
        if candidate.phone != params.get('phone', candidate.phone):
            cached = code_cache.get(current_identity.openid)
            if not cached.get('status', False):
                raise Unauthorized('Phone not verified')
        query.update(params)
    return Response().json()
Пример #14
0
def candidate_signup():
    cached = code_cache.get(current_identity.openid)
    if not cached.get('status', False):
        raise Unauthorized('Phone not verified')
    param_keys = ['name', 'province', 'city', 'score', 'subject']
    params = {k: request.json.get(k) for k in param_keys if k in request.json}
    if len(params.keys()) != len(param_keys):
        raise BadRequest('Require params: {}, only get {}'.format(
            ', '.join(param_keys), ', '.join(params.keys())))
    candidate = CandidateTable(openid=current_identity.openid, phone=cached.get('phone'), **params)
    with Transaction() as session:
        if session.query(CandidateTable).filter(CandidateTable.openid == current_identity.openid).first():
            raise Conflict('Candidate has been posted')
        session.add(candidate)
    return Response().json()
Пример #15
0
def qna():
    q = request.args.get('q', '')
    if not q:
        raise BadRequest('Request arg "q" missing')
    try:
        rsp: Dict[str, List[str, str, str]] = tf_idf_client.find_all(q)
        answer = ''
        for k, v in rsp.items():
            if len(answer) != 0:
                answer += '\n\n'
            answer += '{} {} {}页\n{}'.format(*v, k)
    except IndexError:
        current_app.logger.info('[qna] no correspond answer to {}'.format(q))
        answer = '抱歉,您的问题暂时无法解答呢。(つд⊂)'
    return Response(answer=answer).json()
Пример #16
0
def auth():
    openid = get_openid(request.args.get('code', ''))
    if not openid:
        raise Unauthorized('code invalid')
    seq = request.args.get('seq', '')
    if not seq:
        raise BadRequest('seq empty')
    cached = link_cache.get(seq)
    role = cached.get('role', '')
    if not role:
        return NotFound('link invalid')
    permission = Permission.loads(role)
    privilege = PrivilegeTable(openid=openid, permission=permission.value)
    with Transaction() as session:
        if session.query(PrivilegeTable).filter_by(
                openid=openid, permission=permission.value).first():
            return Conflict('privilege has been checked before')
        session.add(privilege)
    return Response().json()
Пример #17
0
def get_source():
    with Transaction() as session:
        student: StudentTable = session.query(StudentTable).filter(
            StudentTable.openid == current_identity.openid).first()
        assert student is not None
        phone = student.phone
        source: SourceStudentTable = session.query(SourceStudentTable).filter(
            SourceStudentTable.id_card == student.id_card).first()
        assert source is not None
        qq = ''
        reg: NovaRegTable = session.query(NovaRegTable).filter(
            NovaRegTable.openid == current_identity.openid).first()
        if reg:
            phone = reg.phone
            qq = reg.qq
        return Response(stuid=source.stuid,
                        name=source.name,
                        department=source.department,
                        phone=phone,
                        qq=qq).json()
Пример #18
0
def student_signup():
    cached = code_cache.get(current_identity.openid)
    if not cached.get('status', False):
        raise Unauthorized('Phone not verified')
    expected = ['id_card', 'id']
    params = {k: request.json.get(k) for k in expected if k in request.json}
    keys = params.keys()
    if len(keys) != len(expected):
        raise BadRequest('Require params: {}, only get {}'
                         .format(', '.join(expected), ', '.join(keys)))
    student = StudentTable(openid=current_identity.openid, phone=cached.get('phone'), id_card=params.get('id_card'))
    with Transaction() as session:
        if not session.query(SourceStudentTable).filter(
                and_(SourceStudentTable.id_card == params.get('id_card'),
                     or_(SourceStudentTable.admission_id == params.get('id'),
                         SourceStudentTable.stuid == params.get('id')))).first():
            raise NotFound('Correspond id of id_card not found')
        if session.query(StudentTable).filter(StudentTable.openid == current_identity.openid).first():
            raise Conflict('Student has been posted')
        session.add(student)
    return Response().json()
Пример #19
0
def get_students():
    params = {
        k: request.args.get(k, '')
        for k in ['department', 'admission_id', 'origin', 'field', 'name']
    }

    field_arg: str = params.pop('field', '')
    if not field_arg:
        fields = [SourceStudentTable]

        # trait = lambda student: student.to_dict()
        def trait(student: SourceStudentTable):
            return student.to_dict()
    else:
        columns: List[str] = field_arg.split(',')
        fields = [getattr(SourceStudentTable, column) for column in columns]

        # trait = lambda student: {k: getattr(student, k) for k in columns}
        def trait(student: SourceStudentTable):
            return {k: getattr(student, k) for k in columns}

    ids: List[str] = [
        s for s in params.pop('admission_id', '').split(',') if s
    ]
    for idx, id_ in enumerate(ids):
        if id_.startswith('*'):
            id_ = '%' + id_[1:]
        if id_.endswith('*'):
            id_ = id_[:-1] + '%'
        ids[idx] = id_

    params = {k: v for (k, v) in params.items() if v}
    query: orm.query = engine.session.query(*fields).filter_by(**params)
    if ids:
        id_filter = or_(*(SourceStudentTable.admission_id.like(id_)
                          for id_ in ids))
        query: orm.query = query.filter(id_filter)
    return Response(students=[trait(student)
                              for student in query.all()]).json()
Пример #20
0
def get_token():
    data: dict = request.json
    roles = []
    if 'code' in data:
        openid = get_openid_by_code(data.get('code', ''))
        if not openid:
            raise Unauthorized('Code invalid')
        roles = get_roles_of_openid(openid)
    else:
        openid = data.get('username', '')
        password = data.get('password', '')
        if not openid or not password:
            raise BadRequest('username & password or code required')
        with Transaction() as session:
            user: AuthUserTable = session.query(AuthUserTable).filter(AuthUserTable.username == openid).first()
            if not user:
                raise Unauthorized('username not existed')
            if user.password != password:
                raise Unauthorized('password incorrect')
            roles = get_roles_of_openid(openid)
    return Response(token=gen_token(openid, roles),
                    candidate=Permission.CANDIDATE in roles,
                    student=Permission.STUDENT in roles).json()
Пример #21
0
def post_info():
    param_keys = [m.key for m in NovaRegTable.__table__.columns]
    param_keys.remove('openid')
    param_keys.remove('delete')
    params = {k: request.json.get(k) for k in param_keys if k in request.json}
    if len(param_keys) != len(params):
        raise BadRequest('Require params: {}, only get: {}'.format(
            ', '.join(param_keys), ', '.join(params.keys())))
    with Transaction() as session:
        reg: NovaRegTable = session.query(NovaRegTable).filter(
            NovaRegTable.openid == current_identity.openid).first()
        if reg:
            if not reg.delete:
                raise Conflict('student registered before')
            reg.delete = False
            for k, v in params.items():
                setattr(reg, k, v)
        else:
            reg: NovaRegTable = NovaRegTable(openid=current_identity.openid,
                                             **params,
                                             delete=False)
            session.add(reg)
    send_register_msg(reg.name)
    return Response().json()
Пример #22
0
def refresh_token():
    return Response(token=get_crypto_token(current_identity.openid)).json()
Пример #23
0
def admin_get_info():
    with Transaction() as session:
        regs: List[NovaRegTable] = session.query(NovaRegTable).all()
        return Response(
            students=[reg.to_dict() for reg in regs if not reg.delete]).json()
Пример #24
0
def test_token(openid):
    with Transaction() as session:
        is_candidate = True if session.query(CandidateTable).filter(CandidateTable.openid == openid).first() else False
        is_student = True if session.query(StudentTable).filter(StudentTable.openid == openid).first() else False
    return Response(token=get_crypto_token(openid), candidate=is_candidate, student=is_student).json()