示例#1
0
def get_user_by_response(cookie: TCookie) -> tp.Optional[sql.TTableObject]:
    """ Manage get user operation

    Args:
        cookie: http cookie parameters - dict (may be empty)

    Note:
        Send 401 Unauthorized - if no such user

    Returns:
        user_obj or None if wrong session id - (id, type, phone, name, pass, team, credits, avatar)
    """

    # Get session id or ''
    # print(f"Getting user by response sessid raw:{cookie.get('sessid', '')}")
    # sessid = bytes.fromhex(cookie.get('sessid', ''))  # Get session id from cookie
    # print(f'Getting user by response sessid:{sessid}')
    sessid = cookie.get('sessid', '')

    if sessid == '':  # No cookie
        return None

    sess = sql.get_session(sessid)  # Get session object

    if sess is None:  # No such session - wrong cookie
        return None

    user_obj = sql.get_in_table(sess['user_id'],
                                'users')  # Get user by user id

    if user_obj is None:  # No such user - wrong cookie or smth wrong
        return None

    return user_obj
示例#2
0
def get_class(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Class data HTTP request
    Get class description by class id

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Returns:
        Response - result of request
    """

    data = sql.get_in_table(query['id'], 'classes')

    # Json event data
    return http.ok(json_dict=data)
示例#3
0
def get_event(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Event data HTTP request
    Get event description by event id

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Returns:
        Response - result of request
    """

    data = sql.get_in_table(query['id'], 'events')

    # Json event data
    return http.ok(host=env['HTTP_HOST'], json_dict=data)
示例#4
0
def get_project(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Get  Project HTTP request by id
    Send project description in json format

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Returns:
        Response - result of request
    """

    project_id = query['id']

    data = sql.get_in_table(project_id, 'projects')

    return http.ok(json_dict=data)
示例#5
0
文件: post.py 项目: k4black/iHSE_web
def post_remove_enroll(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Remove  HTTP request (by student )
    By cookie add credits to user

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it or timeout

    Returns:
        Response - result of request
        None; Only http answer
    """

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    enroll_id = query['id']
    enroll = sql.get_in_table(enroll_id, 'enrolls')

    if enroll is not None and (
            user_obj['user_type'] == 0 and enroll['user_id'] == user_obj['id'] or user_obj['user_type'] >= 1):
        # Check admin or user remove himself

        event = sql.get_event_with_date(enroll['class_id'])

        if not check_enroll_time(event['date'], event['time']):  # Close for 15 min
            return http.gone()

        sql.remove_enroll(enroll_id)

        return http.ok(host=env['HTTP_HOST'])

    else:
        return http.not_allowed()
示例#6
0
文件: admin.py 项目: k4black/iHSE_web
def post_checkin(env: TEnvironment, query: TQuery,
                 cookie: TCookie) -> TResponse:
    """ Check in at lecture  HTTP request (by admin)
    By cookie add credits to user

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it or timeout

    Returns:
        Response - result of request
        None; Only http answer
    """

    checkins = get_json_by_response(env)
    event_id = query['event']

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)

    event = sql.get_in_table(event_id, 'events')

    if event is None:  # No such event
        return http.not_allowed(host=env['HTTP_HOST'])

    config_dict = config.get_config()

    # Set up credits and enrolls attendance
    if event['type'] == 1 and event['total'] > 0:
        # master
        # Check there are enrolls
        enrolls = sql.get_enrolls_by_event_id(event_id)

        users_in_enrolls = {
            enroll['user_id']
            for enroll in enrolls if not enroll['attendance']
        }  # type: tp.Set[int]
        users_in_checkins = {
            int(checkin['id']): min(int(checkin['bonus']),
                                    config_dict['CREDITS_ADDITIONAL'])
            for checkin in checkins
        }  # type: tp.Dict[int, int]

        users_to_set_credits = {
            k
            for k in users_in_checkins.keys() if k in users_in_enrolls
        }  # type: tp.Set[int]

        # Setup attendance for enrolls
        enrolls = [
            enroll for enroll in enrolls
            if enroll['user_id'] in users_to_set_credits
        ]  # type: tp.List[sql.TTableObject]
        for i in range(len(enrolls)):
            enrolls[i]['attendance'] = True
            enrolls[i]['bonus'] = users_in_checkins[enrolls[i]['user_id']]

            sql.update_in_table(enrolls[i], 'enrolls')

        # TODO: Minus balls if not attendant
        credits = [{
            'user_id':
            int(checkin['id']),
            'event_id':
            event_id,
            'validator_id':
            user_obj['id'],
            'time':
            get_datetime_str(),
            'value':
            config_dict['CREDITS_MASTER'] +
            min(int(checkin['bonus']), config_dict['CREDITS_ADDITIONAL'])
        } for checkin in checkins if int(checkin['id']) in users_to_set_credits
                   ]  # type: tp.List[sql.TTableObject]
        for credit in credits:
            sql.insert_to_table(credit, 'credits')

        logger('post_checkin()',
               f'Checkin users {users_in_checkins} to master event {event_id}',
               type_='LOG')
    else:
        # lecture
        enrolls = [{
            'class_id':
            event_id,
            'user_id':
            int(checkin['id']),
            'time':
            get_datetime_str(),
            'attendance':
            True,
            'bonus':
            min(int(checkin['bonus']), config_dict['CREDITS_ADDITIONAL'])
        } for checkin in checkins]  # type: tp.List[sql.TTableObject]
        for enroll in enrolls:
            sql.update_in_table(enroll, 'enrolls')

        credits = [{
            'user_id':
            int(checkin['id']),
            'event_id':
            event_id,
            'time':
            get_datetime_str(),
            'value':
            config_dict['CREDITS_LECTURE'] +
            min(int(checkin['bonus']), config_dict['CREDITS_ADDITIONAL'])
        } for checkin in checkins]  # type: tp.List[sql.TTableObject]
        for credit in credits:
            sql.insert_to_table(credit, 'credits')

        logger('post_checkin()',
               f'Checkin user {checkins} to lecture event {event_id}',
               type_='LOG')

    return http.ok(env['HTTP_HOST'])