예제 #1
0
def group_invalidate(group_id):
    group.get_group(group_id)
    if request.is_json:
        data = request.json
        AccessToken = data['accessToken']
        ClientToken = data.get("clientToken")

        result = Token.gettoken(AccessToken, ClientToken)
        if result:
            group.token_is_group(result, group_id)
            model.log_yggdrasil(operational="authserver.invalidate",
                                user=result.get("user"),
                                otherargs=json.dumps(
                                    {"clientToken": data.get("clientToken")}),
                                IP=request.remote_addr,
                                time=datetime.datetime.now()).save()
            cache_token.delete(AccessToken)
        else:
            model.log_yggdrasil(operational="authserver.invalidate",
                                otherargs=json.dumps(
                                    {"clientToken": data.get("clientToken")}),
                                IP=request.remote_addr,
                                time=datetime.datetime.now(),
                                successful=False).save()
            if ClientToken:
                raise Exceptions.InvalidToken()
        #User = model.user.get(email=result.email)
        '''if User.permission == 0:
            return Response(simplejson.dumps({
                'error' : "ForbiddenOperationException",
                'errorMessage' : "You have been banned by the administrator, please contact the administrator for help"
            }), status=403, mimetype='application/json; charset=utf-8')'''
        return Response(status=204)
예제 #2
0
def group_PlayerHasJoined(group_id):
    group.get_group(group_id)
    args = request.args
    ServerID = args['serverId']
    PlayerName = args['username']
    RemoteIP = args['ip'] if 'ip' in args else None
    Successful = False
    Data = cache_joinserver.get(ServerID)
    if not Data:
        model.log_yggdrasil(
            operational="sessionserver.session.minecraft.hasJoined",
            IP=request.remote_addr,
            time=datetime.datetime.now(),
            successful=False).save()
        return Response(status=204)
    TokenInfo = Token.gettoken(Data['accessToken'])
    group.token_is_group(TokenInfo, group_id)
    ProfileInfo = model.getprofile_uuid_name(TokenInfo.get("bind"),
                                             name=PlayerName)
    if not TokenInfo or not ProfileInfo:
        model.log_yggdrasil(
            operational="sessionserver.session.minecraft.hasJoined",
            IP=request.remote_addr,
            time=datetime.datetime.now(),
            successful=False).save()
        return Response(status=204)

    ProfileInfo = ProfileInfo.get()

    Successful = PlayerName == ProfileInfo.name and [
        True, RemoteIP == Data['remoteIP']
    ][bool(RemoteIP)]
    if Successful:
        model.log_yggdrasil(
            operational="sessionserver.session.minecraft.hasJoined",
            user=TokenInfo.get("user"),
            IP=request.remote_addr,
            time=datetime.datetime.now()).save()
        result = json.dumps(
            model.format_profile(ProfileInfo,
                                 Properties=True,
                                 unsigned=False,
                                 BetterData=True))
        return Response(result, mimetype="application/json; charset=utf-8")
    else:
        model.log_yggdrasil(
            operational="sessionserver.session.minecraft.hasJoined",
            user=TokenInfo.get("user"),
            IP=request.remote_addr,
            time=datetime.datetime.now(),
            successful=False).save()
        return Response(status=204)
    return Response(status=204)
예제 #3
0
def group_joinserver(group_id):
    group.get_group(group_id)
    token = {}
    if request.is_json:
        data = request.json
        AccessToken = data['accessToken']
        ClientToken = data.get("clientToken")
        TokenValidate = Token.is_validate_strict(AccessToken, ClientToken)

        if not TokenValidate:
            # Token有效
            # uuid = token.bind
            token = Token.gettoken_strict(AccessToken, ClientToken)
            if not token:
                raise Exceptions.InvalidToken()
            group.token_is_group(token, group_id)
            if token.get('bind'):
                result = model.getprofile_uuid(token.get('bind'))
                if not result:
                    return Response(status=404)
            else:
                raise Exceptions.InvalidToken()
            player = model.getprofile(result.get().name).get()
            playeruuid = player.profile_id.replace("-", "")
            if data['selectedProfile'] == playeruuid:
                cache_joinserver.set(data['serverId'], {
                    "accessToken": AccessToken,
                    "selectedProfile": data['selectedProfile'],
                    "remoteIP": request.remote_addr
                },
                                     ttl=config.ServerIDOutTime)
                model.log_yggdrasil(
                    operational="sessionserver.session.minecraft.join",
                    user=token.get("user"),
                    IP=request.remote_addr,
                    time=datetime.datetime.now()).save()
                return Response(status=204)
            else:
                model.log_yggdrasil(
                    operational="sessionserver.session.minecraft.join",
                    user=token.get("user"),
                    IP=request.remote_addr,
                    time=datetime.datetime.now(),
                    successful=False).save()
                raise Exceptions.InvalidToken()
        else:
            model.log_yggdrasil(
                operational="sessionserver.session.minecraft.join",
                IP=request.remote_addr,
                time=datetime.datetime.now(),
                successful=False).save()
            raise Exceptions.InvalidToken()
