Ejemplo n.º 1
0
        public static bool IsAuthorized(Request _request, out TGUser _user)
        {
            OpenFormGraphManager manager = new OpenFormGraphManager();

            string username  = _request.Headers["Username"].First();
            string authToken = _request.Headers["AuthorizationToken"].First();

            TGUser user = manager.GetUser(username);

            if (user != null)
            {
                TGUserAuthorization userAuth = manager.GetUserAuthorization(user.Guid, authToken);

                if (userAuth != null &&
                    !userAuth.IsExpired())
                {
                    _user = user;

                    return(true);
                }
            }

            _user = null;
            return(false);
        }
Ejemplo n.º 2
0
        public static async Task <bool> Execute(TGMessage message, TGUser ncm, GroupConfigurationObject gco, string langcode)
        {
            if (gco.useBotScreen != true)   // Skipping because disabled.
            {
                return(true);
            }

            var query = "SELECT * FROM xenf_autokick WHERE `group`={0} AND `user`={1}";
            var fQry  = string.Format(query, message.chat.id, ncm.id);
            var w     = await SQL.QueryAsync(fQry);

            if (w.Count > 0)
            {
                return(true);
            }

            var UserScore = 500;

            if (ncm.username != null)
            {
                UserScore -= 50;
            }



            return(true);
        }
Ejemplo n.º 3
0
 public static void doFilterUser(TGMessage msg, TGUser user)
 {
     if (!user.is_bot)
     {
         try
         {
             bool b = false;
             b = Filters.XESFilter.autorem(msg, user);
             if (b == true)
             {
                 return;
             }
             b = Filters.XESFilter.namefilter(msg, user);
             if (b == true)
             {
                 return;
             }
             b = Filters.XESFilter.captcha(msg, user);
             if (b == true)
             {
                 return;
             }
         } catch (Exception E)
         {
             Console.WriteLine("F*****g seriously?\n{0}", E.ToString());
         }
     }
 }
Ejemplo n.º 4
0
        public static string Authorize(Request _request, out TGUser _user)
        {
            string username = _request.Headers["Username"].First();
            string password = _request.Headers["Password"].First();

            return(Authorize(username, password, out _user));
        }
Ejemplo n.º 5
0
 public User(TGUser _user)
 {
     Guid         = _user.Guid;
     Username     = _user.Username;
     FirstName    = _user.GivenName;
     LastName     = _user.FamilyName;
     EmailAddress = _user.EmailAddress;
 }
Ejemplo n.º 6
0
        public static bool LoginAndCreateSession(IServerDataManager _sdm, HttpContext _context)
        {
            if (_context != null)
            {
                //Check to see if we already have a session
                TGUser user = (TGUser)_context.Session["User"];
                if (user != null)
                {
                    return(true);
                }

                //Ok we don't have a session
                HttpRequest request = _context.Request;

                //First try the headers
                string tUserGuid = request.Headers["UserGuid"];
                if (GuidHelper.IsValidGuidString(tUserGuid))
                {
                    Guid   userGuid           = new Guid(tUserGuid);
                    string authorizationToken = request.Headers["AuthorizationToken"];

                    user = LoginFromAuthorization(_sdm, userGuid, authorizationToken);

                    //Did we get a user?
                    if (user != null)
                    {
                        //yup.  Store it in the server session
                        _context.Session["User"] = user;
                        return(true);
                    }
                }
                else
                {
                    string authorizationToken;
                    Guid   userGuid;

                    //No don't have headers, lets try for cookies
                    GetCookieValues(request, out userGuid, out authorizationToken);

                    if (!userGuid.Equals(Guid.Empty))
                    {
                        user = LoginFromAuthorization(_sdm, userGuid, authorizationToken);

                        //Did we get a user?
                        if (user != null)
                        {
                            //yup.  Store it in the server session
                            _context.Session["User"] = user;
                            return(true);
                        }
                    }
                }
            }

            //Didn't find header, cookie, or it was a bad login.
            return(false);
        }
        public static void doURLMediaFilter(TGMessage msg, TGUser usr)
        {
            var chat = msg.chat;                                                                      // grab chat.

            var enabled = XenforceRoot.getGroupConfigurationValue(chat, "kickurlunactivated", false); // Check configuration value.

            if (!enabled)                                                                             // return if not enabled.
            {
                return;
            }

            var qsc = "SELECT * FROM xen_activations WHERE activated=0 AND `group`={0} AND `forwho`={1}"; //

            var rqry = string.Format(qsc, chat.id, usr.id);

            SQLQueryInstance QueryInst;
            var  queryok = SQL.Query(rqry, out QueryInst);
            bool onerow  = false;

            if (QueryInst != null && QueryInst.reader.HasRows) // They've already been kicked before. If we return at least one row, then its valid to assume they havent activated
            {                                                  // There can only be one activation index per user per group.
                onerow = true;
            }

            if (QueryInst != null)
            {
                QueryInst.Finish();
            }

            if (!onerow)
            {
                return; // There was no activation
            }
            var wtf = msg.replySendMessage(usr.first_name + " was removed from the chat for sending URL/Media before activating!");

            XenforceRoot.AddCleanupMessage(msg.chat.id, wtf.message_id, 30);
            Telegram.kickChatMember(msg.chat, msg.from, 30);
            msg.delete();

            var statement =
                string.Format("INSERT INTO xenf_autokick (`group`,`user`,`when`,`why`) VALUES ({0},{1},{2},'{3}')",
                              msg.chat.id,
                              msg.from.id,
                              Helpers.getUnixTime(),
                              "URLMedia_Picture"
                              );
            int ra = 0;

            SQL.NonQuery(statement, out ra);
            if (ra < 1)
            {
                Console.WriteLine("Creating autorem incident failed failed. No SQL rows affected.");
                var cmsg = msg.replySendMessage("AutoremAddIncident() FAILED:\n\n Info:\n\n" + SQL.getLastError());
                XenforceRoot.AddCleanupMessage(chat.id, cmsg.message_id, 120);
            }
        }
