예제 #1
0
        public IHttpActionResult ResetPassword([FromBody] ResetPasswordModel model)
        {
            var user = JwtHelper.DecodeToken(model.UserIdentity, TokenAudiences.ResetPassword, false);

            if (user == null)
            {
                return(StatusCode(HttpStatusCode.Forbidden));
            }

            //
            var id     = user.FindFirst(ClaimTypes.NameIdentifier).Value;
            var dbUser = DB.Users.FirstOrDefault(x => x.Id == id && x.EmailConfirmed && !x.LockedOut);

            if (dbUser == null)
            {
                return(BadRequest(MessageResources.ERR_INVALID_ACCOUNT_STATE));
            }

            //
            var token = DB.Tokens.FirstOrDefault(x => x.Token == model.Token && x.User.Id == id && x.TokenType == TokenType.PasswordReset);

            if (token != null)
            {
                DB.Tokens.Remove(token);
                dbUser.SetPassword(model.NewPassword);
                DB.SaveChanges();
                return(StatusCode(HttpStatusCode.NoContent));
            }

            return(BadRequest("Invalid reset code. Please try again!"));
        }
예제 #2
0
        public IHttpActionResult RefreshToken([FromBody] RefreshTokenModel model)
        {
            var decoded = JwtHelper.DecodeToken(model.RefreshToken, TokenAudiences.RefreshToken);

            if (decoded == null)
            {
                return(BadRequest());
            }

            string userId = decoded.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            var    user   = DB.Users.IncludeOptimized(x => x.Claims).FirstOrDefault(x => x.Id == userId);

            if (user == null)
            {
                return(BadRequest());
            }

            return(Ok(new LoginResponse()
            {
                RefreshToken = JwtHelper.SignToken(user, expires: DateTime.UtcNow.AddMonths(1), audience: TokenAudiences.RefreshToken),
                AccessToken = JwtHelper.SignToken(user, audience: TokenAudiences.Universal),
                ExpiresAt = DateTime.UtcNow.AddDays(3),
                IssuedAt = DateTime.UtcNow
            }));
        }
        public void ListOtherPlayerZonesTest()
        {
            // create new player and one map
            var token = "";

            try
            {
                token = UserAccess.Register(DefaultUser.Username + "1", DefaultUser.Password);
            }
            catch
            {
                token = UserAccess.Login(DefaultUser.Username + "1", DefaultUser.Password);
            }
            var decodedToken = JwtHelper.DecodeToken(token);
            var mapHashId    = ZoneAccess.CreateMap(DefaultZone.Name, DefaultZone.Content, DefaultZone.Level);

            UserToken.Token = Token;
            var maps = ZoneAccess.GetPlayerZones(decodedToken.UserId);

            Assert.AreEqual(1, maps.Count);
            Assert.AreEqual(DefaultZone.Name, maps[0].Name);

            // login as user to delete map and user
            UserToken.Token = token;
            ZoneAccess.DeleteMap(mapHashId);
            UserAccess.DeleteUser();
        }
예제 #4
0
        /// <summary>
        /// Meldet sich mit dem angegebenen Benutzer an. Gibt null zurück falls login fehlschlägt
        /// </summary>
        /// <param name="client"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="subUrl"></param>
        /// <returns></returns>
        public static LoginResponseObject Login(this HttpClient client, string username, string password, string subUrl = "auth/login")
        {
            HttpResponseMessage response = client.PostAsJsonAsync(subUrl, new UserForLoginDto
            {
                Username = username,
                Password = password,
                Cameras  = new List <CameraDto>()
            }).Result;

            if (!response.IsSuccessStatusCode)
            {
                return(null);
            }

            var content = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            JwtSecurityToken permissionsToken = JwtHelper.DecodeToken(content.SelectToken("permissionsToken").Value <string>());
            Claim            serialClaim      = permissionsToken.Claims.FirstOrDefault(c => c.Type == BeepClaimTypes.PermissionsSerial);
            Claim            envIdClaim       = permissionsToken.Claims.FirstOrDefault(c => c.Type == BeepClaimTypes.EnvironmentId);

            client.DefaultRequestHeaders.Remove(BeepClaimTypes.PermissionsSerial);
            client.DefaultRequestHeaders.Remove(BeepClaimTypes.EnvironmentId);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", content.SelectToken("identityToken").Value <string>());
            client.DefaultRequestHeaders.Add(BeepClaimTypes.PermissionsSerial, serialClaim?.Value);
            client.DefaultRequestHeaders.Add(BeepClaimTypes.EnvironmentId, envIdClaim?.Value);


            return(content.ToObject <LoginResponseObject>());
        }
예제 #5
0
        private ActionResult ConnectUser(bool rememberMe, string userTokenString)
        {
            var token = JwtHelper.DecodeToken(userTokenString);

            var profileService = new ProfileService(token);

            var    myProfile = profileService.GetMyProfile();
            string userData  = JsonConvert.SerializeObject(new PrincessSerializable()
            {
                Id            = myProfile.Id,
                Picture       = myProfile.Picture,
                PrincessTitle = myProfile.PrincessTitle,
                Token         = userTokenString,
                Username      = myProfile.Username,
                UserHashId    = myProfile.UserHashId
            });

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                1,
                myProfile.UserHashId,
                DateTime.Now,
                DateTime.Now.AddMinutes(15),
                rememberMe, //pass here true, if you want to implement remember me functionality
                userData);

            string     encTicket = FormsAuthentication.Encrypt(authTicket);
            HttpCookie faCookie  = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            Response.Cookies.Add(faCookie);
            return(RedirectToAction("Index", "Profil"));
        }
예제 #6
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var auth = request.Headers.Authorization;

            if (auth != null && (auth.Scheme == "Bearer"))
            {
                var principal = JwtHelper.DecodeToken(auth.Parameter, TokenAudiences.Universal);
                if (principal != null)
                {
                    var id = principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                    using (var dbContext = new BookingContext())
                    {
                        if (dbContext.Users.Any(x => x.Id == id && x.EmailConfirmed))
                        {
                            Thread.CurrentPrincipal = principal;

                            if (HttpContext.Current != null)
                            {
                                HttpContext.Current.User = principal;
                            }
                        }
                    }
                }
            }

            return(base.SendAsync(request, cancellationToken));
        }
        public override void OnMessage(string message)
        {
            try
            {
                var jsonMessage = JObject.Parse(message);
                if (hashId == null)
                {
                    _token = JwtHelper.DecodeToken(jsonMessage["user_token"].ToString());
                    hashId = _token.UserId;
                    clientUser.Add(hashId, this);
                }

                var matchHashId = jsonMessage["match_id"].ToString();

                var curgame = Games.FirstOrDefault(g => g.HashId == matchHashId);
                if (curgame != null)
                {
                    foreach (var playerId in curgame.ParticipantsHashId.Where(playerId => hashId != playerId))
                    {
                        clientUser[playerId].Send(message);
                    }

                    foreach (var specId in curgame.SpectatorsHashId)
                    {
                        if (clientUser.ContainsKey(specId))
                        {
                            clientUser[specId].Send(message);
                        }
                    }
                }
            }
            catch
            {
            }
        }
예제 #8
0
        private bool ValidateToken(ref HttpActionContext actionContext)
        {
            // if the request is to login, just return true
            if (actionContext.Request.RequestUri.AbsoluteUri.Contains("api/sam/login"))
            {
                return(true);
            }

            // this lines throw exception (if an error) captured by our filter
            var token        = ExtractToken(actionContext.Request);
            var decodedToken = JwtHelper.DecodeToken(token);

            // here we need to create an exception if we could not find some keys on decoded token
            try
            {
                var context    = decodedToken["context"] as Dictionary <string, object>;
                var user       = context["user"] as Dictionary <string, object>;
                var id         = user["id"];
                var perfil     = user["perfil"] as string;
                var samaccount = user["samaccount"] as string;

                // we are modifying the original request
                actionContext.Request.Headers.Add("id", Convert.ToString(id));
                actionContext.Request.Headers.Add("perfil", perfil);
                actionContext.Request.Headers.Add("samaccount", samaccount);
                actionContext.Request.Headers.Remove("token");

                return(true);
            }
            catch
            {
                throw new ErroEsperado(HttpStatusCode.Unauthorized, "Token Invalid", "The provided token has a valid signature, but has an invalid content");
            }
        }
예제 #9
0
        public IHttpActionResult Activate([FromBody] ActivateAccountModel model)
        {
            var principal = JwtHelper.DecodeToken(model.Token, TokenAudiences.ActivateAccount, false);

            if (principal == null)
            {
                return(Forbidden());
            }

            var id   = principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            var user = DB.Users.Find(id);

            if (user == null)
            {
                return(Forbidden());
            }

            var token = DB.Tokens.FirstOrDefault(x => x.User.Id == id && x.TokenType == TokenType.ActivateAccount && x.Token == model.ActivationCode);

            if (token != null)
            {
                DB.Tokens.Remove(token);
                user.PhoneConfirmed = true;
                DB.SaveChanges();
                return(Empty());
            }

            return(BadRequest("Invalid activation code entered"));
        }
        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            if (!ValidateFields())
            {
                return;
            }

            var username = UsernameEntry.Text;
            var password = PasswordEntry.Password;

            if (RememberMeCheckbox.IsChecked != null)
            {
                Settings.Default.RememberMe = (bool)RememberMeCheckbox.IsChecked;
            }

            // check for remember me
            if (Settings.Default.RememberMe)
            {
                Settings.Default.Username = username;
                Settings.Default.Password = password;
            }

            DisableLoginButtons();

            // Call in new thread to liberate UI
            var thread = new Thread(() =>
            {
                MainWindow.Instance.PanelLoading     = true;
                MainWindow.Instance.PanelMainMessage = "Identification en cours";
                // All entry are valid, we can proceed with login
                try
                {
                    var token         = _userAccess.Login(username, password);
                    _user.UserToken   = token;
                    _user.Name        = username;
                    _user.IsConnected = true;

                    var id = JwtHelper.DecodeToken(token).UserId;
                    NativeFunction.connexion(new StringBuilder(token), token.Length, new StringBuilder(id), id.Length); // Todo kf, add userId

                    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
                    {
                        // Go to main menu if login is completed
                        _eventManager.Notice(new ChangeStateEvent()
                        {
                            NextState = Enums.States.MainMenu
                        });
                        MainWindow.Instance.PanelLoading = false;
                        Load.LoadOnLogin();
                    }));
                }
                catch (Exception exception)
                {
                    ShowError(exception.Message);
                }
            });

            thread.Start();
        }
예제 #11
0
        public void GetDailyTest()
        {
            var daily     = DailyAccess.GetDaily();
            var userToken = JwtHelper.DecodeToken(Token);

            Assert.IsFalse(daily.IsDone);
            Assert.AreEqual(userToken.UserId, daily.UserHashId);
        }
