public async Task SignInOutIn()
 {
     var context = CreateContext();
     var handler = new AuthHandler();
     context.SetFeature<IHttpAuthenticationFeature>(new HttpAuthenticationFeature() { Handler = handler });
     var user = new ClaimsPrincipal();
     await context.Authentication.SignInAsync("ignored", user);
     Assert.True(handler.SignedIn);
     await context.Authentication.SignOutAsync("ignored");
     Assert.False(handler.SignedIn);
     await context.Authentication.SignInAsync("ignored", user);
     Assert.True(handler.SignedIn);
     await context.Authentication.SignOutAsync("ignored", new AuthenticationProperties() { RedirectUri = "~/logout" });
     Assert.False(handler.SignedIn);
 }
Beispiel #2
0
        /// <summary>
        /// Attempts to login using information from properties.
        /// </summary>
        public async void AttemptLogin()
        {
            DisplayLoginWindow = false;
            DisplayLoading     = true;
            OnPropertyChanged(nameof(DisplayLoginWindow));
            OnPropertyChanged(nameof(DisplayLoading));
            string passwordSalt = await APIHandler <string> .GetOne($"Auth/GetSalt/{Username}");

            if (passwordSalt != null)
            {
                (int UserID, string SessionKey)sessionTuple =
                    await APIHandler <(int UserID, string SessionKey)> .GetOne($"Auth/Login/{Username}/{AuthHandler.EncryptPassword(Password, passwordSalt)}");

                if (sessionTuple != default)
                {
                    AuthHandler.UserID     = sessionTuple.UserID;
                    AuthHandler.SessionKey = sessionTuple.SessionKey;
                    await AuthHandler.InitializeAuth();

                    Frame mainFrame = Window.Current.Content as Frame;
                    mainFrame?.Navigate(Type.GetType($"{Application.Current.GetType().Namespace}.MainPage"));
                }
                else
                {
                    DisplayLoginError(Constants.LOGIN_ERROR);
                }
            }
            else
            {
                DisplayLoginError(Constants.LOGIN_ERROR);
            }
        }