Ejemplo n.º 8
0
        public static TGUser LoginFromAuthorization(IServerDataManager _sdm,
                                                    Guid _userGuid,
                                                    string _authorizationToken)
        {
            TGUser user = _sdm.GetUser(_userGuid);

            if (user != null)
            {
                if (user.Active)
                {
                    if (user.IsVerified)
                    {
                        TGUserAuthorization userAuthorization =
                            _sdm.GetUserAuthorization(_userGuid, _authorizationToken);

                        if (userAuthorization != null)
                        {
                            if (userAuthorization.ValidateAuthorizationToken(_authorizationToken))
                            {
                                _sdm.Persist(userAuthorization);

                                return(user);
                            }

                            //Passwords don't match or they were not supplied.
                            _sdm.LogWarning(_userGuid, "Passwords don't match or they were not supplied.");
                        }
                        else
                        {
                            _sdm.LogWarning(_userGuid, "User authorization not found.");
                        }
                    }
                    else
                    {
                        //User isn't verified
                        _sdm.LogWarning(_userGuid, "User isn't verified.");
                    }
                }
                else
                {
                    //User isn't active.
                    _sdm.LogWarning(_userGuid, "User isn't active.");
                }
            }
            else
            {
                //User not found
                _sdm.LogWarning(_userGuid, "User not found.");
            }

            return(null);
        }
