private void createRoom(AdvancedNetworkLib.Client client, CreateRoom createRoom) { ClientUserData userData = client.UserData as ClientUserData; // check if there is any room with the same name if (Server.Clients.Any(c => (c.UserData as ClientUserData)?.RoomName == createRoom.Name)) { client.send(new Error { Job = Job.RoomCreation }); } else { userData.RoomName = createRoom.Name; userData.Password = createRoom.Password; userData.Host = true; // create room list entry lock (this.rooms) { // TODO: make round count variable this.rooms.Add(new RoomInfo { Name = userData.RoomName, Started = false, TotalRoundCount = 5, }); } client.send(new Success { Job = Job.RoomCreation }); } }
private bool SignIn(string name, string pwd, string orgId, OrgType orgType) { NCI_User user = null; if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(pwd) && UserCheck(name, pwd, orgId, orgType, ref user)) { IAuthenticationService authenticationService = IOCContainer.Instance.Resolve <IAuthenticationService>(); ClientUserData clientUserData = new ClientUserData() { UserId = user.UserId, UserIdInt = user.UserId, Account = user.Account, UserName = user.UserName, OrgId = orgId,// 超级管理员可能登陆进入不同Org, 因此这里用登陆选择的ORG. RoleType = user.RoleType, OrgType = (int)orgType, RoleId = user.RoleId, LoginName = user.Account, GovId = user.BelongToGovId }; authenticationService.SignIn(clientUserData, true); return(true); } return(false); }
private void joinRoom(AdvancedNetworkLib.Client client, JoinRoom joinRoom) { ClientUserData userData = client.UserData as ClientUserData; // check password bool passwordIsValid = Server.Clients.Any(c => { var u = c.UserData as ClientUserData; return(u != null && u.RoomName == joinRoom.Name && u.Password == joinRoom.Password); }); if (!passwordIsValid) { client.send(new Error { Job = Job.RoomJoin }); } else { userData.RoomName = joinRoom.Name; userData.Password = joinRoom.Password; userData.Host = false; client.send(new Success { Job = Job.RoomJoin }); } this.updateOverview(); }
public void TryLogout(Action logoutSuccessfulCallback, ClientUserData user, Action <string> errorCallback) { requestWorkQueue.Put(new LogoutRequestHandler(logoutSuccessfulCallback, user, connectionInfoVariable, errorCallback)); }
public ClientUserData GetClientUserDataByAccessToken(string accessToken) { // return GetClientDataAsyn(accessToken).Result; using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://apis.live.net/v5.0/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // New code: string callingMethod = string.Format("me?access_token={0}", accessToken); HttpResponseMessage response = client.GetAsync(callingMethod).Result; if (response.IsSuccessStatusCode) { string jsonUserData = response.Content.ReadAsStringAsync().Result; ClientUserData userData = JsonHelper.DeserializeObject <ClientUserData>(jsonUserData); return(userData); } else { string jsonErrorData = response.Content.ReadAsStringAsync().Result; AuthenticationResponse errorData = JsonHelper.DeserializeObject <AuthenticationResponse>(jsonErrorData); throw new AccessDeniedException(errorData.AuthenticationResponseError); } } }
public ActionResult Login(string name, string pwd, string isRemember) { ViewBag.Msg = ""; ClientUserData user = null; // 临时去掉验证码检验 var code = "1234"; Session["CheckCode"] = code.ToUpper();//Util.Md5(pwd+name) if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(pwd) && !string.IsNullOrEmpty(code) && UserCheck(name, Util.Md5(pwd + name), ref user) && Session["CheckCode"] != null && code.ToUpper() == Session["CheckCode"].ToString().ToUpper()) { IAuthenticationService authenticationService = IOCContainer.Instance.Resolve <IAuthenticationService>(); authenticationService.SignIn(user, isRemember == "on"); ViewBag.User = SecurityHelper.CurrentPrincipal; if (Request.UrlReferrer != null) { var index = Request.UrlReferrer.PathAndQuery.IndexOf("ReturnUrl="); if (index != -1) { var url = HttpUtility.UrlDecode(Request.UrlReferrer.PathAndQuery.Substring(index + 10), Encoding.UTF8); return(Redirect(HttpUtility.UrlDecode(url))); } } //if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"])) //{ // return Redirect(HttpUtility.UrlDecode(Request.QueryString["ReturnUrl"])); //} return(View("MainForm")); } ViewBag.Msg = "请输入正确信息"; return(View()); }
public LogoutRequestHandler(Action logoutSuccessfulCallback, ClientUserData user, ISharedState <ConnectionInfo> connectionInfoVariable, Action <string> errorCallback) : base(errorCallback) { this.user = user; this.connectionInfoVariable = connectionInfoVariable; this.logoutSuccessfulCallback = logoutSuccessfulCallback; }
public ActionResult CheckPwd(string name, string pwd) { ClientUserData user = null; var result = UserCheck(name, Util.Md5(pwd + name), ref user); return(new JsonResult() { Data = new { Ok = result } }); }
/// <summary> /// 自定义过滤器 /// </summary> /// <param name="filterContext"></param> protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[cookieName]; FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception ex) { return; } if (authTicket != null && filterContext.HttpContext.User.Identity.IsAuthenticated) { string UserId = authTicket.Name; if (!string.IsNullOrEmpty(UserId)) { var response = Implement.GetUserInfo(Convert.ToInt32(UserId)); mol = response.Data; if (mol != null) { Uright = mol.Role.RightVle; ViewBag.MenusList = Implement.GetMenus(Uright); ViewBag.UserName = mol.Uname; //把toke用户数据放到 HttpContext.Current.User 里 ClientUserData clientUserData = new ClientUserData() { UserId = mol.Id, Uname = mol.Uname, RoleId = mol.RoleId, pinyin = mol.pinyin, idCard = mol.idCard, PhotoNum = mol.PhotoNum, EmployeeSex = mol.EmployeeSex, EmployeePhone = mol.EmployeePhone, Age = mol.Age, Worker = mol.Worker, HomeAddress = mol.HomeAddress, RightVle = mol.Role.RightVle, RightName = mol.Role.RightName, isAdd = mol.Role.isAdd, isUpdate = mol.Role.isUpdate, isDelete = mol.Role.isDelete, }; if (System.Web.HttpContext.Current != null) { System.Web.HttpContext.Current.User = new UserPrincipal(clientUserData); } } base.OnActionExecuting(filterContext); } } }
public override void OnAuthorization(HttpActionContext context) { var authHeader = context.Request.Headers.FirstOrDefault(a => a.Key == "ApiAuthorization");//获取接收的Token if (context.Request.Headers == null || !context.Request.Headers.Any() || authHeader.Key == null || string.IsNullOrEmpty(authHeader.Value.FirstOrDefault())) { Throw401Exception(context, "NoToken"); return; } var sendToken = authHeader.Value.FirstOrDefault(); //url获取token var now = Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + 5);//当前的时间戳 var dictPayload = DecodeToken(sendToken); if (dictPayload == null) { Throw401Exception(context, "InvalidToken"); } double iat = dictPayload["iat"]; double exp = dictPayload["exp"]; //检查令牌的有效期 if (!(iat < now && now < exp))//如果当前时间戳不再Token声明周期范围内,则返回Token过期 { Throw401Exception(context, "TokenTimeout"); } //获取Token的自定义键值对 int UserId = dictPayload["UserId"]; string UserName = dictPayload["UserName"]; string UserPwd = dictPayload["UserPwd"]; string UserRole = dictPayload["UserRole"]; //把toke用户数据放到 HttpContext.Current.User 里 ClientUserData clientUserData = new ClientUserData() { UserId = UserId, UserName = UserName, UserPwd = UserPwd, UserRole = UserRole }; if (HttpContext.Current != null) { HttpContext.Current.User = new UserPrincipal(clientUserData); } }
public void SignIn(ClientUserData clientUserData, bool createPersistentCookie) { var now = DateTime.Now.ToLocalTime(); string userData = JsonConvert.SerializeObject(clientUserData); var ticket = new FormsAuthenticationTicket( 1 /*version*/, clientUserData.UserId.ToString(), now, now.Add(ExpirationTimeSpan), createPersistentCookie, userData, FormsAuthentication.FormsCookiePath); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { HttpOnly = true, Secure = FormsAuthentication.RequireSSL, Path = FormsAuthentication.FormsCookiePath }; var httpContext = HttpContext.Current; if (FormsAuthentication.CookieDomain != null) { cookie.Domain = FormsAuthentication.CookieDomain; } if (createPersistentCookie) { cookie.Expires = ticket.Expiration; } httpContext.Response.Cookies.Add(cookie); _isAuthenticated = true; ICustomPrincipal user = new ICustomPrincipal(clientUserData); _signedInUser = user; httpContext.User = user; }
public void TryLogin(ClientUserData user, string password, Action <string> errorCallback) { connectionService.TryLogin( () => { Application.Current.Dispatcher.Invoke(() => { LoggedInUser = user; ApplyWorkflowEvent(WorkflowEvent.LoggedIn); undoRedoService = new UndoRedoService(50); undoRedoService.RedoPossibleChanged += OnUndoRedoServiceRedoPossibleChanged; undoRedoService.UndoPossibleChanged += OnUndoRedoServiceUndoPossibleChanged; }); }, user, password, errorCallback ); }
public void Logout(Action logoutSuccessful, Action <string> errorCallback) { connectionService.TryLogout( () => { Application.Current?.Dispatcher.Invoke(() => { undoRedoService.RedoPossibleChanged -= OnUndoRedoServiceRedoPossibleChanged; undoRedoService.UndoPossibleChanged -= OnUndoRedoServiceUndoPossibleChanged; undoRedoService = null; LoggedInUser = null; ApplyWorkflowEvent(WorkflowEvent.LoggedOut); logoutSuccessful?.Invoke(); }); }, LoggedInUser, errorCallback ); }
public override void OnAuthorization(HttpActionContext actionContext) { if (SkipAuthorization(actionContext)) { return; } var authHeader = actionContext.Request.Headers.FirstOrDefault(a => a.Key == "Authorization"); if (actionContext.Request.Headers == null || !actionContext.Request.Headers.Any() || authHeader.Key == null || string.IsNullOrEmpty(authHeader.Value.FirstOrDefault())) { if (AllowAllUser(actionContext)) { return; } Throw401Exception(actionContext, "缺少Authorization头信息!"); } string authorization = authHeader.Value.FirstOrDefault(); authorization = authorization.Replace("Basic ", ""); var encoding = Encoding.GetEncoding("iso-8859-1"); authorization = encoding.GetString(Convert.FromBase64String(authorization)); int separator = authorization.IndexOf(':'); string userName = authorization.Substring(0, separator); string userPassword = authorization.Substring(separator + 1); ClientUserData user = null; var IsSuccess = service.Login(userName, userPassword, out user); if (IsSuccess) { actionContext.Request.Properties.Remove("AuthorizationUserId"); actionContext.Request.Properties.Add("AuthorizationUserId", user.UserId); return; } Throw401Exception(actionContext, "用户登录失败"); }
void Application_PostAuthenticateRequest(object sender, EventArgs e) { System.Web.HttpContext.Current.SetSessionStateBehavior( SessionStateBehavior.Required); HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { ClientUserData clientUserData = null; try { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); clientUserData = JsonConvert.DeserializeObject <ClientUserData>(authTicket.UserData); } catch { } if (HttpContext.Current != null && clientUserData != null) { HttpContext.Current.User = new ICustomPrincipal(clientUserData); } } }
/// <summary> /// 重写基类的验证方式,加入我们自定义的Ticket验证 /// </summary> /// <param name="actionContext"></param> public override void OnAuthorization(HttpActionContext actionContext) { var attributes = actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().OfType <AllowAnonymousAttribute>(); bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute); if (isAnonymous) { base.OnAuthorization(actionContext); } else { var authHeader = from h in actionContext.Request.Headers where h.Key == "token" select h.Value.FirstOrDefault(); if (authHeader != null) { string token = authHeader.FirstOrDefault(); if (!string.IsNullOrEmpty(token)) { //解密用户ticket,并校验用户名密码是否匹配 var userService = ContainerManager.Resolve <IUserService>(); var tokenService = ContainerManager.Resolve <IUserTokenService>(); var userToken = tokenService.GetTicket(token); if (userToken != null) { var user = userService.GetById(userToken.UserID); var permsList = userService.GetMyPermissions(user.UserID); var perms = permsList != null && permsList.Count > 0? string.Join(",", permsList.ToArray()):""; ClientUserData clientUserData = new ClientUserData() { UserId = user.UserID, UserName = user.UserName, UserPermission = perms }; var MyPrincipal = new UserPrincipal(clientUserData); Thread.CurrentPrincipal = MyPrincipal; if (HttpContext.Current != null) { HttpContext.Current.User = MyPrincipal; } if (!_accessName.IsBlank()) { if (!MyPrincipal.HasPermission(_accessName)) { GetResponseMessage(actionContext, 9997, "没有操作权限"); } else { base.OnAuthorization(actionContext); } } else { base.OnAuthorization(actionContext); } } else { GetResponseMessage(actionContext, 9998, "token已失效,请重新登陆!"); } } else { GetResponseMessage(actionContext, 9997, "token不能为空!"); } } else { //没有获取到header头内容 //HandleUnauthorizedRequest(actionContext); GetResponseMessage(actionContext, 1, "未获取到Header!"); } } }
public bool Login(string name, string pwd, out ClientUserData user) { user = null; if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pwd)) { return(false); } var sysUser = unitOfWork.GetRepository <SYS_User>().dbSet.FirstOrDefault(q => q.IsDeleted == false && q.AccountName == name && q.Password == pwd); if (sysUser == null) { return(false); } //Mapper.CreateMap<SYS_User, UserModel>(); var Orgs = sysUser.ORG_Organization.Where(o => !o.IsDeleted).ToList(); var roles = sysUser.SYS_Role.Where(o => !o.IsDeleted).Select(o => new { o.RoleID, o.RoleName }).ToArray(); // var groupIds = sysUser.ORG_Group.Where(o => !o.IsDeleted).Select(o => o.GroupID).ToArray(); var groupIds = sysUser.ORG_Organization.Where(o => !o.IsDeleted).Select(o => o.GroupID).FirstOrDefault(); var contactAddress = sysUser.ORG_Organization.Where(o => !o.IsDeleted).Select(o => new { o.Address, o.City }).FirstOrDefault(); var tel = sysUser.ORG_Organization.Where(o => !o.IsDeleted).Select(o => o.Tel).FirstOrDefault(); if (groupIds == null) { groupIds = sysUser.ORG_Group.Where(o => !o.IsDeleted).Select(o => o.GroupID).ToArray().FirstOrDefault(); } var tmp = Mapper.DynamicMap <UserModel>(sysUser); var roleType = Enum.GetName(typeof(RoleType), RoleType.Other); if (roles[0].RoleName.IndexOf("收费员") != -1) { roleType = Enum.GetName(typeof(RoleType), RoleType.TollCollector); } else if (roles[0].RoleName.IndexOf("医疗") != -1) { roleType = Enum.GetName(typeof(RoleType), RoleType.MedicalPerson); } else if (roles[0].RoleName.IndexOf("派遣服务") != -1) { roleType = Enum.GetName(typeof(RoleType), RoleType.ServicePerson); } user = new ClientUserData() { UserId = tmp.UserID, LoginName = tmp.AccountName, EmpName = tmp.DisplayName, OrgId = Orgs.Count() > 0 ? Orgs[0].OrganizationID : 0, RoleId = roles.Length > 0 ? roles[0].RoleID : 0, RoleType = roleType, GroupId = groupIds.HasValue ? groupIds.Value : 0, OrgAddress = contactAddress == null?"":(contactAddress.City + contactAddress.Address), OrgPhone = tel, IsSurperAdmin = sysUser.SYS_Role.Any(o => o.RoleNo == "R000"), IsGroupAdmin = sysUser.SYS_Role.Any(o => o.RoleNo == "R100"), OrgIds = Orgs.Select(a => a.OrganizationID).ToArray(), LogoPath = Orgs.Count() > 0 ? Orgs[0].LogoPath : "" }; if (user.IsSurperAdmin || user.IsGroupAdmin) { user.OrgId = -1; } var empsrv = new EmployeeService(); var emp = empsrv.GetEmployees(user.UserId); var firstOrDefault = emp.FirstOrDefault(); if (firstOrDefault != null) { if (firstOrDefault.EmpState != "001") { return(false); } user.EmpId = firstOrDefault.EmployeeID; user.DeptID = firstOrDefault.DeptID; user.CheckRoomID = firstOrDefault.CheckRoomID; } ; return(true); }
public ConnectionInfo(ConnectionSessionId sessionId, ClientUserData loggedInUser) { SessionId = sessionId; LoggedInUser = loggedInUser; }
private bool UserCheck(string name, string pwd, ref ClientUserData user) { var service = IOCContainer.Instance.Resolve <IUserService>(); return(service.Login(name, pwd, out user)); }
public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl) { string provider = null; string providerUserId = null; if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId)) { return(this.RedirectToAction("Index", "Home")); } if (ModelState.IsValid) { UserProfile userProfile = this.userManager.GetUserProfileFromProvider(provider, providerUserId); if (userProfile == null) { ClientUserData clientUserData = (ClientUserData)TempData["ClientUserData"]; Random random = new Random(); int userId = random.Next(int.MaxValue); userProfile = new UserProfile { RowKey = userId.ToString(), UserName = string.IsNullOrEmpty(clientUserData.UserName) ? clientUserData.Emails.Account : clientUserData.UserName, AccountEmail = clientUserData.Emails.Account, FirstName = model.FirstName, LastName = model.LastName, City = model.City, Country = model.Country, State = model.State, PreferredEmail = model.PreferredEmail, Gender = clientUserData.Gender, Link = Convert.ToString(clientUserData.Link), IsSuperAdmin = false, TimeZone = model.TimeZone, CreatedTime = DateTime.Now.ToUniversalTime().ToString(), Address1 = model.Address1, Address2 = model.Address2, Phone = model.Phone, PhoneCountryCode = model.PhoneCountryCode, ZipCode = model.ZipCode }; var regions = this.regionSource.GetAvailableRegions(); List <AccessDetails> defaultAccess = new List <AccessDetails>(); foreach (var region in regions) { var accessDetail = new AccessDetails { AccessLevel = AccessLevels.PortalUser, Authority = (Authorities)Convert.ToInt32(region.RegionInformation.Id) }; defaultAccess.Add(accessDetail); } this.userManager.SaveUserDetails( new UserDetails { UserInfo = userProfile, AccessInfo = defaultAccess, }); this.RegisterAuditor.TransactionId = this.RegisterLogger.TransactionId; this.RegisterAuditor.Audit(AuditId.RegisterUser, AuditStatus.Success, default(int), userProfile.UserName + " Registered Successfully"); this.RegisterLogger.Log(TraceEventType.Information, LoggingMessageId.PortalUserRegistration, userProfile.UserName + " registered to the portal"); OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName); OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false); this.RegisterLogger.Log(TraceEventType.Information, LoggingMessageId.PortalUserLoggedIn, userProfile.UserName + " has logged in to the portal"); // By Default IsSuperAdmin is false this.CreateAuthenticationTicket(model.UserName, clientUserData.AccessToken, DateTime.Now, false, false); return(this.RedirectToLocal(returnUrl)); } else { ModelState.AddModelError("UserName", "User already exists. Please enter a different user name."); } } ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName; ViewBag.ReturnUrl = returnUrl; ViewBag.Country = new SelectList(Utility.GetCounties()); ViewBag.TimeZone = new SelectList(Utility.GetTimeZones()); ViewBag.PhoneCountryCode = new SelectList(Utility.GetCountryPhoneCodes()); return(this.View("Register", model)); }
public PageGame(ClientUserData userData) : this() { this.userData = userData; this.userData.IsDrawing = false; this.send_bitmap_thread = null; }
/// <summary> /// 登录接口 /// </summary> /// <param name="auth">参数</param> public IHttpActionResult Post([FromBody] dynamic auth) { BaseResponse <IClientLoginUser> response = new BaseResponse <IClientLoginUser>(); if (auth == null) { response.ResultCode = 501; response.ResultMessage = "输入的参数不正确"; response.IsSuccess = false; return(Ok(response)); } var uid = auth.uid.Value; var pwd = auth.pwd.Value; IClientLoginUser rtUser = null; bool loginRs; if (!Regex.IsMatch(uid, @"^(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$", RegexOptions.IgnoreCase)) { ClientUserData user = null; loginRs = service.Login(uid, Util.Md5(pwd + uid), out user); if (user != null) { user.UserType = Enum.GetName(typeof(UserType), UserType.Employee); } rtUser = user; } else { ClientResidentData user = null; loginRs = residentService.Login(uid, Util.Md5(pwd + uid), out user); if (user != null) { user.UserType = Enum.GetName(typeof(UserType), UserType.Resident); } rtUser = user; } if (rtUser == null || !loginRs) { response.ResultCode = 502; response.ResultMessage = "输入的用户名或密码不正确"; response.IsSuccess = false; return(Ok(response)); } else { response.ResultCode = 200; response.ResultMessage = "登录成功"; response.Data = rtUser; //生成Token var jwtcreated = Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + 5); var payload = new Dictionary <string, dynamic> { { "iss", uid }, { "iat", jwtcreated } }; string token = JWT.JsonWebToken.Encode(payload, KMHC.SLTC.Business.Entity.Constants.SecretKey, JWT.JwtHashAlgorithm.HS256); response.Token = token; //KMHC.Infrastructure.Cached.LocalCachedProvider.Instance.Set(uid, 1); return(Ok(response)); } }
private void Server_ObjectReceived(object sender, AdvancedNetworkLib.ObjectReceivedEventArgs e) { AdvancedNetworkLib.Client client = (sender as AdvancedNetworkLib.Client); ClientUserData userData = client.UserData as ClientUserData; RoomInfo roomInfo = this.rooms.Find(c => c.Name == userData?.RoomName); var obj = e.Object; if (obj is ServerPassword) { ServerPassword serverPassword = obj as ServerPassword; this.checkServerPassword(client, serverPassword); } else if (obj is ChangeState) { var oldState = userData.State; ChangeState changeState = obj as ChangeState; userData.State = changeState.State; if (userData.State == State.RoomChoice) { userData.PlayerName = string.Empty; userData.RoomName = string.Empty; userData.Password = 0; userData.IsDrawing = false; userData.Points = 0; userData.Host = false; // if player was in lobby if (oldState == State.Lobby || oldState == State.LobbyReady) { this.sendLobbyListToAll(roomInfo); } // if player was in game if (oldState == State.Game) { // check if only one player is left in game var playersInGame = this.getPlayersInGame(roomInfo); if (playersInGame.Count() == 1) { // kick last player in game playersInGame.First().send(new KickedNoMorePlayer()); } else if (playersInGame.Count() > 1) { // update ranklist for players in game this.sendRankListToAll(roomInfo); } } // update and send roomlist this.sendRoomListToAll(); } else if (userData.State == State.RoomCreation) { string randomRoomName = string.Empty; // generate random room name // TODO: better performance when checking host boolean first int i = 1000; while (Server.Clients.Count(c => (c.UserData as ClientUserData).RoomName == (randomRoomName = $"Room{Server.rand.Next(0, 999).ToString().PadLeft(3, '0')}") && (c.UserData as ClientUserData).Host) > 0 && i-- > 0) { } client.send(new RandomRoomName { Name = randomRoomName }); } else if (userData.State == State.LobbyReady || userData.State == State.Lobby) { if (userData.PlayerName == string.Empty) { string randomPlayerName = string.Empty; // generate random room name var players = this.getPlayers(roomInfo); while (players.Any(p => { return((p.UserData as ClientUserData).PlayerName == (randomPlayerName = $"Player{Server.rand.Next(0, 999).ToString().PadLeft(3, '0')}")); })) { } userData.PlayerName = randomPlayerName; client.send(new RandomPlayerName { Name = randomPlayerName }); // update and send lobbylist this.sendLobbyListToAll(roomInfo); } else { string newPlayerName = changeState.Data as string; // check if any player has already the same name int playerWithSameName = Server.Clients.Count(c => c.UserData != null && c != client && (c.UserData as ClientUserData).RoomName == userData.RoomName && (c.UserData as ClientUserData).PlayerName == newPlayerName); if (playerWithSameName > 0) { client.send(new Error { Job = Job.NameChange }); } else { // name is free and will be used userData.PlayerName = newPlayerName; if (userData.Host) { client.send(new Success { Job = Job.NameChange }); } else { bool hostIsPlaying = Server.Clients.Count(c => c.UserData != null && (c.UserData as ClientUserData).RoomName == userData.RoomName && (c.UserData as ClientUserData).Host && (c.UserData as ClientUserData).State == State.Game) > 0; client.send(new Success { Job = hostIsPlaying ? Job.GameStart : Job.NameChange }); } // update and send lobbylist this.sendLobbyListToAll(roomInfo); } } // update and send roomlist this.sendRoomListToAll(); } else if (userData.State == State.Game) { if (userData.Host) { // send ranklist this.sendRankListToAll(roomInfo); // tell other players that the game starts var players = this.getPlayersInLobbyAndReady(roomInfo); this.sendObjectToPlayers(players, new StartGame()); } else { // check if player joins later if (this.rooms.Exists(c => c.Name == userData.RoomName && c.Started)) { // this player joins later // send ranklist this.sendRankListToAll(roomInfo); // get current drawer and send drawing request var currentDrawer = this.getCurrentDrawer(roomInfo); if (currentDrawer != null) { currentDrawer.send(new DrawingRequest()); } } else { // count players in lobby var playersInLobbyCount = this.getPlayersInLobbyAndReady(roomInfo).Count(); // start game when all players are in the game if (playersInLobbyCount == 0) { // start game for the first time roomInfo.Started = true; // start first round this.startRound(roomInfo); } } } this.sendRoomListToAll(); } this.updateCountLabels(); } else if (obj is CreateRoom) { CreateRoom createRoom = obj as CreateRoom; this.createRoom(client, createRoom); } else if (obj is JoinRoom) { JoinRoom joinRoom = obj as JoinRoom; this.joinRoom(client, joinRoom); } else if (obj is StartGame) { int playerCount = this.getPlayers(roomInfo).Count(); int playerCountReady = this.getPlayersInLobbyAndReady(roomInfo).Count(); if (playerCount != playerCountReady || playerCount < 2) { client.send(new Error { Job = Job.GameStart }); } else { client.send(new Success { Job = Job.GameStart }); } } else if (obj is ChatMessage) { var chatMessage = obj as ChatMessage; chatMessage.PlayerName = userData.PlayerName; // get all clients in the same room and that are playing var players = this.getPlayersInGame(roomInfo); // check if entered word is equal to searched word bool foundWord = (roomInfo.CurrentWord.ToLower() == chatMessage.Text.ToLower()); if (foundWord && (roomInfo.RoundInfo.PlayerTimes.ContainsKey(userData.PlayerName) || userData.IsDrawing)) { client.send(new WhatDoYouWantInfo()); } else { var foundWordInfo = foundWord ? new FoundWordInfo { PlayerName = userData.PlayerName } : null; if (foundWord) { // give points roomInfo.RoundInfo.PlayerTimes.Add(userData.PlayerName, 500 * ((players.Count() - 1) - roomInfo.RoundInfo.PlayerTimes.Count)); } foreach (var player in players) { if (foundWord) { player.send(foundWordInfo); } else { player.send(chatMessage); } } // check if this is the last player that found the word if (foundWord && roomInfo.RoundInfo.PlayerTimes.Count == players.Count() - 1) { // end round roomInfo.RoundInfo.WordUpdateTimer.Stop(); // send revealed word string revealedWord = string.Join(" ", roomInfo.CurrentWord); var choosedWordInfo = new ChoosedWordInfo { Word = revealedWord }; this.sendObjectToPlayers(players, choosedWordInfo); this.nextDrawer(roomInfo); } } } else if (obj is Drawing) { // get every player in the same room, except drawer var players = this.getPlayersInGameExceptDrawer(roomInfo); this.sendObjectToPlayers(players, obj); } else if (obj is ChoosedWord) { var choosenWord = obj as ChoosedWord; roomInfo.CurrentWord = choosenWord.Word; roomInfo.CurrentWordRevealed.Clear(); // store choosen word to list with choosen words => solution is a bit ugly roomInfo.ChoosenWordIndices.Add(this.wordList.IndexOf(this.wordList.First(w => w.Word == choosenWord.Word))); var timer = roomInfo.RoundInfo.WordUpdateTimer = new Timer(); timer.Interval = (int)((this.roundDuration * 1000.0) / choosenWord.Word.Length); timer.Tick += (s2, e2) => this.revealCharOfWord(s2, roomInfo); this.revealCharOfWord(timer, roomInfo); timer.Start(); } else if (obj is KickedByHost) { var playerName = (obj as KickedByHost).PlayerName; var player = this.getPlayerByName(playerName); player?.send(obj); } }