예제 #4
0
def group_index(group_id):
    group.get_group(group_id)
    return Response(json.dumps({
        "meta":
        config.YggdrasilIndexData,
        "skinDomains":
        config.SiteDomain if "SiteDomain" in config.__dict__ else
        [urlparse(request.url).netloc.split(":")[0]],
        "signaturePublickey":
        open(config.KeyPath.Public, 'r').read(),
        'groupId':
        group_id
    }),
                    mimetype='application/json; charset=utf-8')
예제 #5
0
def kf_group_interfaces_report_join(group_id):
    if not request.is_json:
        raise Exceptions.InvalidToken()
    data = request.json

    token = G.auto_verify(request)
    user_uuid = model.getuser_uuid(token.get("user")).uuid
    if not model.group.select().where(model.group.uuid == group_id):
        raise Exceptions.InvalidToken()
    group = G.get_group(group_id)
    if group.joinway not in ["public_join", "public_join_review"]:
        raise Exceptions.InvalidToken()

    if model.member.select().where(
        (model.member.is_disabled == False) &
        (model.member.user == user_uuid) &
        (model.member.group == group.id)
    ):
        raise Exceptions.InvalidToken()

    if group.joinway == "public_join":
        new = model.member(user=user_uuid, group=group_id,
                           permission="common_user")
        new.save()
        return Response(json.dumps(model.kf_format_group_public(group)), mimetype='application/json; charset=utf-8')
    if group.joinway == "public_join_review":
        review = model.review(user=user_uuid, group=group.id)
        review.save()
        return Response(json.dumps({
            "reviewId": review.id
        }), mimetype='application/json; charset=utf-8')
    if group.joinway == 'private':
        raise Exceptions.InvalidToken()
예제 #6
0
def delete_switch(gid, data):
    serializer = GroupSwitchPostSerializer(data=data, many=True)
    if not serializer.is_valid():
        raise IgniteException(serializer.errors)
    group.delete_switch(gid, serializer.data)
    grp = group.get_group(gid)
    serializer = GroupDetailSerializer(grp)
    return serializer.data
예제 #7
0
def group_signout(group_id):
    group.get_group(group_id)
    if request.is_json:
        data = request.json
        email = data['username']
        passwd = data['password']
        result = model.getuser(email)
        if not result:
            model.log_yggdrasil(operational="authserver.signout",
                                IP=request.remote_addr,
                                time=datetime.datetime.now(),
                                successful=False).save()
            raise Exceptions.InvalidCredentials()
        else:
            group.get_member(result, group_id)
            '''if result.permission == 0:
                return Response(json.dumps({
                    'error' : "ForbiddenOperationException",
                    'errorMessage' : "Invalid credentials. Invalid username or password."
                }), status=403, mimetype='application/json; charset=utf-8')'''
            if not cache_limit.get(".".join(['lock', result.email])):
                cache_limit.set(".".join(['lock', result.email]),
                                "LOCKED",
                                ttl=config.AuthLimit)
            else:
                raise Exceptions.InvalidCredentials()
            if password.crypt(passwd,
                              salt=result.passwordsalt) == result.password:
                Token_result = Token.getalltoken(result)
                if Token_result:
                    for i in Token_result:
                        if i.get("group") == group_id:
                            cache_token.delete(i)
                model.log_yggdrasil(operational="authserver.signout",
                                    user=result.uuid,
                                    IP=request.remote_addr,
                                    time=datetime.datetime.now()).save()
                return Response(status=204)
            else:
                model.log_yggdrasil(operational="authserver.signout",
                                    user=result.uuid,
                                    IP=request.remote_addr,
                                    time=datetime.datetime.now(),
                                    successful=False).save()
                raise Exceptions.InvalidCredentials()