Ejemplo n.º 9
0
        public bool ValidateUser(TGUser _user, string _testPassword)
        {
            TGUserPassword userPassword = GetTGUserPassword(_user.Guid);

            if (userPassword != null)
            {
                string testHash = TGUserPassword.HashPassword(userPassword.Salt, _testPassword);

                if (testHash.Equals(userPassword.HashedPassword))
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_username"></param>
        /// <param name="_authorizationToken"></param>
        /// <param name="_user"></param>
        /// <returns></returns>
        public bool ValidateUser(string _username, string _authorizationToken, out TGUser _user)
        {
            _user = GetUser(_username);

            if (_user != null)
            {
                TGUserAuthorization userAuthorization = GetUserAuthorization(_user.Guid, _authorizationToken);

                if (userAuthorization != null)
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 11
0
        private List <HydrantHeader> ProcessHydrants(IEnumerable <Hydrant> _hydrants, GeoPoint _center = null)
        {
            HydrantWikiManager        hwm   = new HydrantWikiManager();
            Dictionary <Guid, string> users = new Dictionary <Guid, string>();

            var output = new List <HydrantHeader>();

            foreach (var hydrant in _hydrants)
            {
                string username;
                Guid   userGuid = hydrant.OriginalTagUserGuid;

                if (users.ContainsKey(userGuid))
                {
                    username = users[userGuid];
                }
                else
                {
                    TGUser user = hwm.GetUser(userGuid);
                    users.Add(user.Guid, user.Username);
                    username = user.Username;
                }

                var outputHydrant = new HydrantHeader
                {
                    HydrantGuid  = hydrant.Guid,
                    Position     = new GeoLocation(hydrant.Position.Y, hydrant.Position.X, 0),
                    ThumbnailUrl = hydrant.ThumbnailUrl,
                    ImageUrl     = hydrant.ImageUrl,
                    Username     = username
                };

                if (_center == null)
                {
                    outputHydrant.DistanceInFeet = null;
                }
                else
                {
                    outputHydrant.DistanceInFeet = PositionHelper.GetDistance(_center, hydrant.Position).ToFeet();
                }

                output.Add(outputHydrant);
            }

            return(output);
        }
Ejemplo n.º 12
0
        public IUserIdentity GetUserFromIdentifier(Guid _identifier, NancyContext _context)
        {
            OpenFormGraphManager manager = new OpenFormGraphManager();

            TGUser user = manager.GetUser(_identifier);

            if (user != null &&
                user.IsVerified)
            {
                if (user.EulaAccepted || _context.Request.Path.Contains("signeula"))
                {
                    NancyUser nUser = new NancyUser {
                        UserName = user.Username
                    };
                    return(nUser);
                }
            }

            return(null);
        }
Ejemplo n.º 13
0
        public string HandleUserGet(DynamicDictionary _parameters)
        {
            OpenFormGraphManager manager = new OpenFormGraphManager();

            User jUser = AuthHelper.ValidateToken(manager, Request);

            if (jUser != null && jUser.IsUserAdmin)
            {
                string sGuid = _parameters["Guid"];
                Guid   userGuid;

                if (Guid.TryParse(sGuid, out userGuid))
                {
                    TGUser user       = manager.GetUser(userGuid);
                    User   jOtherUser = new User(user);

                    return(JsonConvert.SerializeObject(jOtherUser));
                }
            }

            return(null);
        }
Ejemplo n.º 14
0
        public static TGUser Login(IServerDataManager _sdm, Guid _userGuid, string _password)
        {
            TGUser user = _sdm.GetUser(_userGuid);

            if (user != null)
            {
                if (user.Active)
                {
                    if (user.IsVerified)
                    {
                        if (_sdm.ValidateUser(user, _password))
                        {
                            return(user);
                        }

                        //Passwords don't match or they were not supplied.
                        _sdm.LogWarning(_userGuid, "Passwords don't match or they were not supplied.");
                    }
                    else
                    {
                        //User isn't verified
                        _sdm.LogWarning(_userGuid, "User isn't verified.");
                    }
                }
                else
                {
                    //User isn't active.
                    _sdm.LogWarning(_userGuid, "User isn't active.");
                }
            }
            else
            {
                //User not found
                _sdm.LogWarning(_userGuid, "User not found.");
            }

            return(null);
        }
Ejemplo n.º 15
0
        public bool SendCannedEmail(TGUser _tgUser,
                                    string _cannedEmailName,
                                    NameValueCollection _additionParameters)
        {
            try
            {
                CannedEmail cannedEmail = GetCannedEmail(_cannedEmailName);

                if (cannedEmail != null)
                {
                    SystemEmail email = new SystemEmail(cannedEmail.Guid);

                    TGSerializedObject tgso = _tgUser.GetTGSerializedObject();
                    foreach (string key in _additionParameters.Keys)
                    {
                        string value = _additionParameters.Get(key);
                        tgso.Add(key, value);
                    }

                    CannedEmailHelper.PopulateEmail(cannedEmail, email, tgso);

                    SESHelper.SendMessage(email);
                    Persist(email);

                    return(true);
                }

                TraceFileHelper.Warning("Canned email not found");
            }
            catch (Exception ex)
            {
                TraceFileHelper.Exception(ex);
            }

            return(false);
        }
Ejemplo n.º 16
0
        public static bool autorem(TGMessage msg, TGUser usr)
        {
            var chat   = msg.chat;
            var enable = XenforceRoot.getGroupConfigurationValue(chat, "autoban", true);

            if (!enable)
            {
                return(false);
            }                              // Not enabled.
            var qsc  = "SELECT * FROM xenf_autokick WHERE `group`={0} AND `user`={1}";
            var rqry = string.Format(qsc, chat.id, usr.id);

            MySql.Data.MySqlClient.MySqlDataReader datar;
            SQLQueryInstance QueryInst;
            var queryok = SQL.Query(rqry, out QueryInst);

            if (QueryInst != null && QueryInst.reader.HasRows) // They've already been kicked before.
            {
                QueryInst.Finish();
                return(false);
            }
            if (QueryInst != null)
            {
                QueryInst.Finish();
            }

            var UserID         = usr.id;
            var GroupID        = msg.chat.id;
            var user_name_full = usr.first_name + " " + usr.last_name;
            var userscore      = 500;

            for (int i = 0; i < user_name_full.Length; i++)
            {
                var wtf = user_name_full[i];
                if (wtf > 0xAF)
                {
                    userscore += 5;
                }
                else if (wtf < 0x80)
                {
                    userscore -= 3;
                }
            }
            var picons = Telegram.getNumProfilePhotos(usr);

            userscore -= picons * 45;
            if (picons == 0)
            {
                userscore += 30;
            }
            if (userscore > 488)
            {
                Telegram.kickChatMember(chat, usr, 120);
                if (XenforceRoot.getGroupConfigurationValue(chat, "announcekicks", 1) > 0)
                {
                    msg.delete();
                    var msgr = msg.replySendMessage(user_name_full + " was automatically removed from the chat -- I think they're a bot.");
                    XenforceRoot.AddCleanupMessage(chat.id, msgr.message_id, 30);
                    var statement =
                        string.Format("INSERT INTO xenf_autokick (`group`,`user`,`when`,`why`) VALUES ({0},{1},{2},'{3}')",
                                      GroupID,
                                      UserID,
                                      Helpers.getUnixTime(),
                                      "Bot Score too high"
                                      );
                    int ra = 0;
                    SQL.NonQuery(statement, out ra);
                    if (ra < 1)
                    {
                        Console.WriteLine("Creating autorem incident failed failed. No SQL rows affected.");
                        var cmsg = msg.replySendMessage("AutoremAddIncident() FAILED:\n\n Info:\n\n" + SQL.getLastError());
                        XenforceRoot.AddCleanupMessage(chat.id, cmsg.message_id, 120);
                    }
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 17
0
        public AppModule()
        {
            Get["/"] = _parameters =>
            {
                return(View["index.sshtml"]);
            };

            Get["/dev/BuildDB"] = _parameters =>
            {
                bool devMode = Config.GetBooleanValue("DevMode", false);

                if (devMode)
                {
                    OpenFormGraphStructureManager structureManager = new OpenFormGraphStructureManager();
                    structureManager.BuildDB();

                    return(View["dev_dbbuildresult.sshtml"]);
                }

                return(null);
            };

            Get["/dev/BuildAdminUser"] = _parameters =>
            {
                bool devMode = Config.GetBooleanValue("DevMode", false);

                if (devMode)
                {
                    OpenFormGraphManager manager = new OpenFormGraphManager();

                    TGUser user = manager.GetUser("OFGAdmin");
                    if (user == null)
                    {
                        user = new TGUser {
                            Username = "******", GivenName = "Admin", FamilyName = "User"
                        };
                        manager.Persist(user);

                        string password = RandomString.GetRandomString(10);

                        TGUserPassword tgPassword = TGUserPassword.GetNew(user.Guid, user.Username, password);
                        manager.Persist(tgPassword);

                        TGUserRole userAdminRole = new TGUserRole
                        {
                            Active     = true,
                            Name       = UserRoles.UserAdmin,
                            ParentGuid = user.Guid
                        };
                        manager.Persist(userAdminRole);

                        TGUserRole dataAdminRole = new TGUserRole
                        {
                            Active     = true,
                            Name       = UserRoles.DataAdmin,
                            ParentGuid = user.Guid
                        };
                        manager.Persist(dataAdminRole);

                        JsonObjects.NewUser jNewUser = new NewUser(user, password);

                        return(View["dev_buildadminuserresult.sshtml", jNewUser]);
                    }
                }

                return(null);
            };
        }
Ejemplo n.º 18
0
 public NewUser(TGUser _user, string _password)
     : base(_user)
 {
     Password = _password;
 }
Ejemplo n.º 19
0
        public static bool namefilter(TGMessage msg, TGUser usr)
        {
            var chat   = msg.chat;
            var enable = XenforceRoot.getGroupConfigurationValue(chat, "autobannames", true);

            if (!enable)
            {
                return(false);
            }                              // Not enabled.
            var qsc  = "SELECT * FROM xenf_autokick WHERE `group`={0} AND `user`={1}";
            var rqry = string.Format(qsc, chat.id, usr.id);

            MySql.Data.MySqlClient.MySqlDataReader datar;
            SQLQueryInstance QueryInst;
            var queryok = SQL.Query(rqry, out QueryInst);

            if (QueryInst != null && QueryInst.reader.HasRows) // They've already been kicked before.
            {
                QueryInst.Finish();
                return(false);
            }
            if (QueryInst != null)
            {
                QueryInst.Finish();;
            }

            var UserID         = usr.id;
            var GroupID        = msg.chat.id;
            var user_name_full = usr.first_name + " " + usr.last_name;

            var userscore = 0;

            for (int i = 0; i < ShitNames.Length; i++)
            {
                var q = user_name_full.Contains(ShitNames[i]);
                if (q)
                {
                    userscore++;
                }
            }
            if (userscore > 0)
            {
                Telegram.kickChatMember(chat, usr, 120);
                if (XenforceRoot.getGroupConfigurationValue(chat, "announcekicks", 1) > 0)
                {
                    msg.delete();
                    var msgr = msg.replySendMessage(user_name_full + " removed -- name matches common bot.");
                    XenforceRoot.AddCleanupMessage(chat.id, msgr.message_id, 30);
                    var statement =
                        string.Format("INSERT INTO xenf_autokick (`group`,`user`,`when`,`why`) VALUES ({0},{1},{2},'{3}')",
                                      GroupID,
                                      UserID,
                                      Helpers.getUnixTime(),
                                      "Name is in blacklist"
                                      );
                    int ra = 0;
                    SQL.NonQuery(statement, out ra);
                    if (ra < 1)
                    {
                        Console.WriteLine("Creating autorem incident failed failed. No SQL rows affected.");
                        var cmsg = msg.replySendMessage("AutoremAddIncident() FAILED:\n\n Info:\n\n" + SQL.getLastError());
                        XenforceRoot.AddCleanupMessage(chat.id, cmsg.message_id, 120);
                    }
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_user"></param>
        public void Persist(TGUser _user)
        {
            TGUserDAO dao = new TGUserDAO(MongoDB);

            dao.Persist(_user);
        }
Ejemplo n.º 21
0
        private BaseResponse HandleGetTagsToReview(DynamicDictionary _parameters)
        {
            User user;

            if (AuthHelper.IsAuthorized(Request, out user))
            {
                if (user.UserType == UserTypes.SuperUser ||
                    user.UserType == UserTypes.Administrator)
                {
                    HydrantWikiManager hwm  = new HydrantWikiManager();
                    List <Tag>         tags = hwm.GetPendingTags();

                    List <TagToReview> tagsToReview = new List <TagToReview>();

                    foreach (var tag in tags)
                    {
                        TagToReview reviewTag = new TagToReview();
                        reviewTag.TagId     = tag.Guid;
                        reviewTag.ImageGuid = tag.ImageGuid;

                        TGUser tagUser = hwm.GetUser(tag.UserGuid);
                        if (tagUser != null)
                        {
                            reviewTag.Username = tagUser.Username;

                            UserStats stats = hwm.GetUserStats(tagUser.Guid);
                            reviewTag.UserTagsApproved = stats.ApprovedTagCount;
                            reviewTag.UserTagsRejected = stats.RejectedTagCount;
                        }

                        if (tag.ImageGuid != null)
                        {
                            reviewTag.ThumbnailUrl = tag.GetUrl(true);
                            reviewTag.ImageUrl     = tag.GetUrl(false);
                        }

                        if (tag.Position != null)
                        {
                            reviewTag.Position = new Position()
                            {
                                Latitude  = tag.Position.Y,
                                Longitude = tag.Position.X
                            };

                            List <Hydrant> nearby = hwm.GetHydrants(
                                reviewTag.Position.Latitude,
                                reviewTag.Position.Longitude,
                                200);

                            reviewTag.NearbyHydrants = ProcessHydrants(nearby, tag.Position);
                        }

                        tagsToReview.Add(reviewTag);
                    }

                    hwm.LogInfo(user.Guid, string.Format("Retrieved Tags to Review ({0})", tagsToReview.Count));

                    return(new TagsToReviewResponse()
                    {
                        Success = true,
                        Tags = tagsToReview
                    });
                }
                else
                {
                    return(new BaseResponse {
                        Error = "User not allowed to review tags",
                        Success = false
                    });
                }
            }
            else
            {
                LogUnauthorized(Request);
                return(new BaseResponse
                {
                    Error = "Not authenticated",
                    Success = false
                });
            }
        }
Ejemplo n.º 22
0
        public static bool captcha_CheckExpired()
        {
            MySql.Data.MySqlClient.MySqlDataReader cur;
            SQLQueryInstance QueryInst;

            var ss = SQL.Query("SELECT * FROM xen_activations WHERE activated=0 OR activation_checked=0", out QueryInst);

            if (!ss)
            {
                Console.WriteLine("Query for activation checks failed {0}", SQL.getLastError());
                if (QueryInst != null)
                {
                    QueryInst.Finish();
                }
                return(false);
            }
            Stack <CaptchaActivationIndex> captchaActivationIndices = new Stack <CaptchaActivationIndex>(1024); // hax?

            // totally hax, I have to pull group configuration to check and see if the group has specific features enabled.
            // But I can't do that if I already have an SQL cursor open. So i'll have to read all of the results of it

            cur = QueryInst.reader;
            // before I can make a call to get group configuration.

            var ib = 0;

            while (cur.Read())
            {
                ib++;
                // Console.WriteLine(ib);
                var b = new CaptchaActivationIndex
                {
                    index              = (long)cur["index"],
                    activation_id      = (string)cur["activation_id"],
                    activated          = (int)cur["activated"],
                    forwho             = (long)cur["forwho"],
                    group              = (long)cur["group"],
                    whencreated        = (long)cur["whencreated"],
                    activation_checked = (int)cur["activation_checked"],
                    username           = (string)cur["username"],
                    actmessage         = (long)cur["actmessage"]
                };

                captchaActivationIndices.Push(b);
            }
            QueryInst.Finish();  // close it up.

            for (int i = 0; i < captchaActivationIndices.Count; i++)
            {
                var CurrentActivation = captchaActivationIndices.Pop();
                var chat = new TGChat();
                var user = new TGUser();
                user.id = CurrentActivation.forwho;
                chat.id = CurrentActivation.group;
                var kicktime = XenforceRoot.getGroupConfigurationValue(chat, "kicktime", 30);
                var announce = XenforceRoot.getGroupConfigurationValue(chat, "announcekicks", 1);
                var unmute   = XenforceRoot.getGroupConfigurationValue(chat, "muteuntilverified", false);
                //Console.WriteLine("Wtf {0} {1}",CurrentActivation.activated,CurrentActivation.activation_checked);
                if (CurrentActivation.activated == 0)
                {
                    if (CurrentActivation.whencreated < Helpers.getUnixTime() - (kicktime * 60))
                    {
                        Telegram.deleteMessage(chat, CurrentActivation.actmessage);
                        Telegram.kickChatMember(chat, user, 0); // kick them from the chat.
                        Console.WriteLine("Remove user?");
                        var rar = 0;
                        var ok  = SQL.NonQuery(string.Format("DELETE FROM xen_activations WHERE activation_id='{0}'", CurrentActivation.activation_id), out rar);
                        if (announce > 0)
                        {
                            var mymessage = Telegram.sendMessage(chat, CurrentActivation.username + " was removed from the chat for not completing the CAPTCHA.");
                            if (mymessage != null)
                            {
                                XenforceRoot.AddCleanupMessage(chat.id, mymessage.message_id, 30); // Clean up after 30 seconds.
                            }
                        }
                    }
                }
                else if (CurrentActivation.activated == 1 && CurrentActivation.activation_checked == 0)
                {
                    Telegram.deleteMessage(chat, CurrentActivation.actmessage);

                    var Oldmsg  = CurrentActivation.username + ", thanks for verifying you're not a robot.";
                    var actiMsg = XenforceRoot.getGroupConfigurationValue(chat, "activationmessage", "%NAME, thanks for verifying you're not a robot.");
                    if (actiMsg == null || actiMsg.Length < 5)
                    {
                        actiMsg = Oldmsg;
                    }

                    actiMsg = actiMsg.Replace("%NAME", CurrentActivation.username);

                    var mymessage = Telegram.sendMessage(chat, actiMsg);
                    var ra        = 0;
                    var ok        = SQL.NonQuery("UPDATE xen_activations SET activation_checked=1 WHERE activation_id='" + SQL.escape(CurrentActivation.activation_id) + "'", out ra);
                    if (!ok)
                    {
                        Console.WriteLine("Updating activation message failed! Might spam!!!?");
                    }
                    if (mymessage != null)
                    {
                        XenforceRoot.AddCleanupMessage(chat.id, mymessage.message_id, 30); // Clean up after 30 seconds.
                    }

                    if (unmute)
                    {
                        Telegram.restrictChatMember(chat, user, 0, true, true, true, true);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 23
0
 public void SendUserValidationEmail(TGUser _tgUser, TGUserEmailValidation _tgUserEmailValidation)
 {
 }
Ejemplo n.º 24
0
        public string HandleUserAddPost(DynamicDictionary _parameters)
        {
            OpenFormGraphManager manager = new OpenFormGraphManager();
            BaseResult           result  = new BaseResult();

            User jUser = AuthHelper.ValidateToken(manager, Request);

            if (jUser != null && jUser.IsUserAdmin)
            {
                string  json     = ReadBody();
                NewUser jNewUser = JsonConvert.DeserializeObject <NewUser>(json);

                if (jNewUser != null)
                {
                    jNewUser.Guid = Guid.NewGuid();

                    TGUser testUser = manager.GetUser(jNewUser.Username);
                    if (testUser == null)
                    {
                        TGUser newUser = new TGUser
                        {
                            FamilyName   = jNewUser.LastName,
                            GivenName    = jNewUser.FirstName,
                            EmailAddress = jNewUser.EmailAddress,
                            IsVerified   = true,
                            DisplayName  = jNewUser.Username,
                            Username     = jNewUser.Username
                        };
                        manager.Persist(newUser);

                        TGUserPassword userPassword = TGUserPassword.GetNew(newUser.Guid, newUser.Username,
                                                                            jNewUser.Password);
                        manager.Persist(userPassword);

                        //Add Admin Roles as required
                        if (jNewUser.IsUserAdmin)
                        {
                            TGUserRole userAdminRole = new TGUserRole
                            {
                                Active     = true,
                                ParentGuid = newUser.Guid,
                                Name       = UserRoles.UserAdmin
                            };
                            manager.Persist(userAdminRole);
                        }

                        if (jNewUser.IsDataAdmin)
                        {
                            TGUserRole dataAdminRole = new TGUserRole
                            {
                                Active     = true,
                                ParentGuid = newUser.Guid,
                                Name       = UserRoles.DataAdmin
                            };
                            manager.Persist(dataAdminRole);
                        }

                        result.Result = "Success";
                    }
                    else
                    {
                        result.Result = "UsernameNotAvailable";
                    }
                }
            }

            return(JsonConvert.SerializeObject(result));
        }
Ejemplo n.º 25
0
        public static string Authorize(string _username, string _password, out TGUser _user)
        {
            LoginResult          result  = new LoginResult();
            OpenFormGraphManager manager = new OpenFormGraphManager();

            _user = manager.GetUser(_username);

            if (_user != null)
            {
                if (_user.IsVerified)
                {
                    if (_user.Active)
                    {
                        if (manager.ValidateUser(_user, _password))
                        {
                            TGUserAuthorization authorization =
                                TGUserAuthorization.GetNew(_user.Guid, "unknown");
                            manager.Persist(authorization);

                            result.Result      = "Success";
                            result.AuthToken   = authorization.AuthorizationToken;
                            result.DisplayName = _user.DisplayName;
                            result.Username    = _user.Username;
                        }

                        TGEula eula = manager.GetLatestEula();
                        if (eula != null)
                        {
                            TGEulaAgreement agreement = manager.GetEulaAgreement(_user.Guid, eula.Guid);

                            if (agreement == null)
                            {
                                result.NeedsEula = "True";
                                result.EulaGuid  = eula.Guid.ToString();
                                result.EulaText  = eula.Text;

                                _user.EulaAccepted = false;
                                manager.Persist(_user);
                            }
                            else
                            {
                                result.NeedsEula = "False";
                            }
                        }
                        else
                        {
                            //Bad password or username
                            manager.LogWarning(Guid.Empty, "User not found");
                            _user = null;

                            result.Result = "BadUserOrPassword";
                        }
                    }
                    else
                    {
                        //user not active
                        //Todo - Log Something
                        manager.LogWarning(_user.Guid, "User Not Active");
                        _user = null;

                        result.Result = "NotActive";
                    }
                }
                else
                {
                    //User not verified
                    //Todo - Log Something
                    manager.LogWarning(_user.Guid, "User not verified");
                    _user = null;

                    result.Result = "NotVerified";
                }
            }
            else
            {
                //User not found
                manager.LogWarning(Guid.Empty, "User not found");

                result.Result = "BadUserOrPassword";
            }

            return(JsonConvert.SerializeObject(result));
        }
Ejemplo n.º 26
0
        public static async Task <bool> Execute(TGMessage message, TGUser ncm, GroupConfigurationObject gco, string langcode)
        {
            var query = "SELECT * FROM xenf_activations WHERE `group`={0} AND `forwho`={1}";

            return(false);
        }
Ejemplo n.º 27
0
        public static LoginResult Authorize(OpenFormGraphManager _manager,
                                            string _username, string _password, out TGUser _user)
        {
            LoginResult result = new LoginResult();

            _user = _manager.GetUser(_username);

            if (_user != null)
            {
                if (_user.Active)
                {
                    if (_manager.ValidateUser(_user, _password))
                    {
                        string token = _manager.GetAuthorizationToken(_user.Guid, _password);

                        result.Result    = "Success";
                        result.AuthToken = token;
                        result.Username  = _username;

                        if (_manager.HasUserRole(_user.Guid, UserRoles.UserAdmin))
                        {
                            result.IsUserAdmin = true;
                        }
                        else
                        {
                            result.IsUserAdmin = false;
                        }

                        if (_manager.HasUserRole(_user.Guid, UserRoles.DataAdmin))
                        {
                            result.IsDataAdmin = true;
                        }
                        else
                        {
                            result.IsDataAdmin = false;
                        }
                    }
                    else
                    {
                        //Bad password or username
                        TraceFileHelper.Warning("User not found");
                        _user = null;

                        result.Result = "BadUserOrPassword";
                    }
                }
                else
                {
                    //user not active
                    //Todo - Log Something
                    TraceFileHelper.Warning("User Not Active");
                    _user = null;

                    result.Result = "NotActive";
                }
            }
            else
            {
                //User not found
                TraceFileHelper.Warning("User not found");
                result.Result = "BadUserOrPassword";
            }

            return(result);
        }
Ejemplo n.º 28
0
 public string getRspTGUser()
 {
     return(TGUser.Replace("null", ""));
 }
Ejemplo n.º 29
0
        public static bool captcha(TGMessage msg, TGUser usr)
        {
            var UserID         = usr.id;
            var GroupID        = msg.chat.id;
            var ActivationID   = Helpers.Base64Encode(UserID.ToString() + GroupID.ToString());
            var q              = usr.username;
            var user_name_full = usr.first_name + " " + usr.last_name;
            var ko             = 0;

            var ok = SQL.NonQuery(string.Format("DELETE FROM xen_activations WHERE activation_id='{0}'", ActivationID), out ko); // Remove the current activation ID.


            if (q != null)
            {
                user_name_full = "@" + q; // okay okay fine jeez.
            }


            var muteUntilVerified = XenforceRoot.getGroupConfigurationValue(msg.chat, "muteuntilverified", false);
            var kicktime          = XenforceRoot.getGroupConfigurationValue(msg.chat, "kicktime", 30);
            var instance_time     = Helpers.getUnixTime();

            var FullMessageOld = string.Format(
                "Welcome, %NAME. \n" +
                "Please complete a quick captcha within %DURATION minutes to verify you're not a bot: \n\n" +
                "%ACTURL"
                );

            var FullMessage = XenforceRoot.getGroupConfigurationValue(msg.chat, "message", FullMessageOld);


            if (FullMessage == null || FullMessage.Length < 10)
            {
                FullMessage = FullMessageOld;
            }

            FullMessage = FullMessage.Replace("%ACTURL", "http://www.xayr.ga/xenf2/?actid=" + ActivationID);
            FullMessage = FullMessage.Replace("%DURATION", kicktime.ToString());
            FullMessage = FullMessage.Replace("%NAME", user_name_full);

            if (muteUntilVerified == true)
            {
                Telegram.restrictChatMember(msg.chat, usr, 0, false, false, false, false); // Restrict until they verify.
                FullMessage += "\n\nYou will not be able to send any messages until you've verified.";
            }

            var message = msg.replySendMessage(FullMessage);

            // INSERT INTO xen_activations (activation_id,group,forwho,whencreated,actmessage,username) VALUES ('{0}',{1},{2},{3},{4},'{5}');

            if (message == null || GroupID == null || instance_time == null || user_name_full == null || ActivationID == null)
            {
                try
                {
                    Console.WriteLine("MESSAGE IS NULL OR SOMETHING");
                    Console.WriteLine("PROBLEM: {0} {1}", message, user_name_full);
                }
                catch { }
            }
            else

            {
                var statement =
                    string.Format("INSERT INTO xen_activations (`activation_id`,`group`,`forwho`,`whencreated`,`actmessage`,`username`) VALUES ('{0}',{1},{2},{3},{4},'{5}')",
                                  SQL.escape(ActivationID),
                                  GroupID,
                                  UserID,
                                  instance_time,
                                  message.message_id,
                                  SQL.escape(user_name_full)
                                  );
                int ra = 0;
                SQL.NonQuery(statement, out ra);
                if (ra < 1)
                {
                    Console.WriteLine("Creating activation ID failed. No SQL rows affected.");
                    var cmsg = msg.replySendMessage("CreateActivationID() FAILED:\n\n Info:\n\n" + SQL.getLastError());
                    if (cmsg != null)
                    {
                        XenforceRoot.AddCleanupMessage(message.chat.id, cmsg.message_id, 120);
                    }
                }

                return(false);
            }
            return(false);
        }