public override Guid OnPlayerConnectionRequest(ServerUser player, ref string msg) { // only allow players on the game server if we have a character selection if (player.CurrentCharacter == null) { return Guid.Empty; } return base.OnPlayerConnectionRequest(player, ref msg); }
public static void sendToClan(virtualUser User, Packet p) { foreach (virtualUser ServerUser in UserManager.getAllUsers()) { if (ServerUser.ClanID == User.ClanID && ServerUser.ClanRank != -1) // Check for clan id { ServerUser.send(p); } } }
public bool Register(ServerUser user) { if (manager.Register(user)) { OnLineUsers.Add(Context.ConnectionId, user); Clients.All.UpdateUsersList(OnLineUsers.Values.Select(u => u.UserName).ToArray()); return(true); } return(false); }
public ServerUser CreateAndGetServerUser(Int32 IDServer, Int32 IDUser) { var SU = new ServerUser() { IDServer = IDServer, IDUser = IDUser }; this.ServerUser.Add(SU); return(SU); }
public async void SetBookmarksCount() { await((HomeLayout)App.Current.MainPage).SetLoading(true, "Loading your bookmarks..."); user = App.serverData.mei_user.currentUser; peopleBCount.Text = (await BaseFunctions.GetPeopleCount(user.userBookmarks.people)).ToString(); sessionsBCount.Text = (await BaseFunctions.GetSessionCount(user.userBookmarks.session)).ToString(); speakersBCount.Text = (await BaseFunctions.GetSpeakersCount(user.userBookmarks.speakers)).ToString(); exhibitorsBCount.Text = (await BaseFunctions.GetExhibitorsCount(user.userBookmarks.exhibitors)).ToString(); sponsorsBCount.Text = (await BaseFunctions.GetSponsorsCount(user.userBookmarks.sponsors)).ToString(); await((HomeLayout)App.Current.MainPage).SetLoading(false, "Loading event sessions..."); }
public void SetShippingDetails() { currentUser = App.serverData.mei_user.currentUser; if (currentUser != null) { billingInformation = App.serverData.mei_user.userAddressList[shippingIndex]; shippingFirstName.Text = billingInformation.firstName; shippingLastName.Text = billingInformation.lastName; shippingAddressLine1.Text = billingInformation.addressLine1; if (!string.IsNullOrEmpty(billingInformation.addressLine2)) { shippingAddressLine2.Text = billingInformation.addressLine2; } else { shippingAddressLine2.IsVisible = false; } shippingCity.Text = billingInformation.city; shippingState.Text = billingInformation.state; shippingZipCode.Text = billingInformation.postalCode; if (!string.IsNullOrEmpty(billingInformation.addressLine2)) { currentTransaction.transactionShippingAddress = shippingAddressLine1.Text + "," + shippingAddressLine2.Text + "," + shippingCity.Text + "," + shippingState.Text + "," + shippingZipCode.Text; } else { currentTransaction.transactionShippingAddress = shippingAddressLine1.Text + "," + shippingCity.Text + "," + shippingState.Text + "," + shippingZipCode.Text; } } if (App.serverData.mei_user.userAddressList.Count > 1) { if (shippingIndex == App.serverData.mei_user.userAddressList.Count - 1) { nextAddress.IsVisible = false; } else { nextAddress.IsVisible = true; } if (shippingIndex == 0) { previousAddress.IsVisible = false; } else { previousAddress.IsVisible = true; } } else { nextAddress.IsVisible = false; previousAddress.IsVisible = false; } }
protected override bool OnCharacterDeleting(SqlConnection con, SqlTransaction tran, int characterId, ServerUser owner) { bool rslt = CharacterUtil.Instance.DeleteCharacter_TSRating(characterId, con, tran); if (rslt) { return base.OnCharacterDeleting(con, tran, characterId, owner); } return false; }
public bool Register(ServerUser user) { if (Manger.IsUserExist(user)) { return(false); } else { Manger.AddUser(new ServerUser(user.UserName, user.Password)); return(true); } }
/// <summary> 踢出用户 /// </summary> void UCOnLineUser_ShotoffEvent(object sender, EventArgs e) { try { if (cmbacc.SelectedIndex == 0) { MessageBoxEx.ShowInformation("请选择所属账套"); return; } Dictionary <string, string> dic = new Dictionary <string, string>(); foreach (DataGridViewRow dr in dgvUser.Rows) { object isCheck = dr.Cells["colCheck"].EditedFormattedValue; if (isCheck != null && (bool)isCheck) { string userid = dr.Cells["user_id"].Value.ToString(); if (!dic.ContainsKey("userid")) { dic.Add(userid, dr.Cells["land_name"].Value.ToString()); } } } if (dic.Keys.Count == 0) { MessageBoxEx.ShowInformation("请选择踢出用户!"); return; } if (MessageBoxEx.ShowQuestion("你确定要将选中用户踢出系统吗?")) { string accCode = cmbacc.SelectedValue.ToString(); foreach (string str in dic.Keys) { LoginSessionInfo.Instance.ShotOffUser(accCode, str); if (accCode == GlobalStaticObj_Server.CommAccCode) { ClientUser.UserLoginOut(dic[str], accCode); } else { ServerUser.UserLoginOut(dic[str], accCode); } } } MessageBoxEx.ShowInformation("操作成功"); } catch (Exception ex) { GlobalStaticObj_Server.GlobalLogService.WriteLog("在线用户", ex); MessageBoxEx.ShowWarning("程序异常"); } }
/// <summary> /// Returns all user data using a token for verification /// </summary> public async Task <TaskResult <User> > GetUserWithToken(string token) { AuthToken authToken = await Context.AuthTokens.FindAsync(token); if (authToken == null) { return(new TaskResult <User>(false, "Failed to verify token.", null)); } ServerUser user = await Context.Users.FindAsync(authToken.User_Id); return(new TaskResult <User>(true, "Retrieved user.", user)); }
public async Task LeaveServerAsync(int serverId, int userId) { ServerUser serverUser = await mainDatabase.ServerUser.Where(su => su.UserId == userId && su.ServerId == serverId).FirstOrDefaultAsync(); mainDatabase.ServerUser.Remove(serverUser); await mainDatabase.SaveChangesAsync(); await Groups.RemoveFromGroupAsync(Context.ConnectionId, MakeServerGroupId(serverId)); await Clients.Caller.SendAsync("ReceiveLeaveServerSignal", serverId); await Clients.Group(MakeServerGroupId(serverId)).SendAsync("ReceiveOtherUserLeaveServerSignal", userId, serverUser.RoleId); }
public async Task EnsureCreated(IUser user, IGuild guild) { var(serverCreated, userCreated) = (false, false); var server = await _serverRepository.FindAsync(guild.Id, (qry, ctx) => qry.Include(s => s.ServerBotRoles)); if (server == null) { var botRoles = await _botRoleRepository.GetAsync(); server = new Server { Id = guild.Id, ServerBotRoles = botRoles.Select(role => new ServerBotRole { Role = role }).ToList() }; await _serverRepository.PostAsync(server); serverCreated = true; } var userEntity = await _userRepository.FindAsync(user.Id); if (userEntity == null) { userEntity = new User { Id = user.Id, }; await _userRepository.PostAsync(userEntity); userCreated = true; } if (serverCreated || userCreated) { var botRole = user.Id != _config.OwnerId ? server.ServerBotRoles.FirstOrDefault(br => br.RoleId == (int)BotRoleLevel.User) : server.ServerBotRoles.FirstOrDefault(br => br.RoleId == (int)BotRoleLevel.Owner); var serverUser = new ServerUser { Role = botRole, Server = server, User = userEntity }; await _serverUserRepository.PostAsync(serverUser); await _serverUserRepository.SaveAllChangesAsync(); } }
public void Disconnect_CreateUserAddUserToListOfUsersAndDisconnect_UserDisconnectedAndDefault() { ServiceChat sChat = new ServiceChat(); ServerUser userPetro = new ServerUser() { ID = 3, Name = "Petro", operationContext = OperationContext.Current }; sChat.users.Add(userPetro); sChat.Disconnect(userPetro.ID); Assert.AreEqual(default, sChat.users.FirstOrDefault(i => i.ID == userPetro.ID));
public async Task <PhraseItem> AddReviewAsync([NotNull] PhraseItem phrase, [NotNull] ServerUser user, [NotNull] PostReviewRequest request) { var reviewState = new ReviewState { Comment = request.Comment, State = request.Status, UserId = user.Id }; var cloned = phrase.Clone(); cloned.Version++; UpdateReviewStates(cloned, reviewState, user.Id, request.ClearReview); await CloseAndInsertAsync(cloned, phrase, user.Id); return(cloned); }
public override async Task Execute(string[] args, SocketMessage message) { ServerUser user = DBUtil.UserFromMessage(message); if ((user.CookieCount) != 69d) { await message.Channel.SendMessageAsync("", false, EmbedUtil.GetEmbed("You do not possess " + 69d + " in your jar so this operation cannot be completed")); } else { user.CookieCount -= double.PositiveInfinity; await message.Channel.SendMessageAsync("", false, EmbedUtil.GetEmbed("Welcome to the club :wink:\n" + 69d + " Cookies have been taked from your jar")); } }
public async Task ChangeUserRole(int userId, int serverId, int newRoleId) { ServerUser serverUser = await mainDatabase.ServerUser.Where(su => su.ServerId == serverId && su.UserId == userId).FirstOrDefaultAsync(); if (serverUser == null) { return; } int oldRoleId = serverUser.RoleId; serverUser.RoleId = newRoleId; await mainDatabase.SaveChangesAsync(); await Clients.Group(MakeServerGroupId(serverId)).SendAsync("ReceiveChangeUserRoleSignal", userId, oldRoleId, newRoleId); }
public string GetSort(ServerUser s) { if (s != null) { if (s.userLastName != null) { return(s.userLastName); } else { return(s.userFirstName); } } return(string.Empty); }
private void ConnectionFromServer(object sender, RoutedEventArgs e) { if (SerchServers.SelectedIndex == -1) { return; } var server = SerchServersList[SerchServers.SelectedIndex]; var SU = new ServerUser() { IDServer = server.ID, IDUser = User.ID, StatusObj = StatusObj.Add, Name = User.Name }; SendMessageToServer.SendMessageSerialize(SU); }
public void Execute(ServerUser su) { var room = su.Room; if (room != null) { if (Pms != null) { room.Prepare(su, Pms); } else { room.UnPrepare(su); } } }
public async Task <IActionResult> Edit(int id, [Bind("Id,Name,Description,ServerUsername,ServerPassword,User,Date,Enable")] ServerUser serverUser) { if (id != serverUser.Id) { return(NotFound()); } try { serverUser.Date = DateTime.Now; serverUser.User = User.Identity.Name; if (serverUser.ServerUsername != null) { serverUser.ServerUsername = GALibrary.GACrypto.Base64Encode(serverUser.ServerUsername); } if (serverUser.ServerPassword != null) { serverUser.ServerPassword = GALibrary.GACrypto.Base64Encode(serverUser.ServerPassword); } else { String serverUserPassword = _context.ServerUser.AsNoTracking().First(x => x.Id == id).ServerPassword.Clone().ToString(); serverUser.ServerPassword = serverUserPassword; } if (ModelState.IsValid) { _context.Update(serverUser); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewBag.ServerUserEnabled = new SelectList(new[] { new { ID = true, Name = "Sim" }, new { ID = false, Name = "Não" }, }, "ID", "Name", serverUser.Enable); GALibrary.GALogs.SaveLog("ServerUser", "Fim da edicao do usuario " + serverUser.Name + " realizada pelo usuario " + User.Identity.Name, 2, _context.Parameter.FirstOrDefault()); return(View(serverUser)); } catch (Exception erro) { GALibrary.GALogs.SaveLog("ServerUser", "Erro ao editar usuario " + serverUser.Name + " pelo usuario " + User.Identity.Name + ": " + erro.ToString(), 1, _context.Parameter.FirstOrDefault()); return(View("~/Views/Shared/Error.cshtml")); } }
public async Task <IActionResult> ChangeUserRole(ChangeUserRoleViewModel model) { if (model == null) { return(BadRequest()); } ServerUser serverUser = await _context.ServerUser.Where(su => su.ServerId == model.ServerId && su.UserId == model.UserId).FirstOrDefaultAsync(); if (serverUser == null) { return(NotFound(model)); } serverUser.RoleId = model.NewRoleId; await _context.SaveChangesAsync(); return(Ok(serverUser)); }
// Метод подключения public void Connect() { // Если ещё не подключены, создаём пользователя, заносим в него данные и отправляем его сервису. Получаем обратно назначенный ИД if (!IsConnected) { ServerUser user = new ServerUser { Name = tbUserName.Text, Room = cmbGroup.SelectedIndex, Color = (NameColor)cmbColor.SelectedIndex }; id = client.Connect(user); tbUserName.IsEnabled = false; btnConnect.Content = "Отключиться"; IsConnected = true; } }
public async void ChangePasswordOnServer(object sender, EventArgs e) { if (string.IsNullOrEmpty(oldpassword.Text)) { await((HomeLayout)App.Current.MainPage).DisplayAlert("Alert", "Old password field is empty", "OK"); return; } if (string.IsNullOrEmpty(newpassword.Text)) { await((HomeLayout)App.Current.MainPage).DisplayAlert("Alert", "New Password field is empty", "OK"); return; } try { string address = "http://www.myeventit.com/PHP/ChangePassword.php/"; var client = App.serverData.GetHttpClient(); ServerUser user = App.serverData.mei_user.currentUser; string userString = JsonConvert.SerializeObject(user); var postData = new List <KeyValuePair <string, string> >(); postData.Add(new KeyValuePair <string, string>("user", userString)); postData.Add(new KeyValuePair <string, string>("newpassword", newpassword.Text)); postData.Add(new KeyValuePair <string, string>("oldpassword", oldpassword.Text)); HttpContent content = new FormUrlEncodedContent(postData); CancellationToken c = new CancellationToken(); HttpResponseMessage result = await client.PostAsync(address, content, c); var isRegistered = await result.Content.ReadAsStringAsync(); if (isRegistered.ToString() == "true") { await((HomeLayout)App.Current.MainPage).DisplayAlert("Alert", "Your password has been changed", "OK"); return; } else { await((HomeLayout)App.Current.MainPage).DisplayAlert("Alert", "Old password is wrong", "OK"); return; } } catch (Exception exception) { await App.Current.MainPage.DisplayAlert("Alert", "Something went wrong please retry..", "Ok"); } }
void LoadUserProfiles() { string[] filePaths = Directory.GetFiles($"{workspace}/userdata"); foreach (string path in filePaths) { try { ServerUser user = ServerUser.CreateFromJson( JsonSharp.JsonObject.Parse(File.ReadAllText(path)) ); users.TryAdd(user.username, user); } catch (Exception ex) { ScreenIO.Error($"Error occured while loading user profile \"{path}\": {ex.Message}"); } } }
public bool LogIn(ServerUser user) { if (manager.IsUserExist(user)) { if (!OnLineUsers.Any(p => p.Value.UserName == user.UserName && p.Value.Password == user.Password)) { OnLineUsers.Add(Context.ConnectionId, user); Clients.All.UpdateUsersList(OnLineUsers.Values.Select(u => u.UserName).ToArray()); return(true); } Clients.All.UpdateUsersList(OnLineUsers.Values.Select(u => u.UserName).ToArray()); return(false); } else { return(false); } }
public LobbyTesting() { ServerLobby lobby = new ServerLobby(); ServerUser host = new ServerUser("host", false,null); Room room; Console.WriteLine("---------create room------------"); lobby.CreateRoom(host, "testRoom", true, "asdqwe", out room); PrintLobby(lobby); Console.WriteLine("---------create room--------------"); lobby.CreateRoom(host, "testRoom2", false, "", out room); lobby.CreateRoom(host, "testRoom3", false, "", out room); PrintLobby(lobby); string lobbyDataString = JsonConvert.SerializeObject(lobby.Serialize(), new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); Lobby resultLobby = JsonConvert.DeserializeObject<Lobby>(lobbyDataString, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); PrintLobby(resultLobby); Console.WriteLine("Lobby test end"); Console.Read(); }
/// <summary> /// Will return the auth object for a valid token, including the user. /// This will log the access time in the user object. /// A null response means the token was invalid. /// </summary> public static async Task <ServerAuthToken> TryAuthorize(string token, ValourDB db) { if (token == null) { return(null); } ServerAuthToken authToken = null; if (QuickCache.ContainsKey(token)) { authToken = QuickCache[token]; } else { authToken = await db.AuthTokens.FindAsync(token); QuickCache.TryAdd(token, authToken); } // Spin off a task to do things we don't want to wait on var t = Task.Run(async() => { using (ValourDB tdb = new ValourDB(ValourDB.DBOptions)) { if (authToken == null) { authToken = await tdb.AuthTokens.FindAsync(token); } if (authToken != null) { ServerUser user = await tdb.Users.FindAsync(authToken.User_Id); user.Last_Active = DateTime.UtcNow; await tdb.SaveChangesAsync(); } } }); return(authToken); }
internal PhraseItem ToPhraseItem([NotNull] ServerUser authorUser, [NotNull] PhraseItem existingPhrase) { var newReviewStates = new List <ReviewState>(); foreach (var state in existingPhrase.ReviewStates) { if (state.UserId == authorUser.Id) { newReviewStates.Add(new ReviewState { UserId = authorUser.Id, State = State.Accept, Comment = Comment }); } else { newReviewStates.Add(ClearReview ? new ReviewState { UserId = state.UserId, State = State.Unknown } : state.Clone()); } } if (!newReviewStates.Select(s => s.UserId).Contains(authorUser.Id)) { newReviewStates.Add(new ReviewState { UserId = authorUser.Id, State = State.Accept, Comment = Comment }); } var phraseItem = new PhraseItem { PackId = existingPhrase.PackId, Phrase = Phrase, Complexity = Complexity, Description = Description, Version = existingPhrase.Version + 1, TrackId = existingPhrase.TrackId, CreatedById = authorUser.Id, CreatedDate = DateTime.Now, ReviewStates = newReviewStates }; return(phraseItem); }
private void SeedUsers() { var zhadko = new ServerUser { UserName = "******" }; var fomin = new ServerUser { UserName = "******" }; var sivykh = new ServerUser { UserName = "******" }; var tatarintsev = new ServerUser { UserName = "******" }; _userManager.CreateAsync(zhadko, _configuration["zhadko"]).Wait(); _userManager.CreateAsync(fomin, _configuration["fomin"]).Wait(); _userManager.CreateAsync(sivykh, _configuration["sivykh"]).Wait(); _userManager.CreateAsync(tatarintsev, _configuration["tatarintsev"]).Wait(); }
private void DisСonnectionFromServer(object sender, RoutedEventArgs e) { if (SerchServers.SelectedIndex == -1) { return; } var server = SerchServersList[SerchServers.SelectedIndex]; if (UserServerList.FirstOrDefault(x => x.ID == server.ID) is null) { return; } var SU = new ServerUser() { ID = User.ServerUser.FirstOrDefault(x => x.IDServer == server.ID).ID, StatusObj = StatusObj.Delete }; SendMessageToServer.SendMessageSerialize(SU); }
internal PhraseItem ToPhraseItem(ServerUser user) { var reviewState = new ReviewState { User = user, State = State.Accept }; var phraseItem = new PhraseItem { Phrase = Phrase, Complexity = Complexity, Description = Description, PackId = PackId, Version = 1, CreatedBy = user, CreatedDate = DateTime.Now, ReviewStates = new List <ReviewState> { reviewState } }; return(phraseItem); }
public async Task <ActionResult <ServerUser> > PostServerUser(ServerUser serverUser) { _context.ServerUser.Add(serverUser); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (ServerUserExists(serverUser.ServerId)) { return(Conflict()); } else { throw; } } return(CreatedAtAction("GetServerUser", new { id = serverUser.ServerId }, serverUser)); }
public UserItem(ServerUser user) { InitializeComponent(); tbUserNameInList.Text = user.Name; bool ChangableQuantity = (user.ID == ClientMaintaining.ID && !ClientMaintaining.ClientReadiness); if (user.isLeader) { imgUserLeaderOrDelete.Source = new BitmapImage(new Uri("Resources/leader.png", UriKind.Relative)); } if (user.Ready) { Readiness.Source = new BitmapImage(new Uri("Resources/ready.png", UriKind.Relative)); } pickedUser = user; if (ClientMaintaining.isSelfServer && ClientMaintaining.ID != user.ID) { btCross.Opacity = 1; //imgCross.Source = new BitmapImage(new Uri("Resources/X.png", UriKind.Relative)); } else { btCross.Opacity = 0; } if (user.Order != null) { foreach (var item in user.Order.Items) { lbOrderItems.Items.Add(new OrderItem(item, ChangableQuantity)); //lbUsers.Items.Add(new UserItem(user)); } } }
/// <summary> /// Adds the user's account to the authorized users list. This method should also disconnect any previous sockets that might be connected using the same account /// </summary> /// <param name="client"></param> /// <param name="persist">Determines if the ticket should be persisted in the datastore. Normally, you only need to do this when you are about to transfer control of the player to another server in the Hive.</param> /// <returns></returns> public static bool AuthorizeUser(ServerUser client, bool persist) { if (client == null) { return false; } lock (m_AuthorizedAccountsSyncRoot) { if (client.MyConnection != null && client.MyConnection.IsAlive) { client.Profile.SetLoggedIn(client.MyConnection.RemoteEndPoint.AddressFamily.ToString(), client.MyConnection.RemoteEndPoint.ToString()); } ServerUser existing = null; if (AuthorizedAccounts.TryGetValue(client.AccountName.ToLower(), out existing)) { UnAuthorizeUser(existing); if (existing.MyConnection != null) { existing.MyConnection.KillConnection("Logging in from another client."); } } Log1.Logger("Server.Login").Debug("Authorizing *" + client.AccountName.ToLower() + "*"); AuthorizedAccounts.Add(client.AccountName.ToLower(), client); AuthorizedAccounts.Associate(client.ID, client.AccountName.ToLower()); client.RenewAuthorizationTicket(persist); } return true; }
/// <summary> /// Adds the user's account to the authorized users list. This method should also disconnect any previous sockets that might be connected using the same account /// </summary> /// <param name="client"></param> /// <returns></returns> public static bool AuthorizeUser(ServerUser client) { return AuthorizeUser(client, ServerBase.UseDatabaseConnectivity); }
/// <summary> /// Each server in the cluster can have one parent. Whenever the parent connects, we call this method. /// </summary> public static void AddParentConnection(InboundConnection client, ServerUser su) { InboundConnection con = null; if (ParentConnections.TryGetValue(client.ServerUser.AccountName.ToLower(), out con)) { con.KillConnection("Parent server logging in again from different connection."); con.Disconnected -= new InboundConnection.DisconnectedDelegate(ParentConnection_Disconnected); ParentConnections.Remove(con.ServerUser.AccountName.ToLower()); } ParentConnections.Add(client.ServerUser.AccountName.ToLower(), client); client.Disconnected += new InboundConnection.DisconnectedDelegate(ParentConnection_Disconnected); }
/// <summary> /// Saves/updates the character to the DB /// </summary> /// <param name="owner">owning account</param> /// <param name="id">the id for the character to get</param> /// <param name="enforceUniqueName">You can change a toon's name in the DB. To ensure unique names, set to true. IMPORTANT!!!: If you are saving /// , i.e. updating an EXISTING toon without changing his name, set enforceUniqueName to FALSE - otherwise the update will fail since that /// toon's name already exists in the DB, the update will fail.</param> /// <returns></returns> public bool SaveCharacter(ServerUser owner, ServerCharacterInfo toon, bool enforceUniqueName, ref string rsultMsg) { SqlConnection con = null; SqlTransaction tran = null; try { Guid cown = Guid.Empty; if (DB.Instance.Character_Save(owner.ID, toon, (int)PropertyID.Name, toon.CharacterName, enforceUniqueName, out rsultMsg, out tran, out con)) { if (!OnCharacterSaving(con, tran, toon, ref rsultMsg)) { tran.Rollback(); } else { tran.Commit(); } } else { if (con.State != System.Data.ConnectionState.Closed && con.State != System.Data.ConnectionState.Connecting) { if (tran != null) { tran.Rollback(); } } rsultMsg = "Can't save character. " + rsultMsg; return false; } } catch (Exception e) { } finally { if (con != null) { con.Close(); con.Dispose(); con = null; } if (tran != null) { tran.Dispose(); tran = null; } } return true; }
public override void Deserialize(byte[] data, Pointer p, bool includeComponents) { m_CharacterInfo = new Shared.CharacterInfo(); m_CharacterInfo.Deserialize(data, p, includeComponents); ServerUser su = new ServerUser(); su.AuthTicket = Guid.Empty; su.OwningServer = BitPacker.GetString(data, p); su.ID = new Guid(BitPacker.GetString(data, p)); su.AccountName = BitPacker.GetString(data, p); su.Profile = (AccountProfile)BitPacker.GetSerializableWispObject(data, p); su.CurrentCharacter = this; this.TargetResource = new Guid(BitPacker.GetString(data, p)); OwningAccount = su; base.Deserialize(data, p, includeComponents); }
public PacketRelay MakeRelayPacket(string targetServer, Guid targetUser, ServerUser from, Packet message) { PacketRelay relay = new PacketRelay(); relay.PacketID = (int)ServerPacketType.Relay; relay.PacketSubTypeID = message.PacketID; relay.Flags = message.Flags; relay.From = from.CurrentCharacter.CharacterInfo; relay.Message = message.Serialize(new Pointer()); relay.OriginServer = this.ServerUserID; relay.TargetServer = targetServer; relay.To = targetUser; return relay; }
public static void UnAuthorizeUser(ServerUser client) { UnAuthorizeUser(client, true); }
protected void SendGameMessageReply(ServerUser client, ReplyType rp, string msg, Packet inResponseToPacket, PropertyBag parms, bool compress, bool encrypt) { PacketReply rmsg = client.MyConnection.CreateStandardReply(inResponseToPacket, rp, msg); if (parms != null) { rmsg.Parms = parms; } rmsg.IsCompressed = compress; rmsg.IsEncrypted = encrypt; inResponseToPacket.ReplyPacket = rmsg; }
public void RelayPacketToRemoteUser(AuthTicket target, Packet msg, ServerUser from) { // Sure it's not local? INetworkConnection local = ConnectionManager.GetUserConnection(target.AccountID); if (local != null) { local.Send(msg); return; } // Forward to server INetworkConnection remote = GetServerConnection(target.TargetServer); if (remote == null) { // sorry it didn't work out. return; } RelayPacketToRemoteUser(target, msg, from, remote); }
/// <summary> /// Relays a packet to a user attached to a remote server, if possible. If the user is not currently attached, then the message is lost. /// </summary> /// <param name="targetAccount">the character we're sending this message to</param> /// <param name="msg">the packet we want to send</param> /// <param name="from">who originated the packet</param> public void RelayPacketToRemoteUser(int targetCharacter, Packet msg, ServerUser from) { AuthTicket at = ConnectionManager.GetAuthorizationTicketForCharacter(targetCharacter); if (at != null) { RelayPacketToRemoteUser(at, msg, from); } }
/// <summary> /// Relays a packet to a user attached to a remote server, if possible. If the user is not currently attached, then the message is lost. /// </summary> /// <param name="targetAccount">the account we're sending this message to</param> /// <param name="msg">the packet we want to send</param> /// <param name="from">who originated the packet</param> public void RelayPacketToRemoteUser(Guid targetAccount, Packet msg, ServerUser from) { AuthTicket at = ConnectionManager.GetAuthorizationTicketForAccount(targetAccount); if (at != null) { RelayPacketToRemoteUser(at, msg, from); } }
/// <summary> /// Returns the authorized user object, or null if the user isn't currently authorized /// </summary> /// <param name="account"></param> /// <returns></returns> public static ServerUser GetAuthorizedUser(string account, ServerBase server, PacketLoginRequest.ConnectionType conType) { ServerUser u = null; if (conType == PacketLoginRequest.ConnectionType.AssistedTransfer) { lock (m_AuthorizedAccountsSyncRoot) { AuthorizedAccounts.TryGetValue(account.ToLower(), out u); } } else if (conType == PacketLoginRequest.ConnectionType.UnassistedTransfer) { Guid ticket = Guid.Empty; string authServer = ""; DateTime whenAuthd = DateTime.MinValue; int character = -1; string targetServerID = ""; Guid accountID = Guid.Empty; if (!DB.Instance.User_GetAuthorizationTicket(account, out authServer, out ticket, out whenAuthd, out character, out targetServerID, out accountID) || ticket == Guid.Empty) { return null; } if (targetServerID != server.ServerUserID) { // we weren't authorized to be on this server. Log1.Logger(server.ServerUserID).Error("[" + account + "] attempted unassisted transfer to [" + server.ServerUserID + "], but that user was only authorized to transfer to target server ID [" + targetServerID+ "]. Connection denied."); return null; } if (whenAuthd + AuthTicketLifetime < DateTime.UtcNow) { // ticket expired. Log1.Logger(server.ServerUserID).Error("[" + account + "] attempted unassisted transfer to [" + server.ServerUserID + "], but that user's auth ticket is expired. Connection denied."); return null; } // Got a ticket. Load up the user from the DB. u = new ServerUser(); u.OwningServer = server.ServerUserID; u.AuthTicket = ticket; u.ID = accountID; u.AccountName = account; // load the profile AccountProfile ap = new AccountProfile(account); u.Profile = ap; ap.Load(server.RequireAuthentication); // load the character if (character > -1) { string msg = ""; u.CurrentCharacter = CharacterUtil.Instance.LoadCharacter(u, character, ref msg); if (u.CurrentCharacter == null) { // Couldn't load character. Log1.Logger(server.ServerUserID).Error("[" + account + "] attempted unassisted transfer with characer [" + character + "], but that character could not be loaded from the DB: [" + msg + "]. Connection denied."); return null; } u.CurrentCharacter.OwningAccount = u; CharacterCache.CacheCharacter(u.CurrentCharacter, server.ServerUserID); } } AuthorizeUser(u); // gotta call this to activate/renew the auth ticket on this server. return u; }
private static bool CanExecute(ServerUser user, CommandData c, string[] parms, ref string msg) { return CanExecute(user.Profile.UserRoles, user.AccountName, c, parms, ref msg); }
public static void UnAuthorizeUser(ServerUser client, bool persist) { lock (m_AuthorizedAccountsSyncRoot) { if (client.AccountName == null || client.ID == null) { return; } // Remove from local authorized clients list AuthorizedAccounts.Remove(client.AccountName.ToLower()); // if we persist the unauthorization, the client will have to go through the login server again. if (persist) { DB.Instance.User_UnauthorizeSession(client.AccountName); } Log1.Logger("Server").Debug("Unauthorized account [" + client.AccountName + "] and auth ticket [" + client.AuthTicket.ToString() + "]. [" + AuthorizedAccounts.Count.ToString() + "] authorized accounts left in cache."); } }
private void RelayPacketToRemoteUser(AuthTicket target, Packet msg, ServerUser from, INetworkConnection con) { PacketRelay relay = MakeRelayPacket(target.TargetServer, target.AccountID, from, msg); con.Send(relay); }
/// <summary> /// Adds an entry to the DB listing of which servers are hosting which game. /// </summary> /// <param name="db"></param> /// <param name="owningClusterServerId"></param> /// <param name="gameId"></param> /// <param name="createdOnUTC"></param> /// <param name="createdByCharacter"></param> /// <returns></returns> public static bool Lobby_TrackGameForServer(this DB db, string owningClusterServerId, IGame game, DateTime createdOnUTC, ServerUser createdByCharacter) { bool result = true; SqlConnection con = DB.SessionDataConnection; SqlCommand cmd = DB.GetCommand(con, "Lobby_AddGameToServerMap", true); cmd.Parameters.Add(new SqlParameter("@ClusterServerID", owningClusterServerId)); cmd.Parameters.Add(new SqlParameter("@GameID", game.GameID)); cmd.Parameters.Add(new SqlParameter("@CreatedOn", createdOnUTC)); cmd.Parameters.Add(new SqlParameter("@CreatedByCharacter", createdByCharacter.CurrentCharacter.CharacterInfo.ID)); if (game.Name.Length > 512) { game.Name = game.Name.Substring(0, 512); } cmd.Parameters.Add(new SqlParameter("@GameName", game.Name)); cmd.Parameters.Add(new SqlParameter("@MaxPlayers", game.MaxPlayers)); SqlTransaction tran = null; try { con.Open(); tran = con.BeginTransaction(IsolationLevel.ReadCommitted); cmd.Connection = con; cmd.Transaction = tran; cmd.ExecuteNonQuery(); if (OnTrackGame != null && !OnTrackGame(owningClusterServerId, game, createdByCharacter, con, tran)) { tran.Rollback(); return false; } tran.Commit(); } catch (Exception e) { Log1.Logger("Server").Error("Failed to trac new game for server [" + owningClusterServerId + "], create by character ID [" + createdByCharacter + "] in database.", e); if (con.State != System.Data.ConnectionState.Closed && con.State != System.Data.ConnectionState.Connecting) { if (tran != null) { tran.Rollback(); } } return false; } finally { if (con != null) { con.Close(); con.Dispose(); con = null; } if (tran != null) { tran.Dispose(); tran = null; } } return result; }
/// <summary> /// Gets the character from the DB /// </summary> /// <param name="owner">owning account</param> /// <param name="id">the id for the character to get</param> /// <returns></returns> public ServerCharacterInfo LoadCharacter(ServerUser owner, int id, ref string rsultMsg) { SqlConnection con = null; SqlTransaction tran = null; ServerCharacterInfo ci = OnCharacterObjectCreate(CreateNewCharacterShell(), owner); try { Guid cown = Guid.Empty; if (DB.Instance.Character_Load(owner.ID, ci, id, ref cown, out tran, out con)) { if (!OnCharacterLoading(con, tran, ci, ref rsultMsg)) { tran.Rollback(); } else { tran.Commit(); } } else { rsultMsg = "Character doesn't exist."; return null; } } catch (Exception e) { return null; } finally { if (con != null) { con.Close(); con.Dispose(); con = null; } if (tran != null) { tran.Dispose(); tran = null; } } return ci; }
/// <summary> /// Executes a previously added command, passing the parms in order. Returns a textual response to the command. /// </summary> /// <param name="commandName">the name of the command to execute</param> /// <param name="parms">the paramters to pass</param> /// <returns></returns> public static string ExecuteCommand(ServerUser con, string commandName, string[] parms) { return ExecuteCommand(con.AccountName, con.Profile.UserRoles, commandName, parms); }
public ServerCharacterInfo(CharacterInfo characterInfo, ServerUser owner) { OwningAccount = owner; m_CharacterInfo = characterInfo; OnInitialize(); }
private void OnPlayerDone(ServerUser user, PacketGameMessage msg) { try { PlayerDone(user.CurrentCharacter); } catch { } }
/// <summary> /// Creates a new character in the DB using the character template XML file as a basis for stats and properties. If you want to override any of the default /// properties, pass in the appropriate characterProperties property bag. /// </summary> /// <param name="msg">an error message, if any</param> /// <returns></returns> public bool PersistNewCharacter(ServerCharacterInfo ci, ServerUser owner, ref string msg, bool isTempCharacter) { SqlConnection con = null; SqlTransaction tran = null; try { if (ValidateCharacterCreateRequest(ci, ref msg)) { int maxCharacters = (int)owner.Profile.MaxCharacters; if (maxCharacters < 1) maxCharacters = 1; int newCharId = 0; if (DB.Instance.Character_Create(owner.ID, ci.Stats, ci.Properties, (int)PropertyID.Name, ci.CharacterName, true, maxCharacters, isTempCharacter, out msg, out tran, out con, out newCharId)) { ci.CharacterInfo.ID = newCharId; if (OnCharacterPersiting(con, tran, ci)) { tran.Commit(); } else { tran.Rollback(); } return true; } else { if (con.State != System.Data.ConnectionState.Closed && con.State != System.Data.ConnectionState.Connecting) { if (tran != null) { tran.Rollback(); } } } } } catch (Exception exc) { if (con.State != System.Data.ConnectionState.Closed && con.State != System.Data.ConnectionState.Connecting) { if (tran != null) { tran.Rollback(); } } return false; } finally { if (con != null) { con.Close(); con.Dispose(); con = null; } if (tran != null) { tran.Dispose(); tran = null; } } return false; }
protected override bool OnBeforeHandleGamePacket(ServerUser user, PacketGameMessage msg) { try { return IsPlayerPartOfGame(user.CurrentCharacter.ID); } catch { return false; } }
/// <summary> /// Gets called as the character is being deleted from the Database. If you have additional DB tasks /// to add, now is the time. Use the supplied connection and transaction objects. The connection should already /// be open. /// Do NOT close the connection and do NOT commit /rollback the transaction. Simply return true or false if /// you want the deletion to be committed or not. /// </summary> /// <param name="con">the connection object to use for additional database work in relation to character deletion</param> /// <param name="tran">the transaction object to use for additional database work in relation to character deletion</param> /// <returns>return false if you do not want the transaction to be committed, which will also cause character deletion to fail</returns> protected virtual bool OnCharacterDeleting(SqlConnection con, SqlTransaction tran, int chracterId, ServerUser owner) { if (CharacterDeleting != null) { return CharacterDeleting(con, tran, chracterId, owner); } return true; }
protected void SendGameMessageReply(ServerUser client, ReplyType rp, Packet inResponseToPacket, bool compress, bool encrypt) { SendGameMessageReply(client, rp, "", inResponseToPacket, null, compress, encrypt); }
private bool CharacterUtil_OnCharacterDeleting(System.Data.SqlClient.SqlConnection con, System.Data.SqlClient.SqlTransaction tran, int characterId, ServerUser owner) { return OnCharacterDeleting(con, tran, characterId, owner); }
protected virtual bool OnCharacterDeleting(SqlConnection con, SqlTransaction tran, int characterId, ServerUser owner) { return true; }
protected ServerCharacterInfo OnCharacterObjectCreate(CharacterInfo ci, ServerUser owner) { if (CharacterObjectCreate != null) { return CharacterObjectCreate(ci, owner); } return new ServerCharacterInfo(CreateNewCharacterShell(), owner); }