Ejemplo n.º 1
0
    public override void Update(Server server, float dt)
    {
        if (!loaded)
        {
            loaded = true;
            LoadBanlist(server);
        }

        if (server.banlist.ClearTimeBans() > 0)
        {
            SaveBanlist(server);
        }

        foreach (KeyValuePair <int, ClientOnServer> k in server.clients)
        {
            int            clientId = k.Key;
            ClientOnServer c        = k.Value;
            IPEndPointCi   iep1     = c.socket.RemoteEndPoint();

            if (server.banlist.IsIPBanned(iep1.AddressToString()))
            {
                IPEntry entry  = server.banlist.GetIPEntry(iep1.AddressToString());
                string  reason = entry.Reason;
                if (string.IsNullOrEmpty(reason))
                {
                    reason = "";
                }
                server.SendPacket(clientId, ServerPackets.DisconnectPlayer(string.Format(server.language.ServerIPBanned(), reason)));
                Console.WriteLine(string.Format("Banned IP {0} tries to connect.", iep1.AddressToString()));
                server.ServerEventLog(string.Format("Banned IP {0} tries to connect.", iep1.AddressToString()));
                server.KillPlayer(clientId);
                continue;
            }

            string username = c.playername;
            if (server.banlist.IsUserBanned(username))
            {
                UserEntry entry  = server.banlist.GetUserEntry(username);
                string    reason = entry.Reason;
                if (string.IsNullOrEmpty(reason))
                {
                    reason = "";
                }
                server.SendPacket(clientId, ServerPackets.DisconnectPlayer(string.Format(server.language.ServerUsernameBanned(), reason)));
                Console.WriteLine(string.Format("{0} fails to join (banned username: {1}).", (c.socket.RemoteEndPoint()).AddressToString(), username));
                server.ServerEventLog(string.Format("{0} fails to join (banned username: {1}).", (c.socket.RemoteEndPoint()).AddressToString(), username));
                server.KillPlayer(clientId);
                continue;
            }
        }
    }
Ejemplo n.º 2
0
        static void Zadatak7()
        {
            UserEntry     input     = UserEntry.ReadUserFromConsole();
            FormValidator validator = new FormValidator(10);

            if (validator.IsUserEntryValid(input))
            {
                Console.WriteLine("Successfully logged in.");
            }
            else
            {
                Console.WriteLine("Log in failed.");
            }
        }
Ejemplo n.º 3
0
 public static UserData ToUserDataSafely(UserEntry userEntry)
 {
     return(new UserData
     {
         UId = userEntry.UId,
         FullName = userEntry.FullName,
         UserName = userEntry.UserName,
         DateOfBirthUtcTicks = userEntry.DateOfBirthUtcTicks,
         Login = userEntry.Login,
         Avatar = userEntry.Avatar,
         ProfileHead = userEntry.ProfileHead,
         Description = userEntry.Description
     });
 }
Ejemplo n.º 4
0
        private void ConsumerOnReceived(object sender, BasicDeliverEventArgs e)
        {
            using var scope = _scopeFactory.CreateScope();
            var userRepo      = scope.ServiceProvider.GetRequiredService <IDataRepository <UserEntry> >();
            var machineRepo   = scope.ServiceProvider.GetRequiredService <IDataRepository <MachineEntry> >();
            var authEventRepo = scope.ServiceProvider.GetRequiredService <IDataRepository <AuthEventEntry> >() as AuthEventRepository;

            var message = JsonConvert.DeserializeObject <AgentAuthMessage>(Encoding.UTF8.GetString(e.Body));
            var user    = userRepo.Get(message.Username);
            var machine = machineRepo.Get(message.MachineName);

            if (user == null)
            {
                user = new UserEntry
                {
                    Username = message.Username,
                    Id       = Guid.NewGuid()
                };

                userRepo.Add(user);
            }

            if (machine == null)
            {
                machine = new MachineEntry
                {
                    Name = message.MachineName,
                    Ip   = message.MachineIp,
                    Id   = Guid.NewGuid()
                };

                machineRepo.Add(machine);
            }

            var eventDate = DateTime.Parse(message.EventDate);

            if (!authEventRepo.HasEvent(eventDate, machine.Id, user.Id, message.EventType))
            {
                authEventRepo.Add(new AuthEventEntry
                {
                    EventType = message.EventType,
                    EventTime = eventDate,
                    UserId    = user.Id,
                    MachineId = machine.Id,
                    Id        = Guid.NewGuid()
                });
            }

            agentUserModel.BasicAck(e.DeliveryTag, false);
        }
