示例#1
0
def save_token(token, request, *args, **kwargs):
    user = request.user
    toks = Token.objects(
        client_id=request.client.client_id,
        user_id=user.id
    )
    # make sure that every client has only one token connected to a user
    for t in toks:
        t.delete()

    expires_in = token.pop('expires_in')
    expires = datetime.utcnow() + timedelta(seconds=expires_in)

    tok = Token(
        access_token=token['access_token'],
        refresh_token=token['refresh_token'],
        token_type=token['token_type'],
        _scopes=token['scope'],
        expires=expires,
        client_id=request.client.client_id,
        user_id=user.id,
        user=user
    )
    tok.save()
    return tok
示例#2
0
def diary_post():
    to_serialize = {'status': False}
    payload = request.get_json()
    if payload:
        token_str = payload['token']
    else:
        token_str = payload
    code = 200
    if is_token_valid(token_str) == False:
        to_serialize['status'] = False
        to_serialize['error'] = 'Invalid authentication token.'
    else:
        token = Token.objects(token=token_str).first()
        data = json.loads(token.data)
        pk = data['pk']
        user = User.objects(pk=ObjectId(pk)).first()
        username = user.username
        results = Diary.objects(username=username)
        result = []
        if results is not None:
            for oneresult in results:
                diary = {'id': oneresult.id, 'title': oneresult.title, 'author': oneresult.username,
                         'publish_date': oneresult.published_time, 'public': oneresult.public, 'text': oneresult.text}
                result.append(json.dumps(diary))
        to_serialize['status'] = True
        to_serialize['result'] = result

    # todo make the json_response() better
    response = current_app.response_class(
        response=json.dumps(to_serialize),
        status=code,
        mimetype='application/json'
    )
    return response
示例#3
0
def users():
    to_serialize = {'status': False}
    payload = request.get_json()
    if payload and 'token' in payload:
        token_str = payload['token']
    code = 200
    if not is_token_valid(token_str):
        to_serialize['status'] = False
        to_serialize['error'] = 'Invalid authentication token.'
    else:
        token = Token.objects(token=token_str).first()
        data = json.loads(token.data)
        pk = data['pk']
        user = User.objects(pk=ObjectId(pk)).first()
        result = {'username': user.username, 'fullname': user.fullname, 'age': user.age}
        to_serialize['status'] = True
        to_serialize['result'] = json.dumps(result)

    # todo make the json_response() better
    response = current_app.response_class(
        response=json.dumps(to_serialize),
        status=code,
        mimetype='application/json'
    )
    return response
示例#4
0
def debug_getrawdb():
    to_serialize = {'status': 'success'}
    to_serialize['users'] = [db_object_to_dict(usr) for usr in User.objects()]
    to_serialize['tokens'] = [db_object_to_dict(token) for token in Token.objects()]
    to_serialize['diaries'] = [db_object_to_dict(diary) for diary in Diary.objects()]
    code = 200
    response = current_app.response_class(
        response=json.dumps(to_serialize),
        status=code,
        mimetype='application/json'
    )
    return response
示例#5
0
def get_uid_token(flush=False):
    cmdb_info = Cmdb.objects.filter(username=CMDB2_USER)
    tu = Token.objects.all()
    username, password, uid, token = "", "", "", ""
    for ci in cmdb_info:
        username = ci.username
        password = base64.b64decode(ci.password)
    for one in tu:
        uid, token = one.uid, one.token
    if uid and token and not flush:
        return uid, token
    url = CMDB2_URL + "cmdb/openapi/login/"
    data = {
        "username": username,
        "password": password,
        "sign": "",
        "timestamp": TimeToolkit.local2utctime(datetime.now())
    }
    data_str = json.dumps(data)
    try:
        # Log.logger.info("login data:{}".format(data))
        ret = requests.post(url, data=data_str, timeout=5)
        # Log.logger.info(ret.json())
        if ret.json()["code"] == 0:
            uid, token = ret.json()["data"]["uid"], ret.json()["data"]["token"]
            one = Token.objects.filter(uid=uid)
            if one:
                Token.objects(uid=uid).update_one(
                    token=token,
                    token_date=TimeToolkit.local2utctimestamp(datetime.now()))
            else:
                tu = Token(uid=uid,
                           token=token,
                           token_date=TimeToolkit.local2utctimestamp(
                               datetime.now()))
                tu.save()
    except Exception as exc:
        pass
    return uid, token
示例#6
0
def diary_creation():
    to_serialize = {'status': False}
    title,text,public,token=None,None,None,None
    payload = request.get_json()
    payload2 = request.get_json()
    if payload2 and \
            'title' in payload2 and \
            'text' in payload2 and \
            'public' in payload2:
        title = payload2['title']
        text = payload2['text']
        public = payload2['public']

    if payload:
        token_str = payload['token']
    else:
        token_str = payload
    code = 200
    if is_token_valid(token_str) == False:
        to_serialize['status'] = False
        to_serialize['error'] = 'Invalid authentication token.'
    else:
        if title is None or text is None or public is None:
            to_serialize['error'] = 'Required parameter is missing'
        else:
            token = Token.objects(token=token_str).first()
            data = json.loads(token.data)
            pk = data['pk']
            user = User.objects(pk=ObjectId(pk)).first()
            username = user.username
            dtnow = datetime.datetime.now()
            published_time = dtnow.replace(microsecond=0).isoformat()

            diary = Diary(title=title, username=username, published_time=published_time, public=public, text=text)
            diary.save()
            id=diary.id
            to_serialize['status'] = True
            to_serialize['result'] = {'id': id}

    # todo make the json_response() better
    response = current_app.response_class(
        response=json.dumps(to_serialize),
        status=code,
        mimetype='application/json'

    )
    return response
示例#7
0
def users_expire():
    payload = request.get_json()
    if payload and 'token' in payload:
        token_str = payload['token']
    to_serialize = {'status': False}
    code = 200
    if not is_token_valid(token_str):
        to_serialize['status'] = False
    else:
        token = Token.objects(token=token_str).first()
        token.delete()
        to_serialize['status'] = True

    # todo make the json_response() better
    response = current_app.response_class(
        response=json.dumps(to_serialize),
        status=code,
        mimetype='application/json'
    )
    return response
示例#8
0
def diary_permission():
    to_serialize = {'status': False}
    payload = request.get_json()
    payload2 = request.get_json()
    if payload2 and \
            'id' in payload2 and \
            'public' in payload2:

        id = payload2['id']
        public = payload2['public']

    if payload:
        token_str = payload['token']
    else:
        token_str = payload
    code = 200
    if is_token_valid(token_str) == False:
        to_serialize['status'] = False
        to_serialize['error'] = 'Invalid authentication token.'
    else:
        if id is None or public is None:
            to_serialize['error'] = 'Required parameter is missing'
        else:
            token = Token.objects(token=token_str).first()
            data = json.loads(token.data)
            pk = data['pk']
            user = User.objects(pk=ObjectId(pk)).first()
            username = user.username
            diary = Diary.objects(id=id).first()
            DiaryOwner = diary.username
            if DiaryOwner == username:
                diary.update(public=public)
                to_serialize['status'] = True

    # todo make the json_response() better
    response = current_app.response_class(
        response=json.dumps(to_serialize),
        status=code,
        mimetype='application/json'
    )
    return response