예제 #12
0
        public void CreateGameTest()
        {
            // create a basic game
            var game = GameAccess.CreateGame(DefaultGame);

            Assert.AreEqual(JwtHelper.DecodeToken(Token).UserId, game.HostHashId);
            GameAccess.DeleteGame(game.HashId);
        }
        /// <summary>
        /// handle Login with Facebook
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LogInWithFacebookButton_Click(object sender, RoutedEventArgs e)
        {
            DisableLoginButtons();
            MainWindow.Instance.PanelLoading     = true;
            MainWindow.Instance.PanelMainMessage = "Identification en cours";

            var dialog = new FacebookLoginWindow()
            {
                AppId = "719645478171450"
            };

            if (dialog.ShowDialog() == true)
            {
                if (string.IsNullOrWhiteSpace(dialog.AccessToken))
                {
                    ShowError("La fenêtre Facebook a été fermé avant la connexion.");
                    return;
                }

                // Get the access token from Facebook
                _user.FacebookToken   = dialog.AccessToken;
                _user.PlayerLoginType = User.LoginType.Facebook;

                var userId = _userAccess.GetFacebookId(_user.FacebookToken);
                if (string.IsNullOrWhiteSpace(userId))
                {
                    ShowError("L'utilisateur Facebook est invalide");
                    return;
                }

                // Login with facebook credentials
                try
                {
                    var token     = _userAccess.Login("", "", userId);
                    var userToken = JwtHelper.DecodeToken(token);
                    _user.FacebookId  = userId;
                    _user.UserToken   = token;
                    _user.Name        = userToken.Username;
                    _user.IsConnected = true;

                    // Go to main menu if login is completed
                    Load.LoadOnLogin();
                    MainWindow.Instance.PanelLoading = false;
                    _eventManager.Notice(new ChangeStateEvent()
                    {
                        NextState = Enums.States.MainMenu
                    });
                }
                catch (Exception exception)
                {
                    ShowError(exception.Message);
                }
            }
        }
예제 #14
0
        public void GetMapFromHashIdTest()
        {
            var mapHashId = ZoneAccess.CreateMap(DefaultZone.Name, DefaultZone.Content, DefaultZone.Level);
            var map       = ZoneAccess.GetMapFromId(mapHashId);

            Assert.AreEqual(DefaultZone.Name, map.Name);
            Assert.AreEqual(DefaultZone.Content, map.Content);
            Assert.AreEqual(JwtHelper.DecodeToken(Token).UserId, map.CreatorhashId);
            Assert.AreEqual(DefaultZone.Level, map.Level);

            ZoneAccess.DeleteMap(mapHashId);
        }
예제 #15
0
 public void Initialize()
 {
     try
     {
         Token = UserAccess.Register(DefaultUser.Username, DefaultUser.Password);
     }
     catch
     {
         Token = UserAccess.Login(DefaultUser.Username, DefaultUser.Password);
     }
     CurrentUserToken = JwtHelper.DecodeToken(Token);
 }
예제 #16
0
        /// <summary>
        /// Setzt den verwendeten Bearer Token sowie PermissionsSerial und EnvironmentId Header
        /// im <see cref="client"/>.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="login">Login Objekt mit den Token Informationen</param>
        /// <returns></returns>
        public static HttpClient UseLogin(this HttpClient client, LoginResponseObject login)
        {
            Claim serialClaim = JwtHelper.DecodeToken(login.PermissionsToken).Claims
                                .FirstOrDefault(c => c.Type == BeepClaimTypes.PermissionsSerial);
            Claim envId = JwtHelper.DecodeToken(login.PermissionsToken).Claims
                          .FirstOrDefault(c => c.Type == BeepClaimTypes.EnvironmentId);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", login.IdentityToken);
            client.DefaultRequestHeaders.Remove(BeepClaimTypes.PermissionsSerial);
            client.DefaultRequestHeaders.Remove(BeepClaimTypes.EnvironmentId);
            client.DefaultRequestHeaders.Add(BeepClaimTypes.PermissionsSerial, serialClaim?.Value);
            client.DefaultRequestHeaders.Add(BeepClaimTypes.EnvironmentId, envId?.Value);
            return(client);
        }
