Token persistence.

    :param token: A dictionary with the token data.
    :param request: The request instance.
    :returns: A :class:`invenio_oauth2server.models.Token` instance.

def save_token(token, request, *args, **kwargs):
    """Token persistence.

    :param token: A dictionary with the token data.
    :param request: The request instance.
    :returns: A :class:`invenio_oauth2server.models.Token` instance.
    """
    # Exclude the personal access tokens which doesn't expire.
    user = request.user if request.user else current_user

    # Add user information in token endpoint response.
    # Currently, this is the only way to have the access to the user of the
    # token as well as the token response.
    token.update(user={'id': user.get_id()})

    # Add email if scope granted.
    if email_scope.id in token.scopes:
        token['user'].update(
            email=user.email,
            email_verified=user.confirmed_at is not None,
        )

    tokens = Token.query.filter_by(
        client_id=request.client.client_id,
        user_id=user.id,
        is_personal=False,
    )

    # make sure that every client has only one token connected to a user
    if tokens:
        for tk in tokens:
            db.session.delete(tk)
        db.session.commit()

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

    tok = Token(
        access_token=token['access_token'],
        refresh_token=token.get('refresh_token'),
        token_type=token['token_type'],
        _scopes=token['scope'],
        expires=expires,
        client_id=request.client.client_id,
        user_id=user.id,
        is_personal=False,
    )
    db.session.add(tok)
    db.session.commit()
    return tok