def create_known_token(token, username, user, groups=None):
    known_tokens = Path(AUTH_TOKENS_FILE)
    known_tokens.parent.mkdir(exist_ok=True)
    csv_fields = ['token', 'username', 'user', 'groups']
    try:
        with known_tokens.open('r') as f:
            tokens_by_user = {r['user']: r for r in csv.DictReader(f, csv_fields)}
    except FileNotFoundError:
        tokens_by_user = {}
    tokens_by_username = {r['username']: r for r in tokens_by_user.values()}
    if (user in tokens_by_user):
        record = tokens_by_user[user]
    elif (username in tokens_by_username):
        record = tokens_by_username[username]
    else:
        record = tokens_by_user[user] = {}
    record.update({'token': token, 'username': username, 'user': user, 'groups': groups})
    if (not record['groups']):
        del record['groups']
    with known_tokens.open('w') as f:
        csv.DictWriter(f, csv_fields, lineterminator='\n').writerows(tokens_by_user.values())
def create_known_token(token, username, user, groups=None):
    known_tokens = Path(AUTH_TOKENS_FILE)
    known_tokens.parent.mkdir(exist_ok=True)
    csv_fields = ['token', 'username', 'user', 'groups']
    try:
        with known_tokens.open('r') as f:
            tokens_by_user = {r['user']: r for r in csv.DictReader(f, csv_fields)}
    except FileNotFoundError:
        tokens_by_user = {}
    tokens_by_username = {r['username']: r for r in tokens_by_user.values()}
    if (user in tokens_by_user):
        record = tokens_by_user[user]
    elif (username in tokens_by_username):
        record = tokens_by_username[username]
    else:
        record = tokens_by_user[user] = {}
    record.update({'token': token, 'username': username, 'user': user, 'groups': groups})
    if (not record['groups']):
        del record['groups']
    with known_tokens.open('w') as f:
        csv.DictWriter(f, csv_fields, lineterminator='\n').writerows(tokens_by_user.values())