⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 util.cs

📁 Bug管理系统
💻 CS
📖 第 1 页 / 共 3 页
字号:
/* 
Copyright 2002 Corey Trager 
Distributed under the terms of the GNU General Public License
*/

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace btnet
{


	public class Security {
	
		public const int MUST_BE_ADMIN = 1;
		public const int ANY_USER_OK = 2;
		public const int ANY_USER_OK_EXCEPT_GUEST = 3;
		
		public int this_usid = 0;
		public string this_username = "";
		public string this_fullname = "";
		public bool this_is_admin = false;
		public bool this_is_guest = false;
		public bool this_adds_not_allowed = false;
		public string auth_method = "";

		private const int PERMISSION_NONE = 0;
		private const int PERMISSION_READONLY = 1;
		private const int PERMISSION_REPORTER = 3;
		private const int PERMISSION_ALL = 2;
		
		///////////////////////////////////////////////////////////////////////
		public void check_security(DbUtil dbutil, HttpRequest Request, HttpResponse Response, int level)
		{

			Util.write_to_log ("url=" + Request.Url.PathAndQuery);

			HttpCookie cookie = Request.Cookies["se_id"];
						
			// This logic allows somebody to put a link in an email, like
			// edit_bug.aspx?id=66
			// The user would click on the link, go to the logon page (default.aspx),
			// and then after logging in continue on to edit_bug.aspx?id=66
			string original_url = Request.ServerVariables["URL"].ToString().ToLower();
			string original_querystring = Request.ServerVariables["QUERY_STRING"].ToString().ToLower();
			string target = "default.aspx?url=" + original_url + "&qs=" + HttpUtility.UrlEncode(original_querystring);
			
			if (cookie == null)
			{
				Response.Redirect(target);
			}

			Util.write_to_log ("session=" + cookie.Value);

			// guard against "Sql Injection" exploit
			string se_id = cookie.Value.Replace("'", "''");

			// check for existing session for active user
			string sql = @"select us_id, us_admin, us_username, us_firstname, us_lastname,
				isnull(us_forced_project, 0 ) us_forced_project,
				isnull(pu_permission_level, $dpl) pu_permission_level			
				from sessions 
				inner join users on se_user = us_id
				left outer join project_user_xref
					on pu_project = us_forced_project
					and pu_user = us_id
				where se_id = '$se'
				and us_active = 1";
				

			sql = sql.Replace("$se", se_id);
			sql = sql.Replace("$dpl", Util.get_setting("DefaultPermissionLevel","2"));
			
			DataRow dr = dbutil.get_datarow(sql);
			
			// no previously established session
			if (dr == null)
			{
				Response.Redirect(target);
			}
			
			this_usid = Convert.ToInt32(dr["us_id"]);
			this_username = (string) dr["us_username"];
			this_fullname = (string) dr["us_lastname"] + ", " + (string) dr["us_firstname"];
			
			Util.write_to_log ("userid=" + Convert.ToString(this_usid));
			Util.write_to_log ("username=" + this_username);
			
			if ((int)dr["us_admin"] == 1)
			{
				this_is_admin = true;
			}
			else
			{
				this_is_admin = false;
				if (this_username.ToLower() == "guest")
				{
					this_is_guest = true;
				}				
				else
				{
					this_is_guest = false;
				}
			}
			
			
			// if user is forced to a specific project, and doesn't have 
			// at least reporter permission on that project, than user
			// can't add bugs
			if ((int)dr["us_forced_project"] != 0)
			{
				if ((int)dr["pu_permission_level"] == PERMISSION_READONLY
				||  (int)dr["pu_permission_level"] == PERMISSION_NONE)
				{
					this_adds_not_allowed = true;
				}
			}
			

			if (level == MUST_BE_ADMIN && !this_is_admin)
			{
				Response.Redirect("default.aspx");
			}
			else if (level == ANY_USER_OK_EXCEPT_GUEST && this_is_guest)
			{
				Response.Redirect("default.aspx");
			}


			cookie = Request.Cookies["user"];
			if (cookie != null)
			{
				string NTLM = cookie["NTLM"];
				if (NTLM != null && NTLM == "1")
				{
					auth_method = "windows";
				}
				else
				{
					auth_method = "plain";
				}
			}
			else
			{
				auth_method = "plain";			
			}
			


		}

		///////////////////////////////////////////////////////////////////////
		public static void write_menu_item(HttpResponse Response, 
			string this_link, string menu_item, string href)
		{
			Response.Write ("<td valign=middle align=left>");
			if (this_link == menu_item)
			{
				Response.Write ("<a href=" + href + "><span class=selected_menu_item>" + menu_item + "</span></a>");	}
			else
			{
				Response.Write ("<a href=" + href + "><span class=menu_item>" + menu_item + "</span></a>");
			}
			Response.Write ("</td>");
		}
		


		///////////////////////////////////////////////////////////////////////
		public void write_menu(HttpResponse Response, string this_link)
		{

			Response.Write("<table border=0 width=100% cellpadding=0 cellspacing=0 class=menubar><tr>");

			// logo
			string logo = Util.get_setting("LogoHtml","");
			
			if (logo == "")
			{
				Response.Write("<td width=100 valign=middle>");
				Response.Write("<a href=http://btnet.sourceforge.net><div class=logo>");
				Response.Write(Util.get_setting("AppTitle","BugTracker.NET"));
				Response.Write("</div></a>");
				Response.Write("</td>");
				Response.Write("<td width=20>&nbsp</td>");
				Response.Write("</td>");
			}
			else
			{
				Response.Write(logo);
			}

			write_menu_item(Response, this_link, Util.get_setting("PluralBugLabel","bugs"), "bugs.aspx");
			write_menu_item(Response, this_link, "search", "search.aspx");
			if (this_is_admin || Util.get_setting("AllowQueryPageForNonAdmins","1") == "1")
			{
				write_menu_item(Response, this_link, "queries", "queries.aspx");
			}
			
			if (this_is_admin)
			{
				write_menu_item(Response, this_link, "admin", "admin.aspx");
			}
			write_menu_item(Response, this_link, "reports", "reports.aspx");
			
			// for guest account, suppress display of "edit_self
			if (!this_is_guest)
			{
				write_menu_item(Response, this_link, "settings", "edit_self.aspx");
			}
			
			if (auth_method == "plain")
			{
				write_menu_item(Response, this_link, "logoff", "logoff.aspx");
			}
			
			if (Util.get_setting("CustomMenuLinkLabel","") != "")
			{
				write_menu_item(Response, this_link, 
					Util.get_setting("CustomMenuLinkLabel",""), 
					Util.get_setting("CustomMenuLinkUrl",""));
			}

			write_menu_item(Response, this_link, "about", "about.aspx");

			// go to
			Response.Write("<td nowrap valign=middle>");
			Response.Write("<form style='margin: 0px; padding: 0px;' action=edit_bug.aspx method=get>");
			Response.Write("<font size=1>id:&nbsp;</font>");
			Response.Write("<input style='font-size: 8pt;' size=4 type=text name=id accesskey=i>");
			Response.Write("<input class=btn style='font-size: 8pt;' type=submit value='go to ");
			Response.Write(Util.get_setting("SingularBugLabel","bug"));
			Response.Write ("'>");
			Response.Write("</form>");
			Response.Write("</td>");

			Response.Write ("<td nowrap valign=middle>");
			Response.Write ("<span class=smallnote>logged in as:<br>");
			Response.Write (this_username);
			Response.Write ("</span></td>");

			Response.Write("</tr></table><br>");

		}


	}
	

	///////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////
	// Util
	///////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////
	public class Util {

		static Regex reEmail = new Regex(
				@"([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\."
				+ @")|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})",
				RegexOptions.IgnoreCase
				| RegexOptions.CultureInvariant
				| RegexOptions.IgnorePatternWhitespace
				| RegexOptions.Compiled);

			// convert URL's to hyperlinks
		static Regex reHyperlinks = new Regex(
				@"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*",
				RegexOptions.IgnoreCase
				| RegexOptions.CultureInvariant
				| RegexOptions.IgnorePatternWhitespace
				| RegexOptions.Compiled);

		///////////////////////////////////////////////////////////////////////
		public static string get_log_file_path() {

			// determine log file name
			string log_file_folder = Util.get_setting("LogFileFolder","c:\\");
			DateTime now = DateTime.Now;
			string now_string = 
				(now.Year).ToString()
				+ "_" +
				(now.Month).ToString("0#")
				+ "_" +
				(now.Day).ToString("0#");
		
			string path = log_file_folder
				+ "\\"
				+ "btnet_log_"
				+ now_string
				+ ".txt";
				
			return path;

		}

		///////////////////////////////////////////////////////////////////////
		public static void write_to_log(HttpRequest request, string s)
		{

			if (Util.get_setting("LogEnabled","1") == "0")
			{
				return;
			}
			
			if (!System.IO.Directory.Exists(Util.get_setting("LogFileFolder","c:\\")))
			{
				throw (new Exception("LogFileFolder specified in Web.config, \"" 
				+ Util.get_setting("LogFileFolder","c:\\")
				+ "\", not found.  Edit Web.config."));
			}
	
			string path = get_log_file_path();
			System.IO.StreamWriter w = System.IO.File.AppendText(path);

			// write to it
			w.WriteLine(DateTime.Now.ToLongTimeString()	
				+ " " 
				+ request.Url.ToString() 
				+ " " 
				+ s);

			w.Close();

		}

		///////////////////////////////////////////////////////////////////////
		public static void write_to_log(string s)
		{

			if (Util.get_setting("LogEnabled","1") == "0")
			{
				return;
			}

			if (!System.IO.Directory.Exists(Util.get_setting("LogFileFolder","c:\\")))
			{
				throw (new Exception("LogFileFolder specified in Web.config, \"" 
				+ Util.get_setting("LogFileFolder","c:\\")
				+ "\", not found.  Edit Web.config."));
			}
	
			string path = get_log_file_path();
			System.IO.StreamWriter w = System.IO.File.AppendText(path);

			// write to it
			w.WriteLine(DateTime.Now.ToLongTimeString()	
				+ " " 
				+ s);

			w.Close();

		}


		
		///////////////////////////////////////////////////////////////////////
		public static void do_not_cache(HttpResponse Response)
		{
			Response.CacheControl = "no-cache"; 
			Response.AddHeader ("Pragma", "no-cache"); 
			Response.Expires = -1;
		}
		
		///////////////////////////////////////////////////////////////////////
		public static string get_setting(string name, string default_value)
		{
			
			NameValueCollection name_values
				= (NameValueCollection)ConfigurationSettings.GetConfig("btnetSettings");
			if (name_values[name] == null || name_values[name] == "")
			{
				return default_value;
			}
			else
			{
				return name_values[name];
			}
		}


		///////////////////////////////////////////////////////////////////////
		public static bool is_int(string maybe_int)
		{
			try
			{
				int i = Int32.Parse(maybe_int);
				return true;
			}
			catch (Exception e)
			{
				return false;
			}
		}

		///////////////////////////////////////////////////////////////////////
		public static string bool_to_string(bool b)
		{
			return (b ? "1" : "0");
		}
					
		
		///////////////////////////////////////////////////////////////////////
		public static System.Globalization.CultureInfo get_culture_info()
		{
			// Create a basic culture object to provide also all input parsing
			return new System.Globalization.CultureInfo(get_setting("CultureName",System.Threading.Thread.CurrentThread.CurrentCulture.Name));								
		}

		///////////////////////////////////////////////////////////////////////
		public static string format_db_date(object date)
		{


			if (date.GetType().ToString() == "System.DBNull")
			{
				return "";
			}
			// not sure when this case happens, but it's a workaround for a bug
			// somebody reported, 1257368
			else if (date.GetType().ToString() == "System.String")
			{
				return date.ToString();
			}

			return ((DateTime)date).ToString(get_setting("DateTimeFormat","g"),get_culture_info());

		}
		

		///////////////////////////////////////////////////////////////////////
		public static string format_local_date_into_db_format(string date)
		{
			
			
			// seems to already be in the right format			
			DateTime d;
			try 
			{
				d = DateTime.Parse(date,get_culture_info());						
			}
			catch (FormatException)
			{
				// Can not translate this
				return "";
			}
			// Note that yyyyMMdd hh:mm:ss is a universal SQL dateformat for strings.
			return d.ToString(get_setting("SQLServerDateFormat","yyyyMMdd hh:mm:ss"));			

		}

		///////////////////////////////////////////////////////////////////////
		static string convert_to_hyperlink(Match m)
		{
			return String.Format("<a target=_blank href='{0}'>{0}</a>", m.ToString());
		}


		///////////////////////////////////////////////////////////////////////
		static string convert_to_email(Match m) 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -