Exemplo n.º 1
0
        public static void BuildPassword(MSSQLDB db, SqlTransaction trans, Int64 context, Int64 entityId, Int64 enterpriseId)
        {
            String pwdMethod = "random";
            String pwdValue  = "";

            using (DataTable dtRules = db.Select("select password_rule from context c where c.id = " + context + " and (c.password_rule is not null and rtrim(LTRIM(c.password_rule)) <> '')", trans))
            {
                if ((dtRules != null) && (dtRules.Rows.Count > 0))
                {
                    String v = dtRules.Rows[0]["password_rule"].ToString().Trim();

                    if (v.IndexOf("[") != -1)
                    {
                        Regex rex = new Regex(@"(.*?)\[(.*?)\]");
                        Match m   = rex.Match(v);
                        if (m.Success)
                        {
                            pwdMethod = m.Groups[1].Value.ToLower();
                            pwdValue  = m.Groups[2].Value;
                        }
                    }
                    else
                    {
                        pwdMethod = v;
                    }
                }
            }

            switch (pwdMethod)
            {
            case "default":
                //Nada a senha ja foi definida
                break;

            case "field":
                throw new NotImplementedException();

                /*
                 * Int64 fieldId = 0;
                 * Int64.TryParse(pwdValue, out fieldId);
                 * using (DataTable dtFields = db.Select("select * from identity_field where identity_id = " + this.IdentityId + " and field_id = " + fieldId, trans))
                 *  if ((dtFields != null) && (dtFields.Rows.Count > 0))
                 *  {
                 *      pwdValue = dtFields.Rows[0]["value"].ToString();
                 *  }*/
                break;

            default:     //Random
                pwdValue = "";
                break;
            }

            //Se a senha continua vazia, gera uma randômica
            if ((pwdValue == null) || (pwdValue == ""))
            {
                pwdValue = RandomPassword.Generate(14, 16);
            }

            Boolean MustChangePassword = true;

            String pwd = "";

            using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.conn, enterpriseId, trans))

                using (CryptApi cApi = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(pwdValue)))
                    pwd = Convert.ToBase64String(cApi.ToBytes());


            String sql = "update entity set password = @password, change_password = getdate(), must_change_password = @must where id = @entityId";

            SqlParameterCollection par = GetSqlParameterObject();

            par.Add("@entityId", SqlDbType.BigInt).Value = entityId;

            par.Add("@password", SqlDbType.VarChar, pwd.Length).Value = pwd;
            par.Add("@must", SqlDbType.Bit).Value = MustChangePassword;

            db.AddUserLog(LogKey.User_PasswordChanged, null, "Engine", UserLogLevel.Info, 0, 0, context, 0, 0, entityId, 0, "Password changed", "", trans);

            db.ExecuteNonQuery(sql, CommandType.Text, par, trans);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            ServerLocalConfig localConfig = new ServerLocalConfig();

            localConfig.LoadConfig();

            if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null);
            }


            /*************
             * Gera os certificados do servidor
             */
            MSSQLDB db = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);

            db.openDB();
            db.Timeout = 300;


            Int64 entityId = 0;

            if (args.Length > 0)
            {
                Int64.TryParse(args[0], out entityId);
            }

            DataTable tmp = db.Select(String.Format("select e.*, e1.id enterprise_id from entity e inner join context c on c.id = e.context_id inner join enterprise e1 on e1.id = c.enterprise_id where e.id = {0}", entityId));

            if (tmp == null)
            {
                StopOnError("Select is null", null);
            }

            if (tmp.Rows.Count == 0)
            {
                StopOnError("Select is empty", null);
            }

            EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.conn, (Int64)tmp.Rows[0]["entity_id"]);

            Int64 context      = (Int64)tmp.Rows[0]["context_id"];
            Int64 enterpriseId = (Int64)tmp.Rows[0]["enterprise_id"];

            Console.WriteLine("##############################");
            Console.WriteLine("C Pwd: " + tmp.Rows[0]["password"].ToString());

            Console.WriteLine("");
            Console.WriteLine("##############################");
            using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(tmp.Rows[0]["password"].ToString())))
                Console.WriteLine("Pwd: " + Encoding.UTF8.GetString(cApi.clearData));


            String text = "";

            do
            {
                //Console.Clear();
                Console.Write("Deseja redefinir a senha do usuário? (Y/N): ");
                text = Console.ReadLine().Trim();
                if (text.ToLower() == "y")
                {
                    break;
                }
                else if (text.ToLower() == "n")
                {
                    text = "";
                    break;
                }
                else
                {
                    text = "";
                }
            } while (text == "");

            if (text.ToLower() == "y")
            {
                BuildPassword(db, null, context, entityId, enterpriseId);
            }

            db.closeDB();

            StopOnError("", null);
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            localConfig = new ServerLocalConfig();
            localConfig.LoadConfig();

            if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null);
            }

            Int32 cnt      = 0;
            Int32 stepWait = 15000;

            while (cnt <= 10)
            {
                try
                {
                    MSSQLDB db = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                    db.openDB();

                    db.closeDB();

                    break;
                }
                catch (Exception ex)
                {
                    if (cnt < 10)
                    {
                        TextLog.Log("Engine", "Falha ao acessar o banco de dados: " + ex.Message);
                        Thread.Sleep(stepWait);
                        stepWait = stepWait * 2;
                        cnt++;
                    }
                    else
                    {
                        StopOnError("Falha ao acessar o banco de dados", ex);
                    }
                }
            }


            /*************
             * Gera os certificados do servidor
             * Verifica se o certificade está próximo de vencer
             */
            MSSQLDB db2 = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);

            db2.openDB();


            DataTable created = db2.Select("select * from vw_entity_mails where create_date between CONVERT(datetime, convert(varchar(10),DATEADD(DAY, -1, GETDATE()),120) + ' 00:00:00', 120) and CONVERT(datetime, convert(varchar(10),getdate(),120) + ' 23:59:59', 120) order by context_name, full_name");
            DataTable all     = db2.Select("select * from vw_entity_mails order by context_name, full_name");
            Dictionary <String, String> title = new Dictionary <string, string>();

            title.Add("context_name", "Contexto");
            title.Add("full_name", "Nome completo");
            title.Add("login", "Login");
            title.Add("create_date", "Data de criação");
            title.Add("last_login", "Ultimo login");
            title.Add("mail", "E-mail");
            title.Add("locked", "Bloqueado");

            ReportBase rep1 = new ReportBase(created, title);
            ReportBase rep2 = new ReportBase(all, title);

            List <Attachment> atts = new List <Attachment>();

            using (MemoryStream ms1 = new MemoryStream(Encoding.UTF8.GetBytes(rep1.GetTXT())))
                using (MemoryStream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(rep1.GetXML("Usuários", ""))))
                    using (MemoryStream ms3 = new MemoryStream(Encoding.UTF8.GetBytes(rep2.GetTXT())))
                        using (MemoryStream ms4 = new MemoryStream(Encoding.UTF8.GetBytes(rep2.GetXML("Usuários", ""))))
                        {
                            atts.Add(new Attachment(ms1, "created.txt"));
                            atts.Add(new Attachment(ms2, "created.xls"));
                            atts.Add(new Attachment(ms3, "all.txt"));
                            atts.Add(new Attachment(ms4, "all.xls"));

                            List <String> to = new List <string>();
                            to.Add("*****@*****.**");
                            to.Add("*****@*****.**");
                            to.Add("*****@*****.**");

                            sendEmail(db2, "Listagem de usuários em " + DateTime.Now.ToString("dd/MM/yyyy"), to, created.Rows.Count + " usuários criados de " + DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy") + " até " + DateTime.Now.ToString("dd/MM/yyyy"), false, atts);
                        }
            db2.closeDB();
        }