예제 #17
0
        public async Task <IHttpActionResult> BeginActivateAsync([FromUri] string token)
        {
            var principal = JwtHelper.DecodeToken(token, TokenAudiences.ActivateAccount, false);

            if (principal == null)
            {
                return(Forbidden());
            }

            //
            var user = DB.Users.Find(principal.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (user == null)
            {
                return(Forbidden());
            }

            //
            var activateToken = user.Tokens.FirstOrDefault(x => x.TokenType == TokenType.ActivateAccount);

            if (activateToken == null)
            {
                return(Forbidden());
            }

            //  send confirmation email
            await smsService.SendAsync(new SendSMSOptions()
            {
                Destinations = new string[] { user.Email },
                Message      = $"Here's your activation code: {activateToken.Token}"
            });

            //else
            //{

            //    //  send confirmation email
            //    await emailService.SendAsync(new SendMailOptions()
            //    {
            //        Subject = "Activate Account",
            //        Destinations = new string[] { user.Email },
            //        IsHtml = false,
            //        Message = $"Hello {user.FullName.Split(' ')}, here's your account activation code {activateToken.Token}"
            //    });
            //}


            return(Empty());
        }
예제 #18
0
        public void LoginWithExistingFacebookUserTest()
        {
            try
            {
                var tokenString = UserAccess.Login(FacebookUser.Username, "", FacebookUser.FacebookId);
                var token       = JwtHelper.DecodeToken(tokenString);

                if (string.IsNullOrWhiteSpace(token?.Username))
                {
                    Assert.Fail();
                }
            }
            catch (Exception)
            {
                Assert.Fail();
            }
        }
예제 #19
0
        public void LoginWithExistingAppUserTest()
        {
            try
            {
                var tokenString = UserAccess.Login(AppUser.Username, AppUser.Password);
                var token       = JwtHelper.DecodeToken(tokenString);

                if (string.IsNullOrWhiteSpace(token?.Username))
                {
                    Assert.Fail();
                }
            }
            catch (Exception e)
            {
                Assert.Fail(e.Message);
            }
        }
예제 #20
0
        public static UserToken GetUserToken()
        {
            try
            {
                var token = HttpContext.Current.Request.Headers["Authorization"];

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw HttpResponseExceptionHelper.Create("NULL or empty token - Secure controller", HttpStatusCode.Forbidden);
                }

                return(JwtHelper.DecodeToken(token));
            }
            catch (Exception)
            {
                throw HttpResponseExceptionHelper.Create("Invalid token - Secure controller", HttpStatusCode.Forbidden);
            }
        }
예제 #21
0
        public void ListFriendsZonesTest()
        {
            // create map
            var mapHashId    = ZoneAccess.CreateMap(DefaultZone.Name, DefaultZone.Content, DefaultZone.Level);
            var decodedToken = JwtHelper.DecodeToken(Token);


            //create new public user
            try
            {
                UserToken.Token = UserAccess.Register(DefaultUser.Username + "1", DefaultUser.Password);
            }
            catch
            {
                UserToken.Token = UserAccess.Login(DefaultUser.Username + "1", DefaultUser.Password);
            }

            var zones = ZoneAccess.GetMyFriendsZones();

            Assert.AreEqual(0, zones.Count);

            // Add user as friend
            var friendsList = new List <BasicUserInfo>
            {
                new BasicUserInfo()
                {
                    HashId   = decodedToken.UserId,
                    Username = decodedToken.Username
                }
            };

            FriendAccess.UpdateFriends(friendsList);

            zones = ZoneAccess.GetMyFriendsZones();
            Assert.AreEqual(1, zones.Count);

            // delete new user
            UserAccess.DeleteUser();


            // Delete Map
            UserToken.Token = Token;
            ZoneAccess.DeleteMap(mapHashId);
        }
예제 #22
0
        public static UserToken GetWarsimUserToken()
        {
            try
            {
                var token = HttpContext.Current.Request.Headers["Authorization"];

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw HttpResponseExceptionHelper.Create("Null or empty auth token", HttpStatusCode.Forbidden);
                }

                return(JwtHelper.DecodeToken(token));
            }
            catch (Exception)
            {
                return(null);
                //throw HttpResponseExceptionHelper.Create("Invalid auth token", HttpStatusCode.Forbidden);
            }
        }