Ejemplo n.º 5
0
 internal SignupError TrySignUp(IPAddress who_requests, UserEntry new_user)
 {
     if (IsRecentIp(who_requests))
     {
         return(SignupError.HeadServerUnavailable);
     }
     if (!_db_server.InsertUser(new_user))
     {
         return(SignupError.UserExists);
     }
     //DatabaseUserInsert(new_user);
     _recent_user_creators_IPs.Enqueue(new TimestampedIP(who_requests, DateTime.UtcNow));
     return(SignupError.AllOk);
 }
Ejemplo n.º 6
0
 private void UserEntry_Completed(object sender, EventArgs e)
 {
     if (!string.IsNullOrEmpty(UserEntry.Text))
     {
         Helpers.Settings.UserEmail = UserEntry.Text;
         PasswordEntry.Focus();
     }
     else
     {
         //DependencyService.Get<IMessage>().LongAlert("User Email is blank!");
         UserDialogs.Instance.ShowError("User Email is blank!", 3000);
         UserEntry.Focus();
     }
 }
        public void SaveAndReadTest()
        {
            LoginElement login = new LoginElement("jdoe");

            login.Admin            = true;
            login.HashFunctionName = "SHA-1";
            entry.Login            = login;

            QuotaElement quota = new QuotaElement(2048);

            entry.Quota = quota;

            NameElement name = new NameElement("Doe", "John");

            entry.Name = name;

            StringBuilder sb     = new StringBuilder();
            XmlWriter     writer = new XmlTextWriter(new StringWriter(sb));

            entry.SaveToXml(writer);
            writer.Close();

            XmlDocument document = new XmlDocument();

            document.LoadXml(sb.ToString());

            UserEntry newEntry = new UserEntry();

            foreach (XmlNode node in document.FirstChild.ChildNodes)
            {
                ExtensionElementEventArgs args = new ExtensionElementEventArgs();
                args.ExtensionElement = node;
                args.Base             = newEntry;
                newEntry.Parse(args, new AtomFeedParser());
            }

            Assert.AreEqual(login.UserName, newEntry.Login.UserName,
                            "Parsed entry should have same username as original entry");
            Assert.IsTrue(newEntry.Login.Admin,
                          "Parsed entry should have admin property set to true");
            Assert.AreEqual(login.HashFunctionName, newEntry.Login.HashFunctionName,
                            "Parsed entry should have same hash function name as original entry");
            Assert.AreEqual(quota.Limit, newEntry.Quota.Limit,
                            "Parsed entry should have same quota as original entry");
            Assert.AreEqual(name.FamilyName, newEntry.Name.FamilyName,
                            "Parsed entry should have same family name as original entry");
            Assert.AreEqual(name.GivenName, newEntry.Name.GivenName,
                            "Parsed entry should have same given name as original entry");
        }
Ejemplo n.º 8
0
        }// EO CONSTRUCTOR

        internal async Task UpdateTwitchUserColour(OnMessageReceivedArgs e)
        {
            if (e == null)
            {
                return;
            }
            UserEntry user = await UserList.GetDBUserByTwitchID(e.ChatMessage.UserId);

            if (user == null)
            {
                return;
            }
            user._twitchColour     = e.ChatMessage.ColorHex;
            user._lastseenOnTwitch = Core.CurrentTime;
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Reformats and raise a botwide event when a twitch user is banned
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 /// <returns></returns>
 private async void TwitchOnUserBanned(object sender, OnUserBannedArgs e)
 {
     UserEntry BannedUser = await Program.Users.GetUserByTwitchUserName(e.UserBan.Username);
     BotChannel bChan = await Program.Channels.GetTwitchChannelByName(e.UserBan.Channel);
     BanEventArguments banEvent = new BanEventArguments(
         bChan,
         null,
         BannedUser,
         Core.CurrentTime,
         0,
         e.UserBan.BanReason,
         true
         );
     Program.BotEvents.RaiseBanEvent(banEvent);
 }
Ejemplo n.º 10
0
        private async Task ShakeCouch(BotChannel bChan, CouchSettings settings)
        {
            if (!settings._active || !settings._couches[bChan.Key].couchOpen)
            {
                return;
            }

            await Core.LOG(new LogEntry(LOGSEVERITY.INFO, PLUGINNAME, $"Shaking couch in {bChan.TwitchChannelName}."));

            Random        rng     = new Random();
            List <string> victims = new List <string>();

            foreach (string twitchUserName in settings._couches[bChan.Key].TwitchUsernames)
            {
                if (rng.Next(1, 100) <= 20)
                {
                    victims.Add(twitchUserName);
                }
            }
            if (victims.Count < 1)
            {
                Program.TwitchSayMessage(bChan.TwitchChannelName,
                                         dbStrings.GetRandomLine(bChan, "SHAKEF")
                                         );
                return;
            }
            string msg = string.Empty;

            foreach (string victim in victims)
            {
                settings._couches[bChan.Key].TwitchUsernames.Remove(victim);
                msg += victim + ",";
                UserEntry usr = await Program.Users.GetUserByTwitchDisplayName(victim);

                if (usr != null)
                {
                    CouchUserStats markUserStats = await UserStatsRead(bChan.Key, usr.Key);

                    markUserStats.CountBooted++;
                    UserStatsSave(bChan, markUserStats);
                }
            }
            Program.TwitchSayMessage(bChan.TwitchChannelName,
                                     dbStrings.GetRandomLine(bChan, "SHAKES", msg)
                                     );
            settings._couches[bChan.Key].lastActivationTime = Core.CurrentTime;
            SaveBaseSettings(bChan, PLUGINNAME, settings);
        }
Ejemplo n.º 11
0
        public async Task Pass([Optional] string target)
        {
            if (string.IsNullOrEmpty(target))
            {
                Logger.Log("No user specified", "PassSoP", LogSeverity.Error);
                await Context.Channel.SendMessageAsync("Tell me who you want to pass by writing !pass {@user}");

                return;
            }

            ulong     id    = Convert.ToUInt64(target.Substring(2, target.Length - 3).Replace("!", string.Empty));
            UserEntry entry = null;

            if (!SmashDatabase.HasUser(id))
            {
                Logger.Log("User not in database!", "PassSoP", LogSeverity.Error);
                await Context.Channel.SendMessageAsync("This user did not start his Smash Or Pass!");

                return;
            }

            entry = SmashDatabase.GetEntry(id);

            if (entry.RatedBy.Contains(Context.User.Id))
            {
                Logger.Log("User has already voted!", "PassSoP", LogSeverity.Error);
                await Context.Channel.SendMessageAsync($"You have already rated {entry.Name}. To see current results write: !score @{entry.Name}");

                return;
            }

            entry.Passes++;
            entry.RatedBy.Add(Context.User.Id);
            SmashDatabase.UpdateEntry(entry);

            var embed = new EmbedBuilder();

            embed.WithTitle("Smash Or Pass");
            embed.WithDescription($"{Context.User.Username} passed {entry.Name}!");
            embed.AddInlineField(entry.Smashes.ToString(), "Total Smashes");
            embed.AddInlineField(entry.Passes.ToString(), "Total Passes");
            embed.WithImageUrl(entry.Url);
            embed.WithColor(new Color(12, 212, 00));

            await Context.Channel.SendMessageAsync("", false, embed);

            Logger.Log($"User {Context.User.Username} passed {entry.Name}", "PassSoP", LogSeverity.Info);
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> AccountSettings()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Home"));
            }

            string userEmail = HttpContext.Session.GetString("Email");

            var currentCluster = HttpContext.Session.GetString("CurrentClusters");

            if (Startup.Database.ContainsKey(currentCluster))
            {
                var db = Startup.Database[currentCluster];

                if (HttpContext.Request.Query.ContainsKey("NewAlias"))
                {
                    string aliasEmail = HttpContext.Request.Query["NewAlias"];
                    if (aliasEmail.IndexOf('@') > 0)
                    {
                        UserEntry alias = new UserEntry(new UserID(), aliasEmail, userEmail, null);
                        db.User.Add(alias);
                        await db.SaveChangesAsync();
                    }
                }
                var aliases = new List <string>();
                foreach (var user in db.User)
                {
                    if (user.Alias == userEmail)
                    {
                        if (userEmail == user.Email)
                        {
                            ViewData["Password"] = user.Password;
                        }
                        else
                        {
                            aliases.Add(user.Email);
                        }
                    }
                }
                ViewData["Aliases"] = aliases;
            }

            ViewData["Email"]   = userEmail;
            ViewData["Account"] = GetAccountType(HttpContext.Session.GetString("isAuthorized") == "true", HttpContext.Session.GetString("isAdmin") == "true");
            AddViewData();
            return(View());
        }
Ejemplo n.º 13
0
    public bool UnbanPlayer(string username)
    {
        bool exists = false;

        for (int i = BannedUsers.Count - 1; i >= 0; i--)
        {
            UserEntry banneduser = BannedUsers[i];
            if (banneduser.UserName.Equals(username, StringComparison.InvariantCultureIgnoreCase))
            {
                exists = true;
                BannedUsers.RemoveAt(i);
                break;
            }
        }
        return(exists);
    }
