Exemple #1
0
def reset_password_confirmed(request):
    if request.method != 'POST':
        raise PermissionDenied
    uid = request.GET.get('uid')
    uid = sanitize_get_param(uid)
    logged_user = request.zeususer._user
    user = get_user(uid)
    if user:
        if can_do(logged_user, user):
            new_password = random_password()
            user.info['password'] = make_password(new_password)
            user.save()
            message = _("New password for user %(uid)s is "
                        "%(new_pass)s") % {
                            'uid': user.user_id,
                            'new_pass': new_password
                        }
            messages.info(request, message)
        else:
            message = _("You are not authorized to do this")
            messages.error(request, message)
    else:
        message = _("You didn't choose a user")
        messages.error(request, message)
        return redirect(reverse('list_users'))
    url = "%s?uid=%s" % (reverse('user_management'), str(user.id))
    return redirect(url)
Exemple #2
0
def create_user(request):
    users = User.objects.all()
    inst_id = sanitize_get_param(request.GET.get('id'))
    institution = get_institution(inst_id)
    edit_id = sanitize_get_param(request.GET.get('edit_id'))
    edit_user = get_user(edit_id)
    logged_user = request.zeususer._user
    if edit_user:
        if not can_do(logged_user, edit_user):
            raise PermissionDenied
    if edit_user:
        initial = {'institution': edit_user.institution.name}
    elif institution:
        initial = {'institution': institution.name}
    else:
        initial = None
    form = None

    if request.method == 'POST':
        form = userForm(logged_user,
                        request.POST,
                        initial=initial,
                        instance=edit_user)
        if form.is_valid():
            user, password = form.save()
            if edit_user:
                message = _("Changes on user were successfully saved")
            else:
                message = _("User %(uid)s was created with"
                            " password %(password)s.")\
                            % {'uid': user.user_id, 'password': password}
            messages.success(request, message)
            url = "%s?uid=%s" % (reverse('user_management'), \
                str(user.id))
            return redirect(url)

    if request.method == 'GET':
        form = userForm(logged_user, initial=initial, instance=edit_user)

    tpl = 'account_administration/create_user',
    context = {'form': form}
    return render_template(request, tpl, context)
Exemple #3
0
def create_user(request):
    users = User.objects.all()
    inst_id = sanitize_get_param(request.GET.get('id'))
    institution = get_institution(inst_id)
    edit_id = sanitize_get_param(request.GET.get('edit_id'))
    edit_user = get_user(edit_id)
    logged_user = request.zeususer._user
    if edit_user:
        if not can_do(logged_user, edit_user):
            edit_user = None
    if edit_user:
        initial = {'institution': edit_user.institution.name}
    elif institution:
        initial = {'institution': institution.name}
    else:
        initial = None
    form = None

    if request.method == 'POST':
        form = userForm(request.POST, initial=initial, instance=edit_user)
        if form.is_valid():
            user, password = form.save()
            if edit_user:
                message = _("Changes on user were successfully saved")
            else:
                message = _("User %(uid)s was created with"
                            " password %(password)s.")\
                            % {'uid': user.user_id, 'password': password}
            messages.success(request, message)
            url = "%s?uid=%s" % (reverse('user_management'), \
                str(user.id))
            return redirect(url)

    if request.method == 'GET':
        form = userForm(initial=initial, instance=edit_user)

    tpl = 'account_administration/create_user',
    context = {'form': form}
    return render_template(request, tpl, context)
Exemple #4
0
def reset_password_confirmed(request):
    uid = request.GET.get('uid')
    uid = sanitize_get_param(uid)
    logged_user = request.zeususer._user
    user = get_user(uid)
    if user:
        if can_do(logged_user, user):
            new_password = random_password()
            user.info['password'] = make_password(new_password)
            user.save()
            message = _("New password for user %(uid)s is "
                        "%(new_pass)s") % {'uid': user.user_id,
                                           'new_pass': new_password}
            messages.info(request, message)
        else:
            message = _("You are not authorized to do this")
            messages.error(request, message)
    else:
        message = _("You didn't choose a user")
        messages.error(request, message)
        return redirect(reverse('list_users'))
    url = "%s?uid=%s" % (reverse('user_management'),
                                   str(user.id))
    return redirect(url)
Exemple #5
0
async def on_message(message):
    if message.author.bot: return

    # Check for player
    player = game.get_player(message.author.id)
    if player is None:
        player = game.new_player(message.author.id, message.author.name)

    # Dropout because we're running in private mode
    if get_setting(settings, 'private-mode',
                   False) and not player.has_role('operator'):
        return

    # Only respond if this is an explicit command [first character is a $] or if bot gets pinged and it is a command
    if message.clean_content.startswith('$') or (
            client.user in message.mentions and '$' in message.clean_content):
        s = message.clean_content.find('$')
        cmds = shlex.split(message.clean_content[s + 1:])

        command = utils.get_alias(cmds[0])

        if command is None:
            print('Failed to interpret command {0}.'.format(cmds[0]))
        elif not utils.can_do(command, player.roles):
            print('Player tried to execute command {0} without permission.'.
                  format(cmds[0]))
        else:
            print('Running command {0}.'.format(command))

            if command == 'help':
                if len(cmds) > 1:
                    cmd = utils.get_alias(cmds[1])
                    desc = utils.get_help(cmd, player.roles)
                else:
                    desc = utils.get_help(command, player.roles)
                respondqueue.put({'to': message.channel, 'message': desc})
            elif command == 'all':
                desc = utils.get_all(player.roles)
                respondqueue.put({'to': message.author, 'message': desc})
            elif command == 'save':
                game.save(gamefile)
                banking.queue.put({'type': 'save'})
                respondqueue.put({
                    'to': message.author,
                    'message': 'Executing full save.'
                })
            elif command == 'stop':
                await client.logout()

                game.save(gamefile)
                banking.queue.put({'type': 'save'})

                banking.stop()
                manager.stop()

                client.loop.call_soon(sys.exit, 0)
            elif command == 'kill':
                await client.logout()

                banking.stop()
                manager.stop()

                client.loop.call_soon(sys.exit, 0)
            elif command == 'roles':
                if len(cmds) > 1:
                    tgt = game.get_player(cmds[1])
                else:
                    tgt = player

                if tgt is None:
                    respondqueue.put({
                        'to':
                        message.channel,
                        'message':
                        'Cannot find player *{0}*'.format(cmds[1])
                    })
                elif len(tgt.roles) == 0:
                    respondqueue.put({
                        'to':
                        message.channel,
                        'message':
                        '*{0}* has no roles.'.format(tgt.username)
                    })
                else:
                    reply = '*{0}*\'s roles:'.format(tgt.username)
                    for i, r in enumerate(tgt.roles):
                        if r.term_length.total_seconds() > 0:
                            reply += '\n{0}. **{1}** [runs out {2}]'.format(
                                i + 1, r.name.capitalize(),
                                r.term_end.strftime('%d-%m'))
                        else:
                            reply += '\n{0}. **{1}**'.format(
                                i + 1, r.name.capitalize())

                    respondqueue.put({'to': message.channel, 'message': reply})
            elif command == 'addrole':
                if len(cmds) < 3:
                    respondqueue.put({
                        'to':
                        message.channel,
                        'message':
                        'Usage: `{0}`'.format(utils.cmds[command]['example'])
                    })
                    return

                tgt = game.get_player(cmds[1])
                role = Role(cmds[2])

                if tgt.has_role(role):
                    respondqueue.put({
                        'to':
                        message.channel,
                        'message':
                        'Player {0} already has role {1}'.format(
                            tgt.username, role.name)
                    })
                    return

                role.term_start = datetime.datetime.now()
                if len(cmds) < 4:
                    role.term_length = datetime.timedelta(days=-1)
                else:
                    try:
                        role.term_length = datetime.datetime.strptime(
                            cmds[3], '%d-%m-%Y') - role.term_start
                    except Exception as e:
                        respondqueue.put({
                            'to':
                            message.author,
                            'message':
                            'Failed to interpret date format: {0}'.format(
                                str(e))
                        })
                        return

                tgt.roles.append(role)
                respondqueue.put({
                    'to':
                    message.channel,
                    'message':
                    'Gave role {0} to player {1}'.format(
                        role.name, tgt.username)
                })
            elif command == 'delrole':
                if len(cmds) < 3:
                    respondqueue.put({
                        'to':
                        message.channel,
                        'message':
                        'Usage: `{0}`'.format(utils.cmds[command]['example'])
                    })
                    return

                tgt = game.get_player(cmds[1])
                role = Role(cmds[2])

                if not tgt.has_role(role):
                    respondqueue.put({
                        'to':
                        message.channel,
                        'message':
                        'Player {0} does not have role {1}'.format(
                            tgt.username, role.name)
                    })
                    return

                tgt.remove_role(role)
                respondqueue.put({
                    'to':
                    message.channel,
                    'message':
                    'Removed role {0} from player {1}'.format(
                        role.name, tgt.username)
                })
            elif command == 'newaccount':
                if len(cmds) < 2:
                    respondqueue.put({
                        'to':
                        message.channel,
                        'message':
                        'Usage: `{0}`'.format(utils.cmds[command]['example'])
                    })
                    return

                banking.queue.put({
                    'type': 'new',
                    'pid': player.uid,
                    'name': cmds[1],
                    'channel': message.channel
                })
            elif command == 'balance':
                banking.queue.put({
                    'type': 'balance',
                    'pid': player.uid,
                    'channel': message.channel
                })
            elif command == 'transfer':
                if len(cmds) < 4:
                    respondqueue.put({
                        'to':
                        message.channel,
                        'message':
                        'Usage: `{0}`'.format(utils.cmds[command]['example'])
                    })
                    return

                fromid = cmds[1]
                toid = cmds[2]
                amount = cmds[3]
                details = ''
                if len(cmds) > 4: details = cmds[4]

                targets = []

                for u in banking.get_owners(fromid):
                    user = await client.get_user_info(u)
                    if not user in targets:
                        targets.append(user)
                for u in banking.get_owners(toid):
                    user = await client.get_user_info(u)
                    if not user in targets:
                        targets.append(user)

                banking.queue.put({
                    'type': 'transfer',
                    'pid': player.uid,
                    'from': fromid,
                    'to': toid,
                    'amount': amount,
                    'details': details,
                    'channel': targets
                })
            elif command == 'veterans':
                if message.channel.is_private:
                    respondqueue.put({
                        'to':
                        message.channel,
                        'message':
                        'You need to use this command in a server.'
                    })
                    return

                print_all = False
                if len(cmds) > 1:
                    if cmds[1] == 'all' and player.has_role('operator'):
                        print_all = True

                people = []
                names = []
                joined = []

                for m in message.server.members:
                    people.append(m.id)
                    names.append(m.name)
                    joined.append(m.joined_at)

                people = [p for _, p in sorted(zip(joined, people))]
                names = [p for _, p in sorted(zip(joined, names))]
                joined = sorted(joined)

                res = None
                if print_all:
                    res = []

                    for i in range(len(people)):
                        addition = '{0:2d}. {1} ({2})\n'.format(
                            i + 1, names[i], joined[i].strftime('%d-%m-%Y'))
                        if len(res) == 0:
                            res = ['```' + addition]
                        elif len(res[-1]) + len(addition) < 1500:
                            res[-1] += addition
                        else:
                            res[-1] += '```'
                            res.append('```' + addition)

                    res[-1] += '```'
                else:
                    res = '```'
                    for i in range(10):
                        res += '{0:2d}. {1} ({2})\n'.format(
                            i + 1, names[i], joined[i].strftime('%d-%m-%Y'))

                    i = people.index(message.author.id)
                    if i > 10:
                        res += '...\n{0:2d}. {1} ({2})\n'.format(
                            i, names[i - 1],
                            joined[i - 1].strftime('%d-%m-%Y'))
                    res += '{0:2d}. {1} ({2})\n'.format(
                        i + 1, names[i], joined[i].strftime('%d-%m-%Y'))
                    if i + 1 < len(people):
                        res += '{0:2d}. {1} ({2})\n'.format(
                            i + 2, names[i + 1],
                            joined[i + 1].strftime('%d-%m-%Y'))
                    if i + 2 < len(people): res += '...'
                    res += '```'

                respondqueue.put({'to': message.channel, 'message': res})