예제 #23
0
        public override void OnMessage(string message)
        {
            if (_token == null && !string.IsNullOrWhiteSpace(message))
            {
                try
                {
                    _token = JwtHelper.DecodeToken(message);

                    if (!ConnectedUsersHash.Contains(_token.UserId))
                    {
                        ConnectedUsersHash.Add(_token.UserId);
                    }
                }
                catch (Exception)
                {
                    _token = null;
                }
            }
        }
예제 #24
0
        public void Initialize()
        {
            try
            {
                OtherUserToken = UserAccess.Register(DefaultUser.Username + "2", DefaultUser.Password);
            }
            catch (Exception)
            {
                OtherUserToken = UserAccess.Login(DefaultUser.Username + "2", DefaultUser.Password);
            }

            try
            {
                Token = UserAccess.Register(DefaultUser.Username, DefaultUser.Password);
            }
            catch
            {
                Token = UserAccess.Login(DefaultUser.Username, DefaultUser.Password);
            }
            CurrentUserToken = JwtHelper.DecodeToken(Token);
            DefaultGame      = new GameModel()
            {
                Name            = "Default new game",
                MaxPlayersCount = 3,
                IsPrivate       = false,
                ZonesHashId     = new List <string>()
                {
                    "testId"
                }
            };

            OtherPlayerGame = new GameModel()
            {
                Name            = "Defaulst new game",
                MaxPlayersCount = 3,
                IsPrivate       = false,
                ZonesHashId     = new List <string>()
                {
                    "testId"
                }
            };
        }
예제 #25
0
        protected override void OnWebSocketOpen()
        {
            var userToken       = JwtHelper.DecodeToken(this.Context.QueryString.Get("auth_token"));
            var channelIdString = this.Context.QueryString.Get("channel_id");

            Guid channelId;

            // If invalid token, close the connection
            if (userToken == null || string.IsNullOrEmpty(channelIdString) || !Guid.TryParse(channelIdString, out channelId))
            {
                this.Sessions.CloseSession(this.ID, 2000, "Invalid query parameters");
                return;
            }

            try
            {
                this._warsimUser = this._gameManager.GetUser(userToken.UserId);
            }
            catch
            {
                this.Sessions.CloseSession(this.ID, 2001, "This user isn't connected");
                return;
            }

            this._channel = this._chatManager.JoinChannel(this._warsimUser, channelId);

            this._warsimUser.ChatWebSocketId = this.ID;
            this._warsimUser.ActiveChannelId = channelId;

            // Send current channel state to new user
            this.Send(EventBuilder.Build(new ChannelStateMessage
            {
                ActiveUsers = this._channel.ActiveUsers.Select(WarsimClientUser.Map).ToList(),
                Messages    = this._channel.Messages
            }).Serialize());

            this.BroadcastToChannel(EventBuilder.Build(new UserJoinedChannelMessage
            {
                UserId   = this._warsimUser.UserId,
                Username = this._warsimUser.Username
            }).Serialize());
        }
예제 #26
0
파일: CoreHub.cs 프로젝트: Euler-KB/BusWork
        public override async Task OnConnected()
        {
            var auth = this.Context.Headers["Authorization"];
            if (auth?.StartsWith("Bearer") == true)
            {
                var userAuth = JwtHelper.DecodeToken(auth.Split(' ').Last(), validateLifetime: false);
                if (userAuth != null)
                {
                    if (userAuth.IsInRole(UserRoles.Admin))
                    {
                        await Groups.Add(Context.ConnectionId, UserRoles.Admin);
                    }
                    else if (userAuth.IsInRole(UserRoles.User))
                    {
                        await Groups.Add(Context.ConnectionId, UserRoles.User);
                    }
                }
            }

        }
예제 #27
0
        private void OnGameStateUpdate(UpdatedGameStateMessage msg, DateTime timestamp)
        {
            if (!this.GameHosts.ContainsKey(msg.GameId))
            {
                throw new Exception("This game id doesn't match any active game");
            }

            var game      = this.GameHosts[msg.GameId];
            var userToken = JwtHelper.DecodeToken(msg.UserToken);

            if (userToken == null || game.Spectators.ContainsKey(userToken.UserId) || !game.Players.ContainsKey(userToken.UserId))
            {
                throw new Exception("This user is not allowed to change the map state");
            }

            // Update the current map state
            var stats = game.Map.UpdateScene(msg.UpdatedSceneObjects, userToken.UserId, timestamp);

            game.GameStatisticsUpdates.Add(stats);

            this.BroadcastGameState(game);
        }
예제 #28
0
        protected override void OnWebSocketOpen()
        {
            var userToken = JwtHelper.DecodeToken(this.Context.QueryString.Get("auth_token"));
            var udpPort   = this.Context.QueryString.Get("udp_port");

            // If invalid query parameters, close the connection
            if (userToken == null || string.IsNullOrEmpty(udpPort))
            {
                this.Sessions.CloseSession(this.ID, 2000, "Invalid query parameters");
                return;
            }

            // Add user to connected users
            if (this._userManager.Users.ContainsKey(userToken.UserId))
            {
                this.Sessions.CloseSession(this.ID, 2001, "User already connected");
                return;
            }

            this._warsimUser = this._userManager.ConnectUser(userToken.UserId, userToken.Username);
            this._warsimUser.UserWebSocketId = this.ID;

            // Save user UDP endpoint
            this._warsimUser.GameUdpEndPoint = new IPEndPoint(
                this.Context.UserEndPoint.Address,
                int.Parse(udpPort));

            // User has now connected to the game and is visible to other users
            var ev = EventBuilder.Build(new UserConnectedMessage
            {
                UserId   = this._warsimUser.UserId,
                Username = this._warsimUser.Username
            });

            this.Sessions.Broadcast(ev.Serialize());
        }
예제 #29
0
        public void Initialize()
        {
            try
            {
                Token = UserAccess.Register(DefaultUser.Username, DefaultUser.Password);
            }
            catch (Exception)
            {
                Token = UserAccess.Login(DefaultUser.Username, DefaultUser.Password);
            }

            var userToken = JwtHelper.DecodeToken(Token);

            // Delete all zones
            var zones = ZoneAccess.GetMyZones();

            foreach (var zone in zones)
            {
                ZoneAccess.DeleteMap(zone.HashId);
            }

            DefaultZone = new MapModel()
            {
                Content = "Default Content",
                Level   = 0,
                Name    = "newZone2134321"
            };

            DefaultLeader = new LeaderModel()
            {
                PlayerHashId = userToken.UserId,
                PlayerName   = userToken.Username,
                Points       = 100
            };
            DefaultZone.HashId = ZoneAccess.CreateMap(DefaultZone.Name, DefaultZone.Content, DefaultZone.Level);
        }
        public void AddFriendTest()
        {
            var userToken = "";

            try
            {
                userToken = UserAccess.Register(DefaultUser.Username + "1", DefaultUser.Password);
            }
            catch
            {
                userToken = UserAccess.Login(DefaultUser.Username + "1", DefaultUser.Password);
            }
            var decodedToken = JwtHelper.DecodeToken(userToken);

            // Add user as friend
            UserToken.Token = Token;
            var friendsList = new List <BasicUserInfo>
            {
                new BasicUserInfo()
                {
                    HashId   = decodedToken.UserId,
                    Username = decodedToken.Username
                }
            };

            FriendAccess.UpdateFriends(friendsList);

            // Verify the friend
            var friends = FriendAccess.GetFriends();

            Assert.AreEqual(1, friends.Count);

            // delete new user
            UserToken.Token = userToken;
            UserAccess.DeleteUser();
        }