Ejemplo n.º 14
0
        public async Task <UserEntry> AddEntry(UserEntry entry)
        {
            try
            {
                await _context.UserEntry.AddAsync(entry);

                await _context.SaveChangesAsync();

                return(entry);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }
        }
Ejemplo n.º 15
0
        private async Task ReactionAdded(Cacheable<IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            await Core.LOG(new LogEntry(LOGSEVERITY.INFO, "EventCatcherDiscord", "ReactionAdded"));
            UserEntry user = await Program.Users.GetUserByDiscordID(arg3.UserId);
            BotChannel bChan = await Program.Channels.GetDiscordGuildbyID((arg2 as SocketGuildChannel).Guild.Id);


            


            Program.BotEvents.RaiseDiscordReactionAdded(
                bChan,
                user,
                new DiscordReactionArgument(arg2.Id, arg3.MessageId, RESPONSEACTION.REMOVED, arg3.Emote.Name)
            );
        }
Ejemplo n.º 16
0
 public static UserData ToUserData(UserEntry userEntry)
 {
     return(new UserData
     {
         UId = userEntry.UId,
         FullName = userEntry.FullName,
         UserName = userEntry.UserName,
         DateOfBirthUtcTicks = userEntry.DateOfBirthUtcTicks,
         Email = userEntry.Email,
         PhoneNumber = userEntry.PhoneNumber,
         Login = userEntry.Login,
         Password = userEntry.Password,
         Avatar = userEntry.Avatar,
         ProfileHead = userEntry.ProfileHead,
         Description = userEntry.Description
     });
 }
Ejemplo n.º 17
0
        internal async void Connect()
        {
            UserEntry botUser = await Program.Users.GetUserByTwitchUserName("juanthebot");

            int botClientID = -1;

            int.TryParse(botUser._twitchUID, out botClientID);

            Client.ListenToFollows(_twitchID);
            Client.ListenToVideoPlayback(_twitchChannelName);
            Client.ListenToSubscriptions(_twitchID);
            Client.ListenToBitsEvents(_twitchID);
            // Verify
            //Client.ListenToRaid(_twitchID);
            //Client.ListenToWhispers(botUser._twitchUID);
            Client.Connect();
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> ManageUser()
        {
            AddViewData();
            var currentCluster = HttpContext.Session.GetString("CurrentClusters");

            if (Startup.Database.ContainsKey(currentCluster))
            {
                if (!User.Identity.IsAuthenticated || HttpContext.Session.GetString("isAdmin").Equals("false"))
                {
                    return(RedirectToAction("Index", "Home"));
                }
                var db = Startup.Database[currentCluster];
                if (!Object.ReferenceEquals(db, null))
                {
                    if (HttpContext.Request.Query.ContainsKey("AccountChangeEmail"))
                    {
                        string    email     = HttpContext.Request.Query["AccountChangeEmail"];
                        UserEntry userEntry = db.User.First(x => x.Email.Equals(email));
                        // db.User.Update(userEntry);
                        if (userEntry.isAdmin.Equals("true"))
                        {
                            userEntry.isAdmin      = "false";
                            userEntry.isAuthorized = "false";
                        }
                        else if (userEntry.isAuthorized.Equals("false"))
                        {
                            userEntry.isAuthorized = "true";
                        }
                        else
                        {
                            userEntry.isAdmin = "true";
                        }
                        await db.SaveChangesAsync();
                    }
                    List <string[]> userTable = new List <string[]>();
                    foreach (var user in db.User)
                    {
                        string   accountType = (user.Email == user.Alias) ? GetAccountType(user.isAuthorized == "true", user.isAdmin == "true") : "Alias";
                        string[] userString  = new string[] { ParseToUsername(user.Alias), user.Email, accountType };
                        userTable.Add(userString);
                    }
                    ViewData["Users"] = userTable;
                }
            }
            return(View());
        }
        public void Setup()
        {
            var key  = string.Empty;
            var user = default(UserEntry);

            this.data = new Dictionary <string, UserEntry>();

            for (int i = 1; i <= 3; i++)
            {
                key  = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{i}"));
                user = new UserEntry()
                {
                    Name = $"Demo{i}", FingerPrint = key
                };
                data.Add(key, user);
            }
        }
Ejemplo n.º 20
0
        public Main(BaseAuth auth, UserEntry user)
        {
            InitializeComponent();
            AuthModel          = auth;
            Users              = AuthModel.readAllUsers();
            User               = user;
            nicknameLabel.Text = "User: "******"Admin")
            {
                usersPanel.Enabled = false;
            }
            else
            {
                DisplayUsers();
            }
        }
        [HttpPost] //post method
        public ActionResult Delete(UserEntry delete)
        {
            string sInput   = delete.userInput;
            bool   bPresent = false; //variable to see if input was found

            //checks if user has input
            if (sInput == null)
            {
                ViewBag.MyQueue = "Please enter a Search";
            }
            else
            {
                //loops through each item in queue
                while (myQueue.Count != 0)
                {
                    //check to see if first element is the input
                    if (sInput == myQueue.Peek())
                    {
                        //if yes, delete it
                        myQueue.Dequeue();
                        ViewBag.MyQueue = sInput + " was deleted from the queue.";
                        bPresent        = true;
                    }
                    else
                    {
                        //if not, transfer to temp structure
                        myTempQueue.Enqueue(myQueue.Dequeue());
                    }
                }

                //reloads up normal structure
                while (myTempQueue.Count != 0)
                {
                    myQueue.Enqueue(myTempQueue.Dequeue());
                }

                //output if not found
                if (bPresent == false)
                {
                    ViewBag.MyQueue = sInput + " was not found in the queue.";
                }
            }

            return(View("Index"));
        }
Ejemplo n.º 22
0
        protected void lbStep1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(ddlDomains.SelectedValue))
            {
                try
                {
                    AppsService service  = new AppsService(ddlDomains.SelectedValue, UserContext.Current.Organization.GoogleAdminAuthToken);
                    UserFeed    userFeed = service.RetrieveAllUsers();

                    DataTable dt = new DataTable();
                    dt.Columns.Add(Resources.GoogleIntegrationControl_UsernameColumn_HeaderText, typeof(string));
                    dt.Columns.Add(Resources.GoogleIntegrationControl_FirstNameColumn_HeaderText, typeof(string));
                    dt.Columns.Add(Resources.GoogleIntegrationControl_LastNameColumn_HeaderText, typeof(string));
                    dt.Columns.Add(Resources.GoogleIntegrationControl_AdminColumn_HeaderText, typeof(string));

                    for (int i = 0; i < userFeed.Entries.Count; i++)
                    {
                        UserEntry userEntry = userFeed.Entries[i] as UserEntry;
                        dt.Rows.Add(userEntry.Login.UserName, userEntry.Name.GivenName, userEntry.Name.FamilyName, userEntry.Login.Admin ? Resources.GoogleIntegrationControl_AdminColumn_Value : string.Empty);
                    }

                    gvStep1Results.DataSource = dt;
                    gvStep1Results.DataBind();

                    mvStep1.SetActiveView(vwStep1Result);

                    lbImportUsers.Text    = Resources.GoogleIntegrationControl_ImportUsers_LinkButton_Text;
                    lbImportUsers.Visible = lbImportUsers.Enabled = dt.Rows.Count > 0;
                }
                catch (AppsException a)
                {
                    lblStep1Error.Text = string.Format(CultureInfo.CurrentCulture, Resources.GoogleIntegrationControl_GoogleAppsError_Text, a.ErrorCode, a.InvalidInput, a.Reason);
                    mvStep1.SetActiveView(vwStep1Error);
                }
                catch (Exception ex)
                {
                    ShowError(ex, lblStep1Error, mvStep1, vwStep1Error);
                }
            }
            else
            {
                lblStep1Error.Text = Resources.GoogleIntegrationControl_DomainMisingError_Text;
                mvStep1.SetActiveView(vwStep1Error);
            }
        }
Ejemplo n.º 23
0
        private async void TwitchOnChatCommandRecieved(object sender, OnChatCommandReceivedArgs e)
        {
                if(e.Command.ChatMessage.IsMe){return;}
                UserEntry usr = await Program.Users.GetUserByTwitchUserName(e.Command.ChatMessage.Username);
                if (usr == null) return;

                Program.BotEvents.RaiseOnCommandRecieved(new BotWideCommandArguments(){
                    source = MESSAGESOURCE.TWITCH, 
                    channel = e.Command.ChatMessage.Channel,
                    isBroadcaster = e.Command.ChatMessage.IsBroadcaster,
                    isModerator = e.Command.ChatMessage.IsModerator, 
                    user = usr, 
                    userDisplayName = e.Command.ChatMessage.DisplayName,
                    command = e.Command.CommandText.ToLower(),
                    message = e.Command.ChatMessage.Message,
                    arguments = e.Command.ArgumentsAsList
                });
        }
Ejemplo n.º 24
0
        internal bool TryLogIn(UserEntry user)
        {
            if (_authenticated_users.Count > AuthorizedUsersInitCapacity ||
                _authenticated_users.Find(e => e.LoginName == user.LoginName && e.PasswordHash == user.PasswordHash) != null)
            {
                return(false);
            }
            // throws InvalidOperation if multiple rows
            //UserEntry db_user = DatabaseAuthenticateAndSelectUser(user);

            if (!_db_server.CheckUserLogin(user.LoginName, user.PasswordHash))
            {
                return(false);
            }

            _authenticated_users.Add(user);
            return(true);
        }
Ejemplo n.º 25
0
        private bool TryLogIn(UserEntry user)
        {
            if (_authenticated_users.Count > AuthorizedUsersInitCapacity ||
                _authenticated_users.Find(e => e.Name == user.Name && e.PasswordHash == user.PasswordHash) != null)
            {
                return(false);
            }
            // throws InvalidOperation if multiple rows
            DB.User db_user = DatabaseAuthenticateAndSelectUser(user);

            if (db_user == null)
            {
                return(false);
            }

            _authenticated_users.Add(db_user);
            return(true);
        }
        public async Task <ActionResult> Create(UserEntryCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    User identityUser = await _userManager.GetUserAsync(User);

                    int linkedImagesCount = await _imageEntryRepo.CountImagesForUser(identityUser.Id);

                    if (linkedImagesCount > 2)
                    {
                        UserEntry entry = new UserEntry()
                        {
                            Address      = model.Address,
                            CommutingWay = model.CommutingWay,
                            User         = identityUser
                        };

                        await _userEntryRepo.AddEntry(entry);

                        identityUser.HasCompletedSignUp = true;
                        await _userRepo.Update(identityUser);
                    }
                    else
                    {
                        int imageShortage = 3 - linkedImagesCount;
                        ViewBag.imageError =
                            $"We need at least 3 images of you. Upload {imageShortage} extra {(imageShortage == 1 ? "image" : "images")}.";
                        return(View(model));
                    }

                    return(Redirect("/Home/index"));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    ViewBag.error = "Something unexpected went wrong.";
                    return(View(model));
                }
            }

            return(View(model));
        }
Ejemplo n.º 27
0
        private async void TwitchInUserJoined(object sender, TwitchLib.Client.Events.OnUserJoinedArgs e)
        {
            if (TimerStuff.Uptime < 300)
            {
                return;
            }
            BotChannel bChan = await Program.Channels.GetTwitchChannelByName(e.Channel);

            if (!bChan.isLive)
            {
                return;
            }
            UserEntry user = await Program.Users.GetUserByTwitchUserName(e.Username);

            CouchSettings settings = await Settings <CouchSettings>(bChan, PLUGINNAME);

            if (user == null || settings == null)
            {
                return;
            }
            if (settings._greeted.Exists(p => p == user._twitchUsername))
            {
                return;
            }
            if (!settings._couches.ContainsKey(bChan.Key))
            {
                settings._couches[bChan.Key] = new CouchEntry();
            }
            if (user != null && bChan != null && settings._active)
            {
                CouchUserStats uStats = await GetUserCouchStats(bChan.Key, user.Key);

                if (uStats.CountSeated >= settings.potatoGreeting)
                {
                    if (!await dbStrings.TableInit(bChan))
                    {
                        await DBStringsFirstSetup(bChan);
                    }
                    Program.TwitchSayMessage(e.Channel, dbStrings.GetRandomLine(bChan, "GREET").Replace("[USER]", user._twitchDisplayname));
                    settings._greeted.Add(user._twitchUsername);
                    SaveBaseSettings(bChan, PLUGINNAME, settings);
                }
            }
        }
Ejemplo n.º 28
0
        private UserEntry DBReadTwitchUserByName(string twitchname)
        {
            using (SQLiteCommand cmd = new SQLiteCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection  = Core.Data;
                cmd.CommandText = $"SELECT * FROM \"{EXTENSIONNAME}\" WHERE twitchUsername IS @twitchname";
                cmd.Parameters.AddWithValue("@twitchname", twitchname);
                SQLiteDataReader result;
                try
                {
                    result = cmd.ExecuteReader();
                }
                catch (Exception)
                {
                    throw;
                }
                result.Read();
                UserEntry user = new UserEntry
                {
                    linked             = result.GetBoolean(0),
                    _discordUsername   = result.GetString(1),
                    _lastseen          = result.GetInt32(2),
                    _lastseenOnTwitch  = result.GetInt32(3),
                    _twitchUID         = result.GetString(4),
                    _twitchUsername    = result.GetString(5),
                    _twitchDisplayname = result.GetString(6),
                    _twitchColour      = result.GetString(7),
                    _twitchLogo        = result.GetString(8),
                    _discordUID        = (ulong)result.GetInt64(11),
                    lastChange         = (int)result.GetInt64(13),
                    lastSave           = (int)result.GetInt64(14)
                };
                _UserCache.Add(user);

                if (_UserCache[_UserCache.Count - 1]._twitchUsername != twitchname)
                {
                    Core.LOG(new LogEntry(LOGSEVERITY.ERROR, "BotUsers", $"Found DB username {twitchname}, read it and added to cache but last cache entry did not match!"));
                    return(null);
                }

                return(_UserCache[_UserCache.Count - 1]);
            }
        }
Ejemplo n.º 29
0
        private void CreateNewDiscordUser(ulong uid, UserEntry user)
        {
            SocketUser userinfo = Program.DiscordClient.GetUser(uid);

            using (SQLiteCommand cmd = new SQLiteCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection  = Core.Data;
                cmd.CommandText = $"INSERT INTO \"{EXTENSIONNAME}\" VALUES (" +
                                  $"@linked, " +
                                  $"@username, " +
                                  $"@lastseen, " +
                                  $"@lastseenOnTwitch, " +
                                  $"@twitchUID, " +
                                  $"@twichUsername, " +
                                  $"@twitchDisplayname, " +
                                  $"@twitchColour, " +
                                  $"@twitchLogo, " +
                                  $"@twitchCreated, " +
                                  $"@twitchLastUpdate, " +
                                  $"@discordUID, " +
                                  $"@discordStatus, " +
                                  $"@lastChange, " +
                                  $"@lastSave" +
                                  $")";
                cmd.Parameters.AddWithValue("@linked", user.linked);
                cmd.Parameters.AddWithValue("@username", userinfo.Username);
                cmd.Parameters.AddWithValue("@lastseen", Core.CurrentTime);
                cmd.Parameters.AddWithValue("@lastseenOnTwitch", user._lastseenOnTwitch);
                cmd.Parameters.AddWithValue("@twitchUID", user._twitchUID);
                cmd.Parameters.AddWithValue("@twichUsername", user._twitchUsername);
                cmd.Parameters.AddWithValue("@twitchDisplayname", user._twitchDisplayname);
                cmd.Parameters.AddWithValue("@twitchColour", user._twitchColour);
                cmd.Parameters.AddWithValue("@twitchLogo", user._twitchLogo);
                cmd.Parameters.AddWithValue("@twitchCreated", user._twitchCreated);
                cmd.Parameters.AddWithValue("@twitchLastUpdate", user._twitchLastUpdate);
                cmd.Parameters.AddWithValue("@discordUID", uid);
                cmd.Parameters.AddWithValue("@discordStatus", userinfo.Status);
                cmd.Parameters.AddWithValue("@lastChange", Core.CurrentTime);
                cmd.Parameters.AddWithValue("@lastSave", Core.CurrentTime);
                cmd.ExecuteNonQuery();
                //await Core.LOG(new Discord.LogMessage(Discord.LogSeverity.Warning, PLUGINNAME, $"Created entry for Discord user {userinfo.Username}"));
            }
        }
        private UserEntry BuildUser(User user, bool deleted)
        {
            var entry = new UserEntry
            {
                ReferenceId  = user.Id,
                ExternalId   = user.Id,
                Email        = user.PrimaryEmail,
                Disabled     = user.Suspended.GetValueOrDefault(false),
                Deleted      = deleted,
                CreationDate = user.CreationTime
            };

            if (string.IsNullOrWhiteSpace(entry.Email) && !entry.Deleted)
            {
                return(null);
            }

            return(entry);
        }
Ejemplo n.º 31
0
        public bool Register(UserEntry entryData)
        {
            RemoteAsyncUserRegisterDelegate registerDelegate =
                new RemoteAsyncUserRegisterDelegate(pki.Register);
            byte[] challenge = registerDelegate(entryData);

            if (challenge == null)
                return false; // wasn't allowed to register

            // cipher challenge with private key
            CipheredChallenge cc = new CipheredChallenge();
            cc.Signature = rsa.SignData(challenge, "SHA1");
            cc.Sender = entryData.NodeId;

            // send to pki
            RemoteAsyncUserRegisterChallengeResponseDelegate responseDelegate =
                new RemoteAsyncUserRegisterChallengeResponseDelegate(pki.ChallengeResponse);
            bool result = responseDelegate(cc);

            return result;
        }