예제 #8
0
def group_searchmanyprofile(group_id):
    group.get_group(group_id)
    if request.is_json:
        data = list(set(list(request.json)))
        IReturn = []
        for i in range(config.ProfileSearch.MaxAmount - 1):
            try:
                IReturn.append(
                    model.format_profile(
                        model.profile.get(model.profile.name == data[i]),
                        unsigned=True))
            except model.profile.DoesNotExist:
                continue
            except IndexError:
                pass
        return Response(json.dumps(IReturn),
                        mimetype='application/json; charset=utf-8')
    return Response(status=404)
예제 #9
0
def tasks_validation(data, options, job):
    from celery_tasks import get_all_switches
    tsk = []
    if len(data) == 0:
        raise IgniteException("Job cannot have empty task sequence")
    if options == "update":
        ref_count_delete(job)
    for task in data:
        try:
            grp = group.get_group(task[GROUP_ID])
            img = image_profile.get_profile(task[IMAGE_ID])
            if options != 'get' and img.system_image == None:
                raise IgniteException(
                    "No system image is found in the image profile: " +
                    img.profile_name)
            if options != 'get' and task[
                    'type'] == 'epld_upgrade' and img.epld_image == None:
                raise IgniteException(
                    "No epld image is found in the image profile: " +
                    img.profile_name)
            if task['type'] in ['epld_upgrade', 'switch_upgrade']:
                if options != 'get' and img.access_protocol != 'scp':
                    raise IgniteException(
                        "Only scp protocol is supported for image profile: " +
                        img.profile_name)
            task["switch_count"] = len(grp.switch_list)
            # False is to say not to decrypt passwords
            switches = get_all_switches(task, False)
            task['group']['switches'] = switches
            task[IMAGE_NAME] = img.profile_name

            if task['type'] != 'custom':
                task['task_params'] = {}
                image = get_image_details(img)
                if task['type'] == 'epld_upgrade':
                    image['epld_image'] = img.epld_image
                task['task_params']['image'] = image

            if task['type'] == 'custom':
                if task['file_name'] is None and task['function'] is None:
                    raise IgniteException(
                        "Please Provide file/function name Custom task")
                try:
                    task['parameters'] = fill_param_values(task['params'])
                except:
                    raise IgniteException(ERR_IN_PARAMS)

            tsk.append(task)
            if options != "get":
                ref_count_add(grp)
        except Group.DoesNotExist as e:
            raise IgniteException("Group id " + str(task[GROUP_ID]) +
                                  " not found")
        except ImageProfile.DoesNotExist as e:
            raise IgniteException("Image id " + str(task[IMAGE_ID]) +
                                  " not found")
    return tsk
예제 #10
0
def group_searchprofile(group_id, getuuid):
    group.get_group(group_id)
    args = request.args
    result = model.getprofile_id(getuuid)
    if not result:
        return Response(status=204)
    else:
        result = result.get()
    IReturn = model.format_profile(
        #model.user.get(model.user.playername == model.profile.get(profile_id=getuuid).name),
        result,
        Properties=True,
        unsigned={
            "false": False,
            "true": True,
            None: True
        }[args.get('unsigned')],
        BetterData=True)
    return Response(response=json.dumps(IReturn),
                    mimetype='application/json; charset=utf-8')
