using System;
using UnityEngine;
using UnityEngine.Events;
namespace Mirror
{
///
/// Unity Event for the NetworkConnection
///
[Serializable] public class UnityEventNetworkConnection : UnityEvent { }
///
/// Base class for implementing component-based authentication during the Connect phase
///
[HelpURL("https://mirror-networking.com/docs/Guides/Authentication.html")]
public abstract class NetworkAuthenticator : MonoBehaviour
{
[Header("Event Listeners (optional)")]
///
/// Notify subscribers on the server when a client is authenticated
///
[Tooltip("Mirror has an internal subscriber to this event. You can add your own here.")]
public UnityEventNetworkConnection OnServerAuthenticated = new UnityEventNetworkConnection();
///
/// Notify subscribers on the client when the client is authenticated
///
[Tooltip("Mirror has an internal subscriber to this event. You can add your own here.")]
public UnityEventNetworkConnection OnClientAuthenticated = new UnityEventNetworkConnection();
#region server
///
/// Called on server from StartServer to initialize the Authenticator
/// Server message handlers should be registered in this method.
///
public virtual void OnStartServer() { }
///
/// Called on server from OnServerAuthenticateInternal when a client needs to authenticate
///
/// Connection to client.
public abstract void OnServerAuthenticate(NetworkConnection conn);
protected void ServerAccept(NetworkConnection conn)
{
OnServerAuthenticated.Invoke(conn);
}
protected void ServerReject(NetworkConnection conn)
{
conn.Disconnect();
}
#endregion
#region client
///
/// Called on client from StartClient to initialize the Authenticator
/// Client message handlers should be registered in this method.
///
public virtual void OnStartClient() { }
///
/// Called on client from OnClientAuthenticateInternal when a client needs to authenticate
///
/// Connection of the client.
public abstract void OnClientAuthenticate(NetworkConnection conn);
protected void ClientAccept(NetworkConnection conn)
{
OnClientAuthenticated.Invoke(conn);
}
protected void ClientReject(NetworkConnection conn)
{
// Set this on the client for local reference
conn.isAuthenticated = false;
// disconnect the client
conn.Disconnect();
}
#endregion
void OnValidate()
{
#if UNITY_EDITOR
// automatically assign authenticator field if we add this to NetworkManager
NetworkManager manager = GetComponent();
if (manager != null && manager.authenticator == null)
{
manager.authenticator = this;
UnityEditor.Undo.RecordObject(gameObject, "Assigned NetworkManager authenticator");
}
#endif
}
}
}