Beispiel #1
0
        public MessageSender(DbBase database, Int64 messageId)
            : base()
        {
            this.messageId = messageId;
            this.database  = database;

            //Busca no banco a mensage

            DataTable dtMessage = database.ExecuteDataTable("select * from st_messages where id = " + messageId);

            if ((dtMessage == null) || (dtMessage.Rows.Count == 0))
            {
                throw new Exception("Message not found");
            }

            this.enterpriseId = (Int64)dtMessage.Rows[0]["enterprise_id"];
            this.isHtml       = (Boolean)dtMessage.Rows[0]["html"];
            this.mailSubject  = dtMessage.Rows[0]["subject"].ToString();
            this.mailBody     = dtMessage.Rows[0]["body"].ToString();
            this.messageKey   = dtMessage.Rows[0]["key"].ToString();

            this.mailTo = new List <MailAddress>();
            try
            {
                foreach (String m in dtMessage.Rows[0]["to"].ToString().Split(",".ToCharArray()))
                {
                    mailTo.Add(new MailAddress(m));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Erro parsing recipient", ex);
            }
        }
Beispiel #2
0
        static public CASTicketResult GetToken(DbBase database, Uri service, String grantTicket, String username)
        {
            CASTicketResult ret = null;

            if (service != null)
            {
                DataTable dtTickets = database.ExecuteDataTable(String.Format("select * from [CAS_Ticket] where [Service_Uri] = '{0}' and (Grant_Ticket = '{1}' or User_Name = '{2}')", CASPluginService.Normalize(service).AbsoluteUri, grantTicket, username));
                if ((dtTickets != null) && (dtTickets.Rows.Count > 0))
                {
                    ret                     = new CASTicketResult();
                    ret.Success             = true;
                    ret.Service             = CASPluginService.Normalize(dtTickets.Rows[0]["Service_Uri"].ToString());
                    ret.UserId              = dtTickets.Rows[0]["User_Id"].ToString();
                    ret.UserName            = dtTickets.Rows[0]["User_Name"].ToString();
                    ret.GrantTicket         = dtTickets.Rows[0]["Grant_Ticket"].ToString();
                    ret.LongTicket          = dtTickets.Rows[0]["Long_Ticket"].ToString();
                    ret.ProxyTicket         = dtTickets.Rows[0]["Proxy_Ticket"].ToString();
                    ret.CreateDate          = (DateTime)dtTickets.Rows[0]["Create_Date"];
                    ret.Expires             = (DateTime)dtTickets.Rows[0]["Expires"];
                    ret.CreateByCredentials = (Boolean)dtTickets.Rows[0]["Create_By_Credentials"];
                }
            }

            if (ret == null)
            {
                ret = new CASTicketResult();
            }

            if (ret.Success)
            {
                if (service == null)
                {
                    ret.Success = false;
                    return(ret);
                }

                //Verifica se o ticket pode ser validado no serviço atual
                if ((ret.Service == null) || (!ret.Service.Equals(service)))
                {
                    if (database.ExecuteScalar <Int64>(String.Format("select COUNT(*) from [CAS_Service] where Uri = '{0}' and Context_Name = (select Context_Name from [CAS_Service] where Uri = '{1}')", CASPluginService.Normalize(service).AbsoluteUri, ret.Service.AbsoluteUri)) > 0)
                    {
                        ret.CreateByCredentials = false; //Define que as informações foram copiadas de outro token e não a partir de uma autenticação usuário/senha
                    }
                    else
                    {
                        ret.Success = false;
                    }
                }

                //Define o serviço atual
                ret.Service = service;

                //Salva o token copiado
                //ret.SaveToFile(basePath);
                ret.SaveToDb(database);
            }

            return(ret);
        }
Beispiel #3
0
        public static MessageBuilder BuildFromTemplate(DbBase database, Int64 enterpriseId, String templateKey, String recipients, Dictionary <String, String> variable, Object transaction)
        {
            using (DbParameterCollection par = new DbParameterCollection())
            {
                par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId;
                par.Add("@message_key", typeof(String)).Value  = templateKey;

                DataTable dtTemplate = database.ExecuteDataTable("sp_st_get_message_template", CommandType.StoredProcedure, par, transaction);
                if ((dtTemplate == null) || (dtTemplate.Rows.Count == 0))
                {
                    throw new Exception("Message template not found");
                }

                return(new MessageBuilder(enterpriseId, (Boolean)dtTemplate.Rows[0]["html"], dtTemplate.Rows[0]["subject"].ToString(), dtTemplate.Rows[0]["body"].ToString(), recipients, new Uri(dtTemplate.Rows[0]["last_uri"].ToString()), variable));
                //database.ExecuteNonQuery("UPDATE st_messages SET [status] = 'E' WHERE id = @message_id; INSERT INTO st_messages_status (message_id,date,error,status,description) VALUES(@message_id,getdate(),1,@status,@description);", par);
            }
        }
Beispiel #4
0
        public override AccessControl ValidateCtrl(DbBase database, String method, String auth, Dictionary <String, Object> parameters, ExternalAccessControl extCtrl)
        {
            Boolean ret      = false;
            Int64   entityId = 0;

            if (String.IsNullOrWhiteSpace(auth))
            {
                ret = false;
            }
            else
            {
                DataTable tmp = database.ExecuteDataTable(String.Format("select e.id entity_id, ea.*, e.locked from entity_auth ea inner join entity e with(nolock) on ea.entity_id = e.id where e.deleted = 0 and ea.auth_key = '{0}' and end_date > getdate()", auth), CommandType.Text, null);
                if ((tmp == null) || (tmp.Rows.Count == 0))
                {
                    ret = false;
                }
                else if ((Boolean)tmp.Rows[0]["locked"])
                {
                    ret      = false;
                    entityId = (Int64)tmp.Rows[0]["entity_id"];
                }
                else
                {
                    //Existe a chave e está válida
                    //Deve ser implementado aqui o RBAC
                    ret      = true;
                    entityId = (Int64)tmp.Rows[0]["entity_id"];
                }

                tmp.Dispose();
            }

            if (extCtrl != null)
            {
                //Transfere a responsabilidade da autenticação para a chamada externa
                //Passa como parametro a decisão que foi tomada até agora
                this.Acl = extCtrl(method, auth, new AccessControl(entityId, ret), parameters);
            }
            else
            {
                this.Acl = new AccessControl(entityId, ret);
            }

            return(this.Acl);
        }
Beispiel #5
0
 public override DataTable ExecuteDataTable(String command, CommandType commandType, DbParameterCollection parameters, Object transaction)
 {
     return(baseDB.ExecuteDataTable(command, commandType, parameters, transaction));
 }
Beispiel #6
0
        public void SaveToDb(DbBase database, Object transaction)
        {
            //Salva no banco, resgata o message key e depois atualiza o body no db

            Dictionary <String, String> vars = new Dictionary <String, String>();

            try
            {
                MatchCollection ms = Regex.Matches(this.mailBody, @"%(.*?)%", RegexOptions.IgnoreCase);
                foreach (Match m in ms)
                {
                    if (!vars.ContainsKey(m.Groups[1].Value.ToLower()))
                    {
                        vars.Add(m.Groups[1].Value.ToLower(), "");
                    }
                }

                ms = Regex.Matches(this.mailSubject, @"%(.*?)%", RegexOptions.IgnoreCase);
                foreach (Match m in ms)
                {
                    if (!vars.ContainsKey(m.Groups[1].Value.ToLower()))
                    {
                        vars.Add(m.Groups[1].Value.ToLower(), "");
                    }
                }

                if (this.variables != null)
                {
                    List <String> ks = new List <string>();
                    ks.AddRange(vars.Keys);

                    foreach (String k in ks)
                    {
                        foreach (String k1 in this.variables.Keys)
                        {
                            if (k1.ToLower() == k)
                            {
                                vars[k] = this.variables[k1];
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Erro on build enviroment variables", ex);
            }

            foreach (MailAddress mail in this.mailTo)
            {
                String newBody    = this.mailBody;
                String newSubject = this.mailSubject;
                try
                {
                    try
                    {
                        //Imagem para marcação de leitura da mensagem
                        if (this.isHtml) //A tag |message_key| será substituida automaticamente na procedure pela key da mensagem
                        {
                            newBody += "<img src=\"%enterprise_uri%/m/v/|message_key|\" width=\"1\" heigh=\"1\" />";
                        }

                        if (!vars.ContainsKey("enterprise_uri"))
                        {
                            vars.Add("enterprise_uri", "");
                        }

                        vars["enterprise_uri"] = this.serverUri.Scheme + "://" + serverUri.Host + (serverUri.IsDefaultPort ? "" : ":" + serverUri.Port);

                        if (vars.ContainsKey("mail"))
                        {
                            vars["mail"] = mail.Address;
                        }

                        foreach (String k in vars.Keys)
                        {
                            newBody    = Regex.Replace(newBody, "%" + k + "%", vars[k], RegexOptions.IgnoreCase);
                            newSubject = Regex.Replace(newSubject, "%" + k + "%", vars[k], RegexOptions.IgnoreCase);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Erro on build enviroment variables", ex);
                    }


                    using (DbParameterCollection par = new DbParameterCollection())
                    {
                        par.Add("@enterprise_id", typeof(Int64)).Value = this.enterpriseId;
                        par.Add("@send_to", typeof(String)).Value      = mail.Address;
                        par.Add("@is_html", typeof(Boolean)).Value     = this.isHtml;
                        par.Add("@subject", typeof(String)).Value      = newSubject;
                        par.Add("@body", typeof(String)).Value         = newBody;

                        DataTable dtMessage = database.ExecuteDataTable("sp_st_new_message", CommandType.StoredProcedure, par, transaction);
                        if ((dtMessage != null) && (dtMessage.Rows.Count > 0))
                        {
                            try
                            {
                                newBody = dtMessage.Rows[0]["body"].ToString();//Pega o body atualizado pois há tags nele que a procedure atualiza

                                HtmlDocument doc = new HtmlDocument();
                                doc.LoadHtml(newBody);


                                Boolean renew = false;
                                //Substitui os links

                                HtmlNodeCollection aLinks = doc.DocumentNode.SelectNodes("//a[@href]");
                                if (aLinks != null)
                                {
                                    foreach (HtmlNode link in aLinks)
                                    {
                                        HtmlAttribute att = link.Attributes["href"];
                                        using (DbParameterCollection par2 = new DbParameterCollection())
                                        {
                                            par2.Add("@message_id", typeof(Int64)).Value = dtMessage.Rows[0]["id"];
                                            par2.Add("@link", typeof(String)).Value      = att.Value;

                                            String linkKey = database.ExecuteScalar <String>("sp_st_new_message_link", CommandType.StoredProcedure, par2, transaction);

                                            newBody = newBody.Replace(att.Value, this.serverUri.Scheme + "://" + serverUri.Host + (serverUri.IsDefaultPort ? "" : ":" + serverUri.Port) + "/m/l/" + linkKey);
                                            renew   = true;
                                            //
                                        }
                                    }
                                }


                                //Se houver links atualiza o body
                                if (renew)
                                {
                                    using (DbParameterCollection par2 = new DbParameterCollection())
                                    {
                                        par2.Add("@message_id", typeof(Int64)).Value = dtMessage.Rows[0]["id"];
                                        par2.Add("@body", typeof(String)).Value      = newBody;

                                        database.ExecuteNonQuery("update [st_messages] set body = @body where id = @message_id", CommandType.Text, par2, transaction);
                                    }
                                }
                            }
                            catch { }
                        }

                        //database.ExecuteNonQuery("UPDATE st_messages SET [status] = 'E' WHERE id = @message_id; INSERT INTO st_messages_status (message_id,date,error,status,description) VALUES(@message_id,getdate(),1,@status,@description);", par);
                    }
                }
                finally
                {
                    newBody    = null;
                    newSubject = null;
                }
            }
        }