예제 #11
0
def group_validate(group_id):
    group.get_group(group_id)
    if request.is_json:
        data = request.json
        AccessToken = data['accessToken']
        ClientToken = data.get("clientToken")
        result = Token.gettoken_strict(AccessToken, ClientToken)
        if not result:
            model.log_yggdrasil(operational="authserver.validate",
                                otherargs=json.dumps(
                                    {"clientToken": data.get("clientToken")}),
                                IP=request.remote_addr,
                                time=datetime.datetime.now(),
                                successful=False).save()
            raise Exceptions.InvalidToken()
        else:
            group.token_is_group(result, group_id)
            if Token.is_validate_strict(AccessToken, ClientToken):
                model.log_yggdrasil(user=result.get("user"),
                                    operational="authserver.validate",
                                    otherargs=json.dumps({
                                        "clientToken":
                                        data.get("clientToken")
                                    }),
                                    IP=request.remote_addr,
                                    time=datetime.datetime.now(),
                                    successful=False).save()
                raise Exceptions.InvalidToken()
            else:
                model.log_yggdrasil(
                    user=result.get("user"),
                    operational="authserver.validate",
                    otherargs=json.dumps(
                        {"clientToken": data.get("clientToken")}),
                    IP=request.remote_addr,
                    time=datetime.datetime.now(),
                ).save()
                return Response(status=204)
예제 #12
0
def kf_group_interfaces_manage_setting_change(group_id, setting_name):
    data = G.autodata(request)

    token = G.auto_verify(request)
    user_uuid = model.getuser_uuid(token.get("user")).uuid
    group = G.get_group(group_id)

    manager = G.isManager(group_id, user_uuid)

    if setting_name not in [
        "joinway", "name", "enable_yggdrasil", "enable_invite",
        "enable_public_joinhistory", "enable_public_memberlist"
    ]:
        raise Exceptions.InvalidRequestData()

    value = data.get("change_value")

    if setting_name == "joinway":
        if value not in ["public_join", "public_join_review", "private"]:
            raise Exceptions.InvalidRequestData()
        group.joinway = value

    if setting_name == "name":
        if not re.match(r"[a-zA-Z0-9\u4E00-\u9FA5_-]{4,16}$", value):
            raise Exceptions.InvalidRequestData()
        group.name = value

    if setting_name == "enable_yggdrasil":
        if not type(value) == bool:
            raise Exceptions.InvalidRequestData()
        group.enable_yggdrasil = value

    if setting_name == "enable_invite":
        if not type(value) == bool:
            raise Exceptions.InvalidRequestData()
        group.enable_invite = value

    if setting_name == "enable_public_joinhistory":
        if not type(value) == bool:
            raise Exceptions.InvalidRequestData()
        group.enable_public_joinhistory = value

    if setting_name == "enable_public_memberlist":
        if not type(value) == bool:
            raise Exceptions.InvalidRequestData()
        group.enable_public_memberlist = value

    group.save()
    return Response(status=204)
예제 #13
0
파일: job.py 프로젝트: datacenter/ignite
def tasks_validation(data, options, job):
    from celery_tasks import get_all_switches

    tsk = []
    if len(data) == 0:
        raise IgniteException("Job cannot have empty task sequence")
    if options == "update":
        ref_count_delete(job)
    for task in data:
        try:
            grp = group.get_group(task[GROUP_ID])
            img = image_profile.get_profile(task[IMAGE_ID])
            if options != "get" and img.system_image == None:
                raise IgniteException("No system image is found in the image profile: " + img.profile_name)
            if options != "get" and task["type"] == "epld_upgrade" and img.epld_image == None:
                raise IgniteException("No epld image is found in the image profile: " + img.profile_name)
            if task["type"] in ["epld_upgrade", "switch_upgrade"]:
                if options != "get" and img.access_protocol != "scp":
                    raise IgniteException("Only scp protocol is supported for image profile: " + img.profile_name)
            task["switch_count"] = len(grp.switch_list)
            # False is to say not to decrypt passwords
            switches = get_all_switches(task, False)
            task["group"]["switches"] = switches
            task[IMAGE_NAME] = img.profile_name

            if task["type"] != "custom":
                task["task_params"] = {}
                image = get_image_details(img)
                if task["type"] == "epld_upgrade":
                    image["epld_image"] = img.epld_image
                task["task_params"]["image"] = image

            if task["type"] == "custom":
                if task["file_name"] is None and task["function"] is None:
                    raise IgniteException("Please Provide file/function name Custom task")
                try:
                    task["parameters"] = fill_param_values(task["params"])
                except:
                    raise IgniteException(ERR_IN_PARAMS)

            tsk.append(task)
            if options != "get":
                ref_count_add(grp)
        except Group.DoesNotExist as e:
            raise IgniteException("Group id " + str(task[GROUP_ID]) + " not found")
        except ImageProfile.DoesNotExist as e:
            raise IgniteException("Image id " + str(task[IMAGE_ID]) + " not found")
    return tsk