Ejemplo n.º 32
0
        public static SignedEntry sign(UserEntry ue)
        {
            SignedEntry signedEntry = new SignedEntry();
            signedEntry.Entry = ue;

            byte[] data = Encoding.Default.GetBytes(ue.ToString());
            signedEntry.Signature = _rsa.SignData(data, "SHA1");

            return signedEntry;
        }
Ejemplo n.º 33
0
        public byte[] Register(UserEntry entry)
        {
            Console.WriteLine("Got register request from: " + entry.NodeId);

            if (IsInPending(entry))
            {
                Console.WriteLine("Denying access. User with same name/address is pending.");
                return null; // user with same id is already registered, deny
            }

            int challenge = _rand.Next();
            byte[] rawChallenge = Encoding.Default.GetBytes(challenge.ToString());
            PendingChallenge pc = new PendingChallenge(rawChallenge, DateTime.Now);
            waitingChallenge.Add(entry, pc);

            return rawChallenge;
        }
Ejemplo n.º 34
0
 public bool TimeBanPlayer(string username, string bannedby, string reason, int intervalMinutes)
 {
     if (IsUserBanned(username))
     {
         return false;
     }
     UserEntry newBan = new UserEntry();
     newBan.UserName = username;
     newBan.BannedBy = bannedby;
     if (intervalMinutes > 0)
     {
         newBan.BannedUntil = DateTime.UtcNow + TimeSpan.FromMinutes(intervalMinutes);
     }
     if (!string.IsNullOrEmpty(reason))
     {
         newBan.Reason = reason;
     }
     BannedUsers.Add(newBan);
     return true;
 }
Ejemplo n.º 35
0
 private bool IsInPending(UserEntry entry)
 {
     bool result = false;
     foreach (UserEntry e in waitingChallenge.Keys)
     {
         if (e.NodeId.Equals(entry.NodeId) && e.Address.Equals(entry.Address))
         {
             result = true;
             break;
         }
     }
     return result;
 }
Ejemplo n.º 36
0
 public virtual UserInfo GetUserInfo(IIdentity userIdentity)
 {
     UserEntry ue = null;
     if (_users.TryGetValue(userIdentity.Name, out ue))
     {
         if (ue.ReadDate.AddMinutes(5) < DateTime.Now)
         {
             ue = null;
         }
         else
         {
             return ue.User;
         }
     }
     //: ue == null now
     var users = Db.Find<UserInfo>(x => x.Login == userIdentity.Name && x.Active == true).ToList();
     UserInfo ui = null;
     if (users.Count == 0)
     {
         lock (this)
         {
             if (_users.TryGetValue(userIdentity.Name, out ue) && ue.ReadDate.AddMinutes(5) < DateTime.Now)
                 return ue.User;
             else
                 ui = UserNotFound(userIdentity);
         }
     }
     else
     {
         ui = UserFound(userIdentity, users[0]);
     }
     if (ui != null)
     {
         ui.Passwd = null;
         ue = new UserEntry
         {
             ReadDate = DateTime.Now,
             User = ui
         };
         _users.TryAdd(userIdentity.Name, ue);
     }
     //
     return ui;
 }
Ejemplo n.º 37
0
        static void Main(string[] args)
        {
            if (args.Length == 0 || args.Length > 2)
            {
                System.Windows.Forms.MessageBox.Show("Invalid server invocation");
                return;
            }

            loadRPCServices(args);
            _serviceAvailable = true;

            try
            {
                User savedUser = new User();
                string filename = ".\\user" + _serverPort + ".txt";
                TextReader tr = new StreamReader(filename);
                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(savedUser.GetType());
                savedUser = (User)x.Deserialize(tr);
                tr.Close();

                _user = savedUser;
            }
            catch (FileNotFoundException)
            {
                _user = new User();
                _user.SpoofAdress = _myUri;
            }

            /* load or generate pub/priv key for node */
            loadNodePublicPrivateKeys();

            _form = new ServerForm(_myUri);

            /* PKI Communication */
            RSACryptoServiceProvider rsaPki = null;
            if ((rsaPki = readRSAPKI()) == null)
            {
                MessageBox.Show("Couldn't load pubkey of PKI.");
                Application.Exit();
            }
            _pkiCommunicator = new NodePKIHelper(_rsaProvider, rsaPki, args[1]);
            _myUserEntry = new UserEntry();
            _myUserEntry.NodeId = _user.Username;
            _myUserEntry.Address = _myUri;
            _myUserEntry.PubKey = _rsaProvider.ToXmlString(false);

            if (_pkiCommunicator.Register(_myUserEntry))
            {
                Application.Run(_form);
            }
            else
            {
                Application.Exit();
            }
        }