private void OnValidateAuthTicketResponse(SteamId steamId, SteamId ownerId, AuthResponse status) { foreach (KeyValuePair <int, SteamTransport.NetworkPlayer> client in SteamTransport.instance.Server.clients) { if (client.Value.info.Identity.SteamId == steamId) { if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "Authentication Request: {0} {1}", steamId, status); } NetworkConnection conn = NetworkServer.connections[client.Key]; if (status == AuthResponse.OK) { AuthResponseMessage authResponseMessage = new AuthResponseMessage(); conn.Send(authResponseMessage); // Invoke the event to complete a successful authentication OnServerAuthenticated.Invoke(conn); return; } else { AuthResponseMessage authResponseMessage = new AuthResponseMessage(); conn.Send(authResponseMessage); // must set NetworkConnection isAuthenticated = false conn.isAuthenticated = false; // disconnect the client after 1 second so that response message gets delivered StartCoroutine(DelayedDisconnect(conn, 1)); return; } } } }
public void OnAuthenticationRequest(NetworkConnection conn, PlayerInfo msg) { conn.authenticationData = msg; // Invoke the event to complete a successful authentication OnServerAuthenticated.Invoke(conn); }
void OnServerLogin(NetworkConnection conn, LoginMsg message) { if (message.version == Application.version) { if (IsAllowedAccountName(message.account)) { if (Database.singleton.TryLogin(message.account, message.password)) { if (!AccountLoggedIn(message.account)) { manager.lobby[conn] = message.account; Debug.Log("login successful: " + message.account); conn.Send(new LoginSuccessMsg()); OnServerAuthenticated.Invoke(conn); } else { manager.ServerSendError(conn, "already logged in", true); } } else { manager.ServerSendError(conn, "invalid account", true); } } else { manager.ServerSendError(conn, "account name not allowed", true); } } else { manager.ServerSendError(conn, "outdated version", true); } }
void OnServerLogin(NetworkConnection conn, LoginMsg message) { Debug.Log("OnServer Login del NetworkAuthenticahtor"); // correct version? if (message.version == Application.version) { // allowed account name? if (IsAllowedAccountName(message.account)) { // validate account info if (Database.IsValidAccount(message.account, message.password)) { // not in lobby and not in world yet? if (!AccountLoggedIn(message.account)) { // add to logged in accounts manager.lobby[conn] = message.account; // login successful Debug.Log("login successful: " + message.account); // notify client about successful login. otherwise it // won't accept any further messages. conn.Send(new LoginSuccessMsg()); // authenticate on server OnServerAuthenticated.Invoke(conn); } else { //print("account already logged in: " + message.account); <- don't show on live server manager.ServerSendError(conn, "already logged in", true); // note: we should disconnect the client here, but we can't as // long as unity has no "SendAllAndThenDisconnect" function, // because then the error message would never be sent. //conn.Disconnect(); } } else { //print("invalid account or password for: " + message.account); <- don't show on live server manager.ServerSendError(conn, "invalid account", true); } } else { //print("account name not allowed: " + message.account); <- don't show on live server manager.ServerSendError(conn, "account name not allowed", true); } } else { //print("version mismatch: " + message.account + " expected:" + Application.version + " received: " + message.version); <- don't show on live server manager.ServerSendError(conn, "outdated version", true); } }
public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg) { if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "Authentication Request: {0} {1}", msg.authUsername, msg.authPassword); } // check the credentials by calling your web server, database table, playfab api, or any method appropriate. if (msg.authUsername == username && msg.authPassword == password) { // create and send msg to client so it knows to proceed AuthResponseMessage authResponseMessage = new AuthResponseMessage { code = 100, message = "Success" }; conn.Send(authResponseMessage); // Invoke the event to complete a successful authentication OnServerAuthenticated.Invoke(conn); } else { // create and send msg to client so it knows to disconnect AuthResponseMessage authResponseMessage = new AuthResponseMessage { code = 200, message = "Invalid Credentials" }; conn.Send(authResponseMessage); // must set NetworkConnection isAuthenticated = false conn.isAuthenticated = false; // disconnect the client after 1 second so that response message gets delivered StartCoroutine(DelayedDisconnect(conn, 1)); } }
public async void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg) { bool isValid = await loginService.Validate(msg.accessToken); if (!isValid) { StartCoroutine(DelayedDisconnect(conn, "Invalid access token.")); return; } Jwt jwt = new Jwt(msg.accessToken); string[] allowedUserIds = GameState.singleton.gameServerModel.allowedUserIds; if (allowedUserIds.Length > 0 && !allowedUserIds.Contains(jwt.payload.user._id)) { StartCoroutine(DelayedDisconnect(conn, "User not allowed.")); return; } Debug.Log("User is allowed."); // Set authenticationData for other scripts to use. GroupModel groupModel = await GetGroupModel(msg.groupId, jwt.payload.user._id); conn.authenticationData = new AuthenticationData { groupModel = groupModel, userModel = jwt.payload.user }; // Create and send msg to client so it knows to proceed. AuthResponseMessage authResponseMessage = new AuthResponseMessage { code = 200, message = "Success" }; conn.Send(authResponseMessage); OnServerAuthenticated.Invoke(conn); }
/// <summary> /// Called on server from OnServerAuthenticateInternal when a client needs to authenticate /// </summary> /// <param name="conn">Connection to client.</param> public virtual void OnServerAuthenticate(INetworkConnection conn) { OnServerAuthenticated?.Invoke(conn); }
public void Awake() { authenticator.OnServerAuthenticated.AddListener(connection => OnServerAuthenticated.Invoke(connection)); authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated.Invoke); }
/// <summary> /// Called on server from OnServerAuthenticateInternal when a client needs to authenticate /// </summary> /// <param name="player">Connection to client.</param> public virtual void OnServerAuthenticate(INetworkPlayer player) { OnServerAuthenticated?.Invoke(player); }
/// <summary> /// Call this when player has been accepted on the server /// </summary> /// <param name="player"></param> protected void ServerAccept(INetworkPlayer player) { player.IsAuthenticated = true; OnServerAuthenticated?.Invoke(player); }
public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg) { if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "Authentication Request: ticket {0}", msg.ticketString); } TimedTicket t = new TimedTicket(); try { t.Parse(msg.ticketString); } catch (Exception e) { if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "Error parsing: ticket {0}: {1}", msg.ticketString, e); } sendError(conn, 200, "Could not parse ticket"); return; } DateTime now = DateTime.UtcNow; // check the ticket if (t.ServerCurrentAndValid(eventName, now, getServerKey())) { // update for any recently disconnected cliens CheckCurrentSeatConnections(); int numAuthenticated = NetworkServer.connections.Count(kv => kv.Value.isAuthenticated); SeatInfo si = null; if (t.seat != WILDCARD_SEAT) { // if a non-wildcard user joins and they are not kicking // someone then eject wildcard users in LIFO(?) order // check/assign seat if (!seats.ContainsKey(t.seat)) { // new seat si = new SeatInfo { wildcard = false, seat = t.seat, ticket = t, conn = conn }; seats.Add(t.seat, si); if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "Assigned new seat {0} to connection {1}", t.seat, conn.connectionId); } // kick wildcard users if necessary if (numAuthenticated >= maxSeats) { if (!KickWildcardSeats(numAuthenticated + 1 - maxSeats)) { // do we block numbered seats at the quota?! // just note that people shouldn't send out // more seats than set! } } } else { si = seats[t.seat]; if (si.conn != null) { if (t.durationMinutes > si.ticket.durationMinutes) { // current occupant has shorter duration => precedence if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "Current seat {0} holder has precedence, {1} vs {2} minutes", si.seat, si.ticket.durationMinutes, t.durationMinutes); } sendError(conn, 200, "Seat is temporarily in use"); return; } if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "Kick connection {0} from seat {1}, valid? {2}", si.conn.connectionId, si.seat, si.ticket.ServerCurrentAndValid(eventName, now, getServerKey())); } sendError(si.conn, 201, String.Format("Someone else has taken seat {0}", t.seat)); } si.ticket = t; si.conn = conn; if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "Assigned existing seat {0} to connection {1}", t.seat, conn.connectionId); } } } else { // would we need to kick a wildcard with longer duration? if (numAuthenticated >= maxSeats || wildcardSeats.Count >= maxWildcardSeats) { // kick a wildcard with longer duration?! if (wildcardSeats.Count > 0 && wildcardSeats[wildcardSeats.Count - 1].ticket.durationMinutes > t.durationMinutes) { if (KickWildcardSeats(1)) { // that made a space! numAuthenticated--; } else { if (logger.LogEnabled()) { logger.LogFormat(LogType.Error, "Unable to kick long duration wildcard"); } } } } // add a wildcard user if there is space. if (numAuthenticated >= maxSeats || wildcardSeats.Count >= maxWildcardSeats) { if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "No capacity for new wildcard seat, {0}/{1} and {2}/{3} total", wildcardSeats.Count, maxWildcardSeats, numAuthenticated, maxSeats); } sendError(conn, 200, "No space available"); return; } // new seat si = new SeatInfo { wildcard = true, seat = t.seat + (nextWildcardSeat++), ticket = t, conn = conn }; // keep in increasing duration order, so longer tickets are kicked first int shorter = wildcardSeats.Count(s => (s.ticket.durationMinutes <= t.durationMinutes)); wildcardSeats.Insert(shorter, si); if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "Assigned new seat {0} to connection {1}", si.seat, conn.connectionId); } } // OK conn.authenticationData = t; // create and send msg to client so it knows to proceed AuthResponseMessage authResponseMessage = new AuthResponseMessage { code = 100, message = "Success" }; conn.Send(authResponseMessage); // check expire... if (si != null) { StartCoroutine(MonitorTicketExpired(conn, si)); } // Invoke the event to complete a successful authentication OnServerAuthenticated.Invoke(conn); } else { sendError(conn, 200, "Invalid Credentials"); } }
//Server Request to check if account exists or if it needs to be created public void OnServerLogin(NetworkConnection conn, AuthRequestMessage msg) { if (logger.LogEnabled()) { logger.LogFormat(LogType.Log, "Authentication Request: {0} {1}", msg.authUsername, msg.authPassword); } // check the credentials by calling your web server, database table, playfab api, or any method appropriate. if (File.Exists(accountStreamPath + msg.authUsername + ".json")) { Account acc; using (StreamReader stream = new StreamReader(accountStreamPath + msg.authUsername + ".json")) { string json = stream.ReadToEnd(); acc = JsonUtility.FromJson <Account>(json); } if (msg.authUsername == acc.userLogin && msg.authPassword == acc.userPassword) { Debug.Log("Successful authentication"); AuthResponseMessage authResponseMessage = new AuthResponseMessage { code = 100, message = "Success", id = acc.id, username = acc.userLogin, characters = acc.characters }; conn.Send(authResponseMessage); // Invoke the event to complete a successful authentication OnServerAuthenticated.Invoke(conn); } else { Debug.Log("Wrong password"); AuthResponseMessage authResponseMessage = new AuthResponseMessage { code = 200, message = "Invalid Credentials" }; conn.Send(authResponseMessage); // must set NetworkConnection isAuthenticated = false conn.isAuthenticated = false; // disconnect the client after 1 second so that response message gets delivered StartCoroutine(DelayedDisconnect(conn, 1)); } } else { Debug.Log("File not Exists...Creating file"); string[] chars = { }; Account newAccount = new Account(msg.authUsername, msg.authPassword, Directory.GetFiles(accountStreamPath, "*", SearchOption.TopDirectoryOnly).Length, chars); using (StreamWriter stream = new StreamWriter(accountStreamPath + msg.authUsername + ".json")) { string json = JsonUtility.ToJson(newAccount, false); stream.Write(json); } Debug.Log("Successful Creation"); AuthResponseMessage authResponseMessage = new AuthResponseMessage { code = 100, message = "Success", id = newAccount.id, username = newAccount.userLogin, characters = newAccount.characters }; conn.Send(authResponseMessage); // Invoke the event to complete a successful authentication OnServerAuthenticated.Invoke(conn); } }
public override void OnAwake() { base.OnAwake(); authenticator.OnServerAuthenticated += (connection => OnServerAuthenticated.Invoke(connection)); authenticator.OnClientAuthenticated += (connection => OnClientAuthenticated.Invoke(connection)); }