Beispiel #3
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            bool refreshUser = (bool)e.Argument;   // the 'argument' parameter resurfaces here


            BackgroundWorker worker = sender as BackgroundWorker;

            // Check Environment
            Launcher L = new Launcher(Offline);
            Manager  U = new Manager();

            L.CheckDirectories();

            // Test User
            string MCPlayerName = null;
            string UserAccount  = "none";
            string MCUID        = null;

            worker.ReportProgress(25);


            if (refreshUser == true)
            {
                if (U.GetDefault() != Guid.Empty)
                {
                    // Get Account
                    MCUserAccount Account = U.GetAccount(U.GetDefault());

                    // Validate Account
                    AuthHandler A = new AuthHandler();
                    try
                    {
                        Account.accessToken = A.Refresh(Account.accessToken, Account.clientToken);
                        U.SaveAccount(Account);
                    }
                    catch (MCInvalidTokenException)
                    {
                        FrmRefreshToken fTokRefresh = new FrmRefreshToken(Account);
                        DialogResult    res         = fTokRefresh.ShowDialog();
                        if (res == DialogResult.Cancel)
                        {
                            U.SetDefault(Guid.Empty);
                        }
                        fTokRefresh.Dispose();
                    }
                    catch (Exception)
                    {
                        DialogResult res = DialogResult.No;
                        Invoke(new Action(() =>
                        {
                            res = MessageBox.Show(this, "In Offlinemodus wechseln?", "Verbindungsfehler zu Mojang!", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                        }));

                        if (res == DialogResult.Yes)
                        {
                            Offline = true;
                            Invoke(new Action(() =>
                            {
                                MnuAccounts.Enabled = false;
                            }));
                        }
                        else
                        {
                            U.SetDefault(Guid.Empty);
                        }
                    }
                }
            }

            if (U.GetDefault() != Guid.Empty)
            {
                MCPlayerName = U.GetPlayerName(U.GetDefault());
                MCUID        = U.GetMCProfileID(U.GetDefault());
                UserAccount  = U.GetAccount(U.GetDefault()).username;
            }
            // set statusbar
            Invoke(new Action(() =>
            {
                LblDefaultAccount.Text = UserAccount;
                LstPacks.Clear();
                lst_packs_images.Images.Clear();
            }));

            worker.ReportProgress(50);

            // Get Packs from Server
            try
            {
                if (Offline == false)
                {
                    L.LoadAvailablePacks(MCPlayerName, MCUID);
                    MCAvailablePacks packs = L.GetAvailablePacks();
                    if (packs.Packs != null)
                    {
                        foreach (MCAvailablePack Pack in packs.Packs)
                        {
                            ListViewItem LvItem = new ListViewItem(Pack.Name, Pack.Name)
                            {
                                Font = new Font("Thaoma", 16, FontStyle.Bold)
                            };
                            Invoke(new Action(() =>
                            {
                                lst_packs_images.Images.Add(Pack.Name, L.GetPackIcon(Pack));
                                LstPacks.Items.Add(LvItem);
                            }));
                        }
                    }
                }
                else
                {
                    L.LoadInstalledPacks();
                    MCPacksInstalled Packs = L.GetInstalledPacks();
                    if (Packs.packs != null)
                    {
                        foreach (MCPacksInstalledPack Pack in Packs.packs)
                        {
                            ListViewItem LvItem = new ListViewItem(Pack.Name, Pack.Name)
                            {
                                Font = new Font("Thaoma", 16, FontStyle.Bold)
                            };
                            Invoke(new Action(() =>
                            {
                                if (L.GetPackIconOffline(Pack) != null)
                                {
                                    lst_packs_images.Images.Add(Pack.Name, L.GetPackIconOffline(Pack));
                                }
                                LstPacks.Items.Add(LvItem);
                            }));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Invoke(new Action(() =>
                {
                    MessageBox.Show(this, ex.Message.ToString(), "Verbindungsfehler zu Minestar!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }));
            }
            worker.ReportProgress(75);

            // Load installed Packs
            L.LoadInstalledPacks();

            // end worker
            worker.ReportProgress(100);
            System.Threading.Thread.Sleep(500);
        }
 static extern void deleteAuthorization(int platform, AuthHandler callback);
Beispiel #5
0
 private void OnCloseRequest(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
 {
     AuthHandler.Logout();
 }
Beispiel #6
0
        private static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, args) => Console.Error.WriteLine(args.ExceptionObject);

            ThreadPool.SetMinThreads(HttpServerSettings.Concurrency, HttpServerSettings.Concurrency);
            ThreadPool.SetMaxThreads(HttpServerSettings.Concurrency, HttpServerSettings.Concurrency);

            var cancellation = new CancellationTokenSource();
            var token        = cancellation.Token;

            var wsServer = new WsServer <User>(9999, ws => Users.Find(ws.HttpRequest.Cookies?.GetAuth()));

            var authHandler = new AuthHandler(login => Task.Run(() => wsServer.BroadcastAsync(user => AuthHandler.FormatUserMessage(user, login), token), token));
            var foodHandler = new FoodHandler((login, food) => Task.Run(() => wsServer.BroadcastAsync(user => FoodHandler.FormatUserMessage(user, login, food), token), token));

            var staticHandler = new StaticHandler("static", ctx =>
            {
                var url = ctx.Request.Url;
                if (url.HostNameType != UriHostNameType.Dns && url.HostNameType != UriHostNameType.IPv4 && url.HostNameType == UriHostNameType.IPv6)
                {
                    throw new HttpException(400, "Invalid host");
                }

                ctx.Response.Headers["X-Frame-Options"]         = "deny";
                ctx.Response.Headers["X-XSS-Protection"]        = "1; mode=block";
                ctx.Response.Headers["Content-Security-Policy"] = $"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src 'self' ws://{url.Host}:9999;";

                ctx.SetCsrfTokenCookie();
            });

            var httpServer = new HttpServer(8888)
                             .AddHandler("POST", "/signin", authHandler.SignInAsync)
                             .AddHandler("POST", "/signup", authHandler.SignUpAsync)
                             .AddHandler("POST", "/put", foodHandler.PutAsync)
                             .AddHandler("GET", "/get", foodHandler.GetAsync)
                             .AddHandler("GET", "/", staticHandler.GetAsync);

            Console.CancelKeyPress += (sender, args) =>
            {
                Console.Error.WriteLine("Stopping...");
                args.Cancel = true;
                cancellation.Cancel();
            };

            Task.WaitAll(wsServer.AcceptLoopAsync(token), httpServer.AcceptLoopAsync(token));
        }
 static extern void authorize(int platform, AuthHandler callback);
Beispiel #8
0
        /// <summary>
        /// The handler for when the string is received
        /// </summary>
        /// <param name="x">The received string</param>
        private bool ReadXMPPMessage(string x)
        {
            //<failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><incorrect-input/></failure>

            if (x.Contains("</stream:stream>"))
            {
                //TODO: Handle a disconnect
            }
            //Lazy hack, this converts the initial starting output to a valid XML doc
            else if (x.Contains("<stream:stream"))
            {
                x += "</stream:stream>";
            }
            //Lazy hack 2, This stops any stupid blah blah blah is not a part of this domain stuff
            x = x.Replace("stream:", "");

            try
            {
                //The XML Reader
                using (var reader = XmlReader.Create(new StringReader(x)))
                {
                    //Convert to XmlDocument for reading
                    var doc = new XmlDocument();
                    doc.Load(reader);
                    var el = doc.DocumentElement;

                    #region XmppPresenceHandler

                    if (el.Name == "presence" && el.HasChildNodes)
                    {
                        PresenceManager.HandleReceivedPresence(el);
                    }

                    #endregion XmppPresenceHandler

                    #region XmppMessageRecieveHandler

                    else if (el.Name == "message" && el.HasChildNodes)
                    {
                        MessageManager.HandleMessage(el);
                    }

                    #endregion XmppMessageRecieveHandler

                    else if (el.HasChildNodes)
                    {
                        foreach (var node in el.ChildNodes)
                        {
                            var xmlNode = (XmlNode)node;

                            //Handle RsoAuth

                            #region AuthHandler

                            if (xmlNode.Name == "mechanisms")
                            {
                                if (AuthHandler.HandleAuth(xmlNode))
                                {
                                    break;
                                }
                            }

                            #endregion AuthHandler

                            #region ConnectionSuccessHandler

                            if (el.Name == "success" && xmlNode.Name == "#text")
                            {
                                //I have no idea why I did this, but I did it. Don't question me Wild
                                if (int.TryParse(xmlNode.InnerText, out var output))
                                {
                                    Id = output;
                                }

                                //Say we logged in okay
                                OnSuccessLogin?.Invoke();

                                //Send another random static string
                                TcpClient.SendString(
                                    "<stream:stream " +
                                    $"to=\"{Host}\" " +
                                    "xml:lang=\"*\" " +
                                    "version=\"1.0\" " +
                                    "xmlns:stream=\"http://etherx.jabber.org/streams\" " +
                                    "xmlns=\"jabber:client\">");
                            }

                            #endregion ConnectionSuccessHandler

                            #region IDontKnowWtfThisIsButReturnBinding

                            if (xmlNode.Name == "rxep")
                            {
                                //This is sent from client to server after this is received. I honestly don't know this xmpp stuff so lets pretend we read that

                                TcpClient.SendString("<iq type=\"set\" id=\"0\"><bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"><resource>RC</resource></bind></iq>");

                                break;
                            }

                            #endregion IDontKnowWtfThisIsButReturnBinding

                            #region IQManager
                            if (el.Name == "iq")
                            {
                                IqManager.HandleIq(xmlNode, el);
                            }
                            #endregion IQManager
                        }
                    }
                    else
                    {
                        //TODO: <?xml version='1.0'?><stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='3891861776' from='pvp.net' version='1.0'>
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                Debugger.Log(0, "", new JavaScriptSerializer().Serialize(ex));
                return(false);
            }
        }
Beispiel #9
0
 private Server(int port)
 {
     WebSocket   = new WebSocketServer(port);
     AuthHandler = new AuthHandler();
 }
Beispiel #10
0
 /// <summary>
 /// Generates a username for the user
 /// </summary>
 public async void GenerateUserName()
 {
     UserName = await AuthHandler.GenerateUserName(Name);
 }
Beispiel #11
0
 /// <summary>
 /// Generates a random password and random salt for the new user
 /// </summary>
 public void GeneratePassword()
 {
     Password = AuthHandler.GenerateString(8);
     Salt     = AuthHandler.GenerateString(16);
 }
 void deleteConfirmfunc()
 {
     AuthHandler.HandleCharDelete(Exchange.worldClient.curChar, Exchange.worldClient);
 }
Beispiel #13
0
 public UserController(ILogger <ListController> logger, AuthHandler authHandler, Func <IListContext> contextFactory)
 {
     this.logger         = logger;
     this.authHandler    = authHandler;
     this.contextFactory = contextFactory;
 }
Beispiel #14
0
 public AuthController(UserRepository userService, SecurityRepository securityService, IMailService mailService)
 {
     _handler = new AuthHandler(userService, securityService, mailService);
 }