예제 #14
0
def kf_group_interfaces_manage_setting(group_id):
    data = G.autodata(request)

    token = G.auto_verify(request)
    user_uuid = model.getuser_uuid(token.get("user")).uuid
    group = G.get_group(group_id)

    selectResult = G.isManager(group_id, user_uuid)

    return Response(json.dumps({
        "name": group.name,
        "joinway": group.joinway,
        "enable": {
            "yggdrasil": group.enable_yggdrasil,
            "invite": group.enable_invite,
            "public_joinhistory": group.enable_public_joinhistory,
            "public_memberlist": group.enable_public_memberlist
        }
    }), mimetype='application/json; charset=utf-8')
예제 #15
0
def kf_group_interfaces_manage_checkjoin_refuse(group_id, review_id):
    data = G.autodata(request)

    token = G.auto_verify(request)
    user = model.getuser_uuid(token.get("user"))
    user_uuid = user.uuid
    group = G.get_group(group_id)

    manager = G.isManager(group_id, user_uuid)

    selectResult = model.review.select().where(
        (model.review.id == review_id) &
        (model.review.group == group_id)
    )
    if not selectResult:
        raise Exceptions.InvalidToken()
    selectResult = selectResult.get()
    if selectResult.isEnable != True:
        raise Exceptions.InvalidRequestData()
    selectResult.isEnable = False
    selectResult.isAccessed = False

    for i in model.member.select().where(
        (model.member.group == selectResult.group) &
        ((model.member.permission == "manager") | (model.member.permission == "super_manager")) &
        (model.member.is_disabled == True) &
        (model.member.user != manager.uuid)
    ):
        model.message(
            to=i.user,

            title="用户 %(user)s 面向组 %(group)s 的加组申请被拒绝" % (
                [user.uuid, user.username][bool(user.username)], group.name),
            body="用户 %(user)s 面向组 %(group)s 的加组申请被组管理员 %(manager)s 拒绝" % ([user.uuid, user.username][bool(
                user.username)], group.name, [manager.uuid, manager.username][bool(manager.username)]),
            extra=json.dumps({
                "user": user_uuid,
                "group": group.id,
                "manager": manager.uuid
            })
        )
    return Response(status=204)
예제 #16
0
파일: job.py 프로젝트: sushantpande/ignite
def tasks_validation(data, options, job):
    from celery_tasks import get_all_switches
    tsk = []
    if len(data) == 0:
        raise IgniteException("Job cannot have empty task sequence")
    if options == "update":
        ref_count_delete(job)
    for task in data:
        try:
            grp = group.get_group(task["group_id"])
            img = image_profile.get_profile(task["image_id"])
            if options!= 'get' and img.system_image == None:
                raise IgniteException("No system image is found in the image profile: "+ img.profile_name)
            if options!= 'get' and task['type'] == 'epld_upgrade' and img.epld_image == None:
                raise IgniteException("No epld image is found in the image profile: "+ img.profile_name)
            if options!='get' and img.access_protocol != 'scp':
                raise IgniteException("Only scp protocol is supported for image profile: "+ img.profile_name)
            task["switch_count"] = len(grp.switch_list)
            switches = get_all_switches(task)
            task['group']['switches'] = switches
            task['params']={} 
            task['params']['image'] = {}
            image = {}
            image['profile_name'] = img.profile_name
            image['system_image'] = img.system_image
            image['id'] = img.id
            image['image_server_ip'] = img.image_server_ip
            image['image_server_username'] = img.image_server_username
            image['image_server_password'] = img.image_server_password
            image['access_protocol'] = img.access_protocol
            if task['type'] == 'epld_upgrade':
                image['epld_image'] = img.epld_image
            task['params']['image'] = image
            task["image_name"] = img.profile_name
            tsk.append(task)
            if options != "get":
                ref_count_add(grp)
        except Group.DoesNotExist as e:
            raise IgniteException("Group id "+str(task["group_id"])+" not found")
        except ImageProfile.DoesNotExist as e:
            raise IgniteException("Image id "+str(task["image_id"])+" not found")
    return tsk
예제 #17
0
파일: services.py 프로젝트: whchoi98/ignite
def get_group(gid):
    grp = group.get_group(gid)
    serializer = GroupDetailSerializer(grp)
    return serializer.data
예제 #18
0
파일: bot.py 프로젝트: JeffFosterUK/Bot
def main():
    #d = get_updates()
    while True:
        answer = get_message()

        if answer != None:
            chat_id = answer["chat_id"]
            text = answer["text"]
        
            if text == "/btc":
                send_message(chat_id, get_btc())

            elif text == "/btc@JeffFosterUKBot":
                send_message(chat_id, get_btc())
            
            elif text == "/creator":
                send_message(chat_id, get_creator())
            
            elif text == "/creator@JeffFosterUKBot":
                send_message(chat_id, get_creator())

            elif text == "/roll":
                send_message(chat_id, get_roll())

            elif text == "/roll@JeffFosterUKBot":
                send_message(chat_id, get_roll())
        
            elif text == "/ask":
                send_message(chat_id, get_ask())

            elif text == "/ask@JeffFosterUKBot":
                send_message(chat_id, get_ask())

            elif text == "/discord":
                send_message(chat_id, get_discord())

            elif text == "/discord@JeffFosterUKBot":
                send_message(chat_id, get_discord())

            elif text == "/group":
                send_message(chat_id, get_group())

            elif text == "/group@JeffFosterUKBot":
                send_message(chat_id, get_group())

            elif text == "/group_steam":
                send_message(chat_id, get_groupsteam())

            elif text == "/group_steam@JeffFosterUKBot":
                send_message(chat_id, get_groupsteam())

            elif text == "/instagram":
                send_message(chat_id, get_instagram())

            elif text == "/instagram@JeffFosterUKBot":
                send_message(chat_id, get_instagram())

            elif text == "/steam":
                send_message(chat_id, get_steam())

            elif text == "/steam@JeffFosterUKBot":
                send_message(chat_id, get_steam())

            elif text == "/sub":
                send_message(chat_id, get_sub())

            elif text == "/sub@JeffFosterUKBot":
                send_message(chat_id, get_sub())

            elif text == "/trade":
                send_message(chat_id, get_trade())

            elif text == "/trade@JeffFosterUKBot":
                send_message(chat_id, get_trade())

            elif text == "/twitch":
                send_message(chat_id, get_twitch())

            elif text == "/twitch@JeffFosterUKBot":
                send_message(chat_id, get_twitch())

            elif text == "/vk":
                send_message(chat_id, get_vk())

            elif text == "/vk@JeffFosterUKBot":
                send_message(chat_id, get_vk())

            elif text == "/youtube":
                send_message(chat_id, get_youtube())

            elif text == "/youtube@JeffFosterUKBot":
                send_message(chat_id, get_youtube())

            elif "Бот," in text:
                send_message(chat_id, get_botsay())


        else:
            continue


        sleep(2)
예제 #19
0
def group_authenticate(group_id):
    group.get_group(group_id)
    IReturn = {}
    if request.is_json:
        data = request.json
        user = model.getuser(data['username'])
        if not user:
            raise Exceptions.InvalidCredentials()
        '''if user.permission == 0:
            return Response(json.dumps({
                'error' : "ForbiddenOperationException",
                'errorMessage' : "You have been banned by the administrator, please contact the administrator for help"
            }), status=403, mimetype='application/json; charset=utf-8')'''
        if not cache_limit.get(".".join(['lock', user.email])):
            cache_limit.set(".".join(['lock', user.email]),
                            "LOCKED",
                            ttl=config.AuthLimit)
        else:
            raise Exceptions.InvalidCredentials()
        group.get_member(group_id, user.uuid)
        SelectedProfile = {}
        AvailableProfiles = []
        if password.crypt(data['password'],
                          user.passwordsalt) == user.password:
            # 登录成功.
            ClientToken = data.get("clientToken",
                                   str(uuid.uuid4()).replace("-", ""))
            AccessToken = str(uuid.uuid4()).replace("-", "")
            notDoubleProfile = False

            try:
                AvailableProfiles = [
                    model.format_profile(i, unsigned=True)
                    for i in model.profile.select().where(
                        model.profile.createby == user.uuid)
                ]
            except model.profile.DoesNotExist:
                pass

            Profileresult = model.getprofile_createby(user.uuid)
            if len(Profileresult) == 1:
                notDoubleProfile = True
                SelectedProfile = model.format_profile(Profileresult.get())

            cache_token.set(
                AccessToken, {
                    "clientToken": ClientToken,
                    "bind":
                    Profileresult.get().uuid if notDoubleProfile else None,
                    "user": user.uuid,
                    "group": group_id,
                    "createTime": int(time.time())
                },
                ttl=config.TokenTime.RefrushTime * config.TokenTime.TimeRange)

            IReturn = {
                "accessToken": AccessToken,
                "clientToken": ClientToken,
                "availableProfiles": AvailableProfiles,
                "selectedProfile": SelectedProfile
            }
            if "requestUser" in data:
                if data['requestUser']:
                    IReturn['user'] = model.format_user(user)

            if IReturn['selectedProfile'] == {}:
                del IReturn['selectedProfile']

            user.last_login = datetime.datetime.now()
            model.log_yggdrasil(operational="authserver.authenticate",
                                user=user.uuid,
                                otherargs=json.dumps(
                                    {"clientToken": ClientToken}),
                                IP=request.remote_addr,
                                time=datetime.datetime.now()).save()
        else:
            model.log_yggdrasil(operational="authserver.authenticate",
                                user=user.uuid,
                                IP=request.remote_addr,
                                time=datetime.datetime.now(),
                                successful=False).save()
            raise Exceptions.InvalidCredentials()
        return Response(json.dumps(IReturn),
                        mimetype='application/json; charset=utf-8')
예제 #20
0
def kf_group_interfaces_signout(group_id):
    data = G.autodata(request)

    token = G.auto_verify(request)
    user_uuid = model.getuser_uuid(token.get("user")).uuid
    if not model.group.select().where(model.group.uuid == group_id):
        raise Exceptions.InvalidToken()
    group: model.group = G.get_group(group_id)

    known = G.get_member(group_id, user_uuid)
    if known.permission == "super_manager":
        if not data.get("force"):
            raise Exceptions.InvalidToken()
        else:
            manager_result = model.member.select().where(
                (model.member.is_disabled == False) &
                (model.member.permission == "manager") &
                (model.member.group == group_id)
            )
            if manager_result:
                # 有其他管理员可以被任命为组管理员
                # 随!机!选!择!
                manager_selected = manager_result[random.randint(
                    0, len(manager_result) - 1)]
                manager_result.permission = "super_manager"
                manager_result.save()
                model.message(
                    to=manager_result.user,
                    title='您已成为组 "%(groupname)s" 的组管理员' % (group.name),
                    body='因该组的原组管理员的退出, 您已成为该组的组管理员.',
                    extra=json.dumps({
                        "type": "group"
                    })
                )
            else:
                # 通知一波然后删掉, 解散的组不需要
                now_member = model.member.select().where(
                    (model.member.is_disabled == False) &
                    (model.member.group == group_id) &
                    (model.member.user != user_uuid)
                )
                for i in now_member:
                    model.message(
                        to=i.user,
                        title='您已被清理出组 "%(groupname)s"' % (group.name),
                        body="因该组的原组管理员的退出, 您已被清理出该组."
                    ).save()
                model.member.delete().where(model.member.group == group_id).execute()
    else:
        known.is_disabled = True
        known.move_times += 1
        known.save()
        manager_result = model.member.select().where(
            (model.member.is_disabled == False) &
            ((model.member.permission == "manager") | (model.member.permission == "super_manager")) &
            (model.member.group == group_id)
        )
        for i in manager_result:
            model.message(
                to=i.user,
                title='%(user)s 退出组 "%(groupname)s"' % (
                    model.getuser_uuid(user_uuid).username, group.name),
                body="因该成员的主动申请, 该成员已退出该组."
            ).save()
    return Response(status=204)
예제 #21
0
def get_group(gid):
    grp = group.get_group(gid)
    serializer = GroupDetailSerializer(grp)
    return serializer.data
예제 #22
0
def group_refresh(group_id):
    group.get_group(group_id)
    if request.is_json:
        data = request.json
        Can = False
        AccessToken = data.get('accessToken')
        ClientToken = data.get("clientToken",
                               str(uuid.uuid4()).replace("-", ""))
        IReturn = {}
        if 'clientToken' in data:
            OldToken = Token.gettoken_strict(AccessToken,
                                             data.get("clientToken"))
        else:
            OldToken = Token.gettoken_strict(AccessToken)
        if not OldToken:
            raise Exceptions.InvalidToken()
        group.token_is_group(OldToken, group_id)

        if int(time.time()) >= OldToken.get("createTime") + (
                config.TokenTime.RefrushTime * config.TokenTime.TimeRange):
            model.log_yggdrasil(operational="authserver.refrush",
                                user=OldToken.get("user"),
                                otherargs=json.dumps(
                                    {"clientToken": data.get("clientToken")}),
                                IP=request.remote_addr,
                                time=datetime.datetime.now(),
                                successful=False).save()
            raise Exceptions.InvalidToken()
        User = model.getuser_uuid(OldToken.get("user"))
        group.get_member(group_id, User.uuid)
        TokenSelected = OldToken.get("bind")
        if TokenSelected:
            TokenProfile = model.getprofile_uuid(TokenSelected).get()
        else:
            TokenProfile = {}
        if 'selectedProfile' in data:
            PostProfile = data['selectedProfile']
            needuser = model.getprofile_id_name(PostProfile['id'],
                                                PostProfile['name'])
            if not needuser:  # 验证客户端提供的角色信息
                raise Exceptions.IllegalArgumentException()
                # 角色不存在.
            else:
                needuser = needuser.get()
                # 验证完毕,有该角色.
                if OldToken.get('bind'):  # 如果令牌本来就绑定了角色
                    model.log_yggdrasil(operational="authserver.refrush",
                                        user=User.uuid,
                                        otherargs=json.dumps({
                                            "clientToken":
                                            data.get("clientToken")
                                        }),
                                        IP=request.remote_addr,
                                        time=datetime.datetime.now(),
                                        successful=False).save()
                    error = {
                        'error':
                        'IllegalArgumentException',
                        'errorMessage':
                        "Access token already has a profile assigned."
                    }
                    return Response(json.dumps(error),
                                    status=400,
                                    mimetype='application/json; charset=utf-8')
                if needuser.createby != OldToken.get("user"):  # 如果角色不属于用户
                    model.log_yggdrasil(operational="authserver.refrush",
                                        user=User.uuid,
                                        otherargs=json.dumps({
                                            "clientToken":
                                            data.get("clientToken")
                                        }),
                                        IP=request.remote_addr,
                                        time=datetime.datetime.now(),
                                        successful=False).save()
                    error = {
                        'error':
                        "ForbiddenOperationException",
                        'errorMessage':
                        "Attempting to bind a token to a role that does not belong to its corresponding user."
                    }
                    return Response(json.dumps(error),
                                    status=403,
                                    mimetype='application/json; charset=utf-8')
                TokenSelected = model.findprofilebyid(PostProfile['id']).uuid
                IReturn['selectedProfile'] = model.format_profile(
                    model.findprofilebyid(PostProfile['id']), unsigned=True)
                Can = True

        NewAccessToken = str(uuid.uuid4()).replace('-', '')
        cache_token.set(NewAccessToken, {
            "clientToken": OldToken.get('clientToken'),
            "bind": TokenSelected,
            "user": OldToken.get("user"),
            "group": group_id,
            "createTime": int(time.time())
        },
                        ttl=config.TokenTime.RefrushTime *
                        config.TokenTime.TimeRange)

        cache_token.delete(AccessToken)
        IReturn['accessToken'] = NewAccessToken
        IReturn['clientToken'] = OldToken.get('clientToken')
        if TokenProfile and not Can:
            IReturn['selectedProfile'] = model.format_profile(TokenProfile,
                                                              unsigned=True)
        if 'requestUser' in data:
            if data['requestUser']:
                IReturn['user'] = model.format_user(User)

        User.last_login = datetime.datetime.now()
        model.log_yggdrasil(operational="authserver.refrush",
                            user=User.uuid,
                            otherargs=json.dumps(
                                {"clientToken": data.get("clientToken")}),
                            IP=request.remote_addr,
                            time=datetime.datetime.now()).save()

        return Response(json.dumps(IReturn),
                        mimetype='application/json; charset=utf-8')