Example #1
1
	protected void cmdLogin_Click (object sender, EventArgs e)
	{
		LoginResponse response;

		Master.ClearLogin ();

		try {
			WebServiceLogin login = new WebServiceLogin ();
			login.User = txtUser.Text;
			login.Password = txtPassword.Text;
			Console.WriteLine ("Trying to log in with {0}/{1}", login.User, login.Password);
			login.Ip4 = Utilities.GetExternalIP (Context.Request);
			response = Master.WebService.Login (login);
			if (response == null) {
				lblMessage.Text = "Could not log in.";
				txtPassword.Text = "";
			} else {
				Console.WriteLine ("Login.aspx: Saved cookie!");
				FormsAuthenticationTicket cookie = new FormsAuthenticationTicket ("cookie", true, 60 * 24);
				Response.Cookies.Add (new HttpCookie ("cookie", response.Cookie));
				Response.Cookies ["cookie"].Expires = DateTime.Now.AddDays (1);
				Response.Cookies.Add (new HttpCookie ("user", login.User));
				FormsAuthentication.SetAuthCookie (response.User, true);
				Response.Redirect (txtReferrer.Value, false);
			}
		} catch (Exception) {
			lblMessage.Text = "Invalid user/password.";
			txtPassword.Text = "";
		}
	}
Example #2
0
		private void VerifyUserInRoles (DB db, WebServiceLogin login, string[] roles, bool @readonly)
		{
			// Administrator should be given access to everything.
			// So any call to VerifyUserInRoles should add Administrator to that list.
			var completeRoles = roles.Concat(new string[] { Roles.Administrator }).ToArray();
			Authentication.VerifyUserInRoles (Context, db, login, completeRoles, @readonly);
		}
		protected override void OnLoad (EventArgs e)
		{
			base.OnLoad (e); 
			webServiceLogin = Authentication.CreateLogin (Request);

			var laneName = Request.QueryString ["laneName"];
			var baseURL = Request.QueryString ["url"] ?? "http://storage.bos.internalx.com";
			var updateRequest = false;
			var step =  10;
			var limit =  200;

			var revision = getLatestRevision (webServiceLogin, laneName, step, 0, limit);

			Action handleGetLatest = () => {
				var homePage = Page.ResolveUrl ("~/index.aspx");
				var URL = revision != "" ? String.Format ("{0}/{1}/{2}/{3}/manifest", baseURL, laneName, revision.Substring (0, 2), revision) : homePage;
				Response.AppendHeader ("Access-Control-Allow-Origin", "*");
				Response.Redirect (URL);
			};

			Action handleUpdate = () => {
				Response.Write("");
			};

			if (updateRequest) {
				handleUpdate ();
			} else {
				handleGetLatest ();
			}
		}
Example #4
0
		protected override void OnLoad (EventArgs e)
		{
			base.OnLoad (e);
			login = Authentication.CreateLogin (Request);

			requestType = Request.QueryString ["type"];
			limit = Utils.TryParseInt32 (Request.QueryString ["limit"]) ?? 50;
			offset = Utils.TryParseInt32 (Request.QueryString ["offset"]) ?? 0;

			Response.AppendHeader("Access-Control-Allow-Origin", "*");
			switch (requestType) {
				case "laneinfo":
					Response.Write (GetLaneInfo ());
					break;
				case "taginfo":
					Response.Write (GetTagInfo ());
					break;
				case "botinfo":
					GetBotInfo ();
					break;
				case "botstatus":
					Response.Write (GetBotStatusTimes ());
					break;
				default:
					GetBotStatus ();
					break;
			}
		}
Example #5
0
		public LoginResponse Login (WebServiceLogin login)
		{
			LoginResponse response = new LoginResponse ();
			using (DB db = new DB ()) {
				Authenticate (db, login, response);
				response.User = login.User;
				return response;
			}
		}
		public LoginResponse LoginOpenId (WebServiceLogin login, string email, string ip4)
		{
			LoginResponse response = new LoginResponse ();

			using (DB db = new DB ()) {
				VerifyUserInRole (db, login, Roles.Administrator);
				DBLogin_Extensions.LoginOpenId (db, response, email, ip4);
				return response;
			}
		}
Example #7
0
		protected override void OnLoad (EventArgs e)
		{
			base.OnLoad (e); 
			webServiceLogin = Authentication.CreateLogin (Request);

			Response.AppendHeader("Access-Control-Allow-Origin", "*");
			Response.AppendHeader("Content-Type", "text/plain");
			Response.StatusCode = 404;
			Response.Write("GetLatest is deprecated, please use http://wrench.internalx.com/Wrench/GetManifest.aspx or http://wrench.internalx.com/Wrench/GetMetadata.aspx");
		}
Example #8
0
		private Dictionary<string, IEnumerable<HostHistoryEntry>> GetHostHistory (WebServiceLogin web_service_login, int limit, int offset) {
			var hosts = Utils.LocalWebService.GetHosts (login).Hosts.OrderBy(h => h.host);
			var hostHistoryResponses = hosts.Select (host =>
				Utils.LocalWebService.GetWorkHostHistory (login, host.id, "", limit, offset));

			var hostHistories = hostHistoryResponses.ToDictionary (
				hr => hr.Host.host,
				hr => Enumerable.Range(0, hr.RevisionWorks.Count)
					.Select(i =>  new HostHistoryEntry (hr, i))
			);
			return hostHistories;
		}
Example #9
0
		private string GetBotInfo (WebServiceLogin login, bool showHostHistory) {
			var hoststatusresponse = Utils.LocalWebService.GetHostStatus (login);
			var node_information = new Dictionary<string, object> {
				{ "inactiveNodes", GetInactiveHosts (login, hoststatusresponse) },
				{ "activeNodes",   GetActiveHosts (login, hoststatusresponse) },
				{ "downNodes",     GetDownHosts (login, hoststatusresponse) }
				// { "pendingJobs", "asdf" }
			};
			if (showHostHistory)
				node_information.Add ("hostHistory", GetHostHistory (login, limit, offset));
			return JsonConvert.SerializeObject (node_information, Formatting.Indented);
		}
Example #10
0
		public static WebServiceLogin CreateWebServiceLogin (HttpRequest Request)
		{
			WebServiceLogin web_service_login;
			web_service_login = new WebServiceLogin ();
			web_service_login.Cookie = GetCookie (Request, "cookie");
			if (HttpContext.Current.User != null)
				web_service_login.User = GetCookie (Request, "user");
			web_service_login.Ip4 = GetExternalIP (Request);

			// Console.WriteLine ("Master, Cookie: {0}, User: {1}", web_service_login.Cookie, web_service_login.User);

			return web_service_login;
		}
		string getLatestRevision (WebServiceLogin login, string laneName, int step, int offset, int limit){
			var lane = Utils.WebService.FindLane (login, null, laneName).lane;
			var revisions = Utils.WebService.GetRevisions (login, null, laneName, step, offset).Revisions;
			var revisionWorks = revisions.Select (r => Utils.WebService.GetRevisionWorkForLane (login, lane.id, r.id, -1).RevisionWork).ToList ();
			var validRevisions = revisionWorks.Find (wl => validRevision (login, wl));

			if (validRevisions != null) {
				return getRevisionName (revisions, validRevisions.First ().revision_id);
			} else if (offset < limit) {
				return getLatestRevision (login, laneName, step, offset + step, limit);
			} else {
				return "";
			}
		}
Example #12
0
		public LoginResponse LoginOpenId (WebServiceLogin login, string email, string ip4)
		{
			LoginResponse response = new LoginResponse ();

			using (DB db = new DB ()) {
				try {
					VerifyUserInRole (db, login, Roles.Administrator);
					db.Audit (login, "WebServices.LoginOpenId (email: {0}, ip4: {1})", email, ip4);
					DBLogin_Extensions.LoginOpenId (db, response, email, ip4);
				} catch (Exception ex) {
					response.Exception = new WebServiceException (ex);
				}
				return response;
			}
		}
Example #13
0
	public static bool Login (string user, string password, HttpRequest Request, HttpResponse Response)
	{
		LoginResponse response;

		WebServiceLogin login = new WebServiceLogin ();
		login.User = user;
		login.Password = password;

		login.Ip4 = MonkeyWrench.Utilities.GetExternalIP (Request);
		response = Utils.WebService.Login (login);
		if (response == null) {
			Logger.Log ("Login failed");
			return false;
		} else {
			SetCookies (Response, response);
			return true;
		}
	}
Example #14
0
		protected override void OnLoad(EventArgs e)
		{
			var start = DateTime.Now;
			base.OnLoad (e);
			login = Authentication.CreateLogin (Request);
			Response.AppendHeader ("Access-Control-Allow-Origin", "*");
			Dictionary<String, Object> buildStatusResponse = null;
			try {
				if (!string.IsNullOrEmpty (Request ["lane_id"])) {
					var laneId = Utils.TryParseInt32 (Request ["lane_id"]);
					var revisionId = Utils.TryParseInt32 (Request ["revision_id"]);
					if (laneId.HasValue && revisionId.HasValue)
						buildStatusResponse = FetchBuildStatus (laneId.Value, revisionId.Value);
				} else {
					var laneName = Request ["lane_name"];
					var commit = Request ["commit"];
					if (string.IsNullOrEmpty (laneName) || string.IsNullOrEmpty (commit))
						ThrowJsonError (400, "Either lane_name+commit or lane_id+revision_id must be provided to resolve build.");
					buildStatusResponse = FetchBuildStatus (laneName, commit);
				}
				buildStatusResponse.Add ("generation_time", (DateTime.Now - start).TotalMilliseconds);
				Response.Write (JsonConvert.SerializeObject (buildStatusResponse));
			} catch (System.Web.Services.Protocols.SoapException) {
				Response.StatusCode = 403;
				Response.Write (JsonConvert.SerializeObject (new Dictionary<String, String> { {
						"error",
						"You are not authorized to use this resource."
					}
				}));
			} catch (HttpException exp) {
				Response.StatusCode = exp.GetHttpCode ();
				Response.Write (exp.Message);
			} catch (Exception exp) {
				Response.StatusCode = 500;
				Response.Write ("{\"error\": \"" + exp.Message.Replace ("\"", "\\\"") + "\"}");
			} finally {
				Response.Flush ();
				Response.Close ();
			}
		}
Example #15
0
	public static bool Login (string user, string password, HttpRequest Request, HttpResponse Response)
	{
		LoginResponse response;

		WebServiceLogin login = new WebServiceLogin ();
		login.User = user;
		login.Password = password;

		login.Ip4 = MonkeyWrench.Utilities.GetExternalIP (Request);
		response = Utils.WebService.Login (login);
		if (response == null) {
			Logger.Log ("Login failed");
			return false;
		} else {
			Logger.Log ("Login succeeded, cookie: {0}", response.Cookie);
			Response.Cookies.Add (new HttpCookie ("cookie", response.Cookie));
			Response.Cookies ["cookie"].Expires = DateTime.Now.AddDays (1);
			Response.Cookies.Add (new HttpCookie ("user", login.User));
			/* Note that the 'roles' cookie is only used to determine the web ui to show, it's not used to authorize anything */
			Response.Cookies.Add (new HttpCookie ("roles", string.Join (", ", Utils.WebService.GetRoles (login.User))));
			return true;
		}
	}
Example #16
0
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			webServiceLogin = Authentication.CreateLogin(Request);

			var lane = Request.QueryString["lane"];
			var revision = Request.QueryString["revision"];
			var storagePref = Request.QueryString["prefer"];
			var preferAzure = !string.IsNullOrEmpty(storagePref) && (storagePref.ToLower() == "azure");

			var baseUrls = preferAzure ? new string[] { AZURE_ROOT_1, AZURE_ROOT_2, NAS_ROOT } : new string[] { NAS_ROOT };

			var step = 10;
			var limit = 200;

			revision = string.IsNullOrEmpty(revision) ? getLatestRevision(webServiceLogin, lane, step, 0, limit) : revision;

			if (revision != "") {
				writeOutput(baseUrls, lane, revision, storagePref);
			} else {
				throw new HttpException(404, "No Valid Revisions");
			}
		}
Example #17
0
	public void ClearLogin ()
	{
		web_service_login = null;
	}
		public FindRevisionResponse FindRevisionForLane (WebServiceLogin login, int? revision_id, string revision, int? lane_id, string lane)
		{
			FindRevisionResponse response = new FindRevisionResponse ();

			using (DB db = new DB ()) {
				Authenticate (db, login, response, true);
				if ((revision_id == null || revision_id.Value <= 0) && string.IsNullOrEmpty (revision))
					return response;

				if ((lane_id == null || lane_id.Value <= 0) && string.IsNullOrEmpty (lane))
					return response;

				using (IDbCommand cmd = db.CreateCommand ()) {
					if (!lane_id.HasValue) {
						if (!revision_id.HasValue) {
							cmd.CommandText = "SELECT * FROM Revision INNER JOIN Lane ON Revision.lane_id = Lane.id WHERE Revision.revision = @revision AND Lane.lane = @lane;";
							DB.CreateParameter (cmd, "revision", revision);
						} else {
							cmd.CommandText = "SELECT * FROM Revision INNER JOIN Lane ON Revision.lane_id = Lane.id WHERE id = @id AND Lane.lane = @lane;";
							DB.CreateParameter (cmd, "id", revision_id.Value);
						}
						DB.CreateParameter (cmd, "lane", lane);
					} else {
						if (!revision_id.HasValue) {
							cmd.CommandText = "SELECT * FROM Revision WHERE revision = @revision AND lane_id = @lane_id;";
							DB.CreateParameter (cmd, "revision", revision);
						} else {
							cmd.CommandText = "SELECT * FROM Revision WHERE id = @id AND lane_id = @lane_id;";
							DB.CreateParameter (cmd, "id", revision_id.Value);
						}
						DB.CreateParameter (cmd, "lane_id", lane_id.Value);
					}
					DB.CreateParameter (cmd, "lane_id", lane_id);

					using (IDataReader reader = cmd.ExecuteReader ()) {
						if (reader.Read ()) {
							response.Revision = new DBRevision (reader);
						}
					}
				}
			}

			return response;
		}
		public FindHostResponse FindHost (WebServiceLogin login, int? host_id, string host)
		{
			FindHostResponse response = new FindHostResponse ();
			using (DB db = new DB ()) {
				Authenticate (db, login, response);

				response.Host = FindHost (db, host_id, host);

				return response;
			}
		}
		public GetLaneForEditResponse GetLaneForEdit (WebServiceLogin login, int lane_id, string lane)
		{
			GetLaneForEditResponse response = new GetLaneForEditResponse ();
			using (DB db = new DB ()) {
				Authenticate (db, login, response);
				VerifyUserInRole (db, login, Roles.Administrator);

				// We do 2 trips to the database: first to get a list of all the lanes,
				// then to get all the rest of the information.

				response.Lanes = db.GetAllLanes ();

				if (lane_id > 0) {
					response.Lane = response.Lanes.Find ((l) => l.id == lane_id);
				} else {
					response.Lane = response.Lanes.Find ((l) => l.lane == lane);
				}

				var cmdText = new StringBuilder ();

				using (var cmd = db.CreateCommand ()) {
					// 1: db.GetAllLanes
					cmdText.AppendLine ("SELECT * FROM Lane ORDER BY lane;");

					// 2: response.Lane.GetCommandsInherited (db, response.Lanes);
					cmdText.Append ("SELECT * FROM Command WHERE lane_id = ").Append (response.Lane.id);
					DBLane parent = response.Lane;
					while (null != (parent = response.Lanes.FirstOrDefault ((v) => v.id == parent.parent_lane_id))) {
						cmdText.Append (" OR lane_id = ").Append (parent.id);
					}
					cmdText.AppendLine (" ORDER BY sequence;");

					// 3: response.Dependencies = response.Lane.GetDependencies (db);
					cmdText.AppendFormat ("SELECT * FROM LaneDependency WHERE lane_id = {0} ORDER BY dependent_lane_id;", response.Lane.id).AppendLine ();

//					// 4: response.FileDeletionDirectives = DBFileDeletionDirective_Extensions.GetAll (db);
//					cmdText.AppendLine ("SELECT * FROM FileDeletionDirective;");
//
//					// 5: response.LaneDeletionDirectives = DBLaneDeletionDirectiveView_Extensions.Find (db, response.Lane);
//					cmdText.AppendFormat ("SELECT * FROM LaneDeletionDirectiveView WHERE lane_id = {0};", response.Lane.id).AppendLine ();

					// 6: response.Files = response.Lane.GetFiles (db, response.Lanes);
					cmdText.Append (@"
SELECT Lanefile.id, LaneFile.name, '' AS contents, LaneFile.mime, Lanefile.original_id, LaneFile.changed_date 
FROM Lanefile 
INNER JOIN Lanefiles ON Lanefiles.lanefile_id = Lanefile.id 
WHERE Lanefile.original_id IS NULL AND Lanefiles.lane_id = ").Append (response.Lane.id);
					parent = response.Lane;
					while (null != (parent = response.Lanes.FirstOrDefault ((v) => v.id == parent.parent_lane_id))) {
						cmdText.Append (" OR LaneFiles.lane_id = ").Append (parent.id);
					}
					cmdText.AppendLine (" ORDER BY name ASC;");

					// 7: response.LaneFiles = db.GetAllLaneFiles ();
					cmdText.AppendLine ("SELECT * FROM LaneFiles;");

					// 8: response.HostLaneViews = response.Lane.GetHosts (db);
					cmdText.AppendFormat ("SELECT * FROM HostLaneView WHERE lane_id = {0} ORDER BY host;", response.Lane.id).AppendLine ();

					// 9: response.Hosts = db.GetHosts ();
					cmdText.AppendLine ("SELECT * FROM Host ORDER BY host;");

					// 10: response.ExistingFiles = new List<DBLanefile> (); [...]
					cmdText.AppendFormat (@"
SELECT Lanefile.id, LaneFile.name, '' AS contents, LaneFile.mime, Lanefile.original_id, LaneFile.changed_date 
FROM Lanefile
INNER JOIN Lanefiles ON Lanefiles.lanefile_id = Lanefile.id
WHERE Lanefile.original_id IS NULL AND Lanefiles.lane_id <> {0}
ORDER BY Lanefiles.lane_id, Lanefile.name ASC;", response.Lane.id).AppendLine ();

					// 11: response.Variables = DBEnvironmentVariable_Extensions.Find (db, response.Lane.id, null, null);
					cmdText.AppendFormat ("SELECT * FROM EnvironmentVariable WHERE lane_id = {0} AND host_id IS NULL ORDER BY id ASC;", response.Lane.id).AppendLine ();

					// 12: response.Notifications = new List<DBNotification> ();
					cmdText.AppendLine ("SELECT * FROM Notification;");

					// 13: response.LaneNotifications = new List<DBLaneNotification> ();
					cmdText.AppendFormat ("SELECT * FROM LaneNotification WHERE lane_id = {0};", response.Lane.id).AppendLine ();

					// 14
					cmdText.AppendFormat ("SELECT * FROM LaneTag WHERE lane_id = {0};", response.Lane.id).AppendLine ();

					cmd.CommandText = cmdText.ToString ();

					using (IDataReader reader = cmd.ExecuteReader ()) {
						// 1: db.GetAllLanes
						response.Lanes = new List<DBLane> ();
						while (reader.Read ())
							response.Lanes.Add (new DBLane (reader));

						// 2: response.Lane.GetCommandsInherited (db, response.Lanes);
						reader.NextResult ();
						response.Commands = new List<DBCommand> ();
						while (reader.Read ())
							response.Commands.Add (new DBCommand (reader));
						
						// 3: response.Dependencies = response.Lane.GetDependencies (db);
						reader.NextResult ();
						response.Dependencies = new List<DBLaneDependency> ();
						while (reader.Read ())
							response.Dependencies.Add (new DBLaneDependency (reader));

//						// 4: response.FileDeletionDirectives = DBFileDeletionDirective_Extensions.GetAll (db);
//						reader.NextResult ();
//						response.FileDeletionDirectives = new List<DBFileDeletionDirective> ();
//						while (reader.Read ()) {
//							response.FileDeletionDirectives.Add (new DBFileDeletionDirective (reader));
//						}
//
//						// 5: response.LaneDeletionDirectives = DBLaneDeletionDirectiveView_Extensions.Find (db, response.Lane);
//						reader.NextResult ();
//						response.LaneDeletionDirectives = new List<DBLaneDeletionDirectiveView> ();
//						while (reader.Read ())
//							response.LaneDeletionDirectives.Add (new DBLaneDeletionDirectiveView (reader));
					
						// 6: response.Files = response.Lane.GetFiles (db, response.Lanes);
						reader.NextResult ();
						response.Files = new List<DBLanefile> ();
						while (reader.Read ())
							response.Files.Add (new DBLanefile (reader));

						// 7: response.LaneFiles = db.GetAllLaneFiles ();
						reader.NextResult ();
						response.LaneFiles = new List<DBLanefiles> ();
						while (reader.Read ())
							response.LaneFiles.Add (new DBLanefiles (reader));

						// 8: response.HostLaneViews = response.Lane.GetHosts (db);
						reader.NextResult ();
						response.HostLaneViews = new List<DBHostLaneView> ();
						while (reader.Read ()) {
							response.HostLaneViews.Add (new DBHostLaneView (reader));
						}

						// 9: response.Hosts = db.GetHosts ();
						reader.NextResult ();
						response.Hosts = new List<DBHost> ();
						while (reader.Read ())
							response.Hosts.Add (new DBHost (reader));

						// 10: response.ExistingFiles = new List<DBLanefile> (); [...]
						reader.NextResult ();
						response.ExistingFiles = new List<DBLanefile> ();
						while (reader.Read ())
							response.ExistingFiles.Add (new DBLanefile (reader));

						// 11: response.Variables = DBEnvironmentVariable_Extensions.Find (db, response.Lane.id, null, null);
						reader.NextResult ();
						response.Variables = new List<DBEnvironmentVariable> ();
						while (reader.Read ())
							response.Variables.Add (new DBEnvironmentVariable (reader));

						// 12: response.Notifications = new List<DBNotification> ();
						reader.NextResult ();
						response.Notifications = new List<DBNotification> ();
						while (reader.Read ())
							response.Notifications.Add (new DBNotification (reader));

						// 13: response.LaneNotifications = new List<DBLaneNotification> ();
						reader.NextResult ();
						response.LaneNotifications = new List<DBLaneNotification> ();
						while (reader.Read ())
							response.LaneNotifications.Add (new DBLaneNotification (reader));

						// 14
						reader.NextResult ();
						if (reader.Read ()) {
							response.Tags = new List<DBLaneTag> ();
							do {
								response.Tags.Add (new DBLaneTag (reader));
							} while (reader.Read ());
						}
					}
				}

				return response;
			}
		}
		public void RemoveMasterHost (WebServiceLogin login, int host_id, int masterhost_id)
		{
			using (DB db = new DB ()) {
				VerifyUserInRole (db, login, Roles.Administrator);

				using (IDbCommand cmd = db.CreateCommand ()) {
					cmd.CommandText = "DELETE FROM MasterHost WHERE host_id = @host_id AND master_host_id = @masterhost_id;";
					DB.CreateParameter (cmd, "host_id", host_id);
					DB.CreateParameter (cmd, "masterhost_id", masterhost_id);
					cmd.ExecuteNonQuery ();
				}
			}
		}
		public void AddMasterHost (WebServiceLogin login, int host_id, int masterhost_id)
		{
			using (DB db = new DB ()) {
				VerifyUserInRole (db, login, Roles.Administrator);

				DBMasterHost mh = new DBMasterHost ();
				mh.master_host_id = masterhost_id;
				mh.host_id = host_id;
				mh.Save (db);
			}
		}
		public GetHostForEditResponse GetHostForEdit (WebServiceLogin login, int? host_id, string host)
		{
			GetHostForEditResponse response = new GetHostForEditResponse ();

			using (DB db = new DB ()) {
				VerifyUserInRole (db, login, Roles.Administrator);

				response.Host = FindHost (db, host_id, host);
				response.Lanes = db.GetAllLanes ();
				if (response.Host != null) {
					response.Person = FindPerson (db, response.Host.host);
					response.HostLaneViews = response.Host.GetLanes (db);
					response.Variables = DBEnvironmentVariable_Extensions.Find (db, null, response.Host.id, null);
					response.MasterHosts = GetMasterHosts (db, response.Host);
					response.SlaveHosts = GetSlaveHosts (db, response.Host);
				}
				response.Hosts = db.GetHosts ();
			}

			return response;
		}
		private void Audit(WebServiceLogin login, string formatStr, params Object[] formatArgs) {
			auditLog.InfoFormat ("User {0}@{1} {2}", login.User, login.Ip4, String.Format (formatStr, formatArgs));
		}
Example #25
0
		/// <summary>
		/// Authenticates the request with the provided user/pass.
		/// If no user/pass is provided, the method returns a response
		/// with no roles.
		/// If a wrong user/pass is provided, the method throws an exception.
		/// </summary>
		/// <param name="db"></param>
		/// <param name="login"></param>
		/// <param name="response"></param>
		public static void Authenticate (HttpContext Context, DB db, WebServiceLogin login, WebServiceResponse response, bool @readonly)
		{
			Authenticate (Context.Request.UserHostAddress, db, login, response, @readonly);
		}
Example #26
0
		/// <summary>
		/// Verify that the user is a valid user if anonymous access isn't allowed
		/// </summary>
		/// <param name="Context"></param>
		/// <param name="db"></param>
		/// <param name="login"></param>
		public static void VerifyAnonymousAccess (HttpContext Context, DB db, WebServiceLogin login)
		{
			if (Configuration.AllowAnonymousAccess)
				return;
			Authenticate (Context, db, login, null, true);
		}
Example #27
0
		public static void VerifyUserInRole (string remote_ip, DB db, WebServiceLogin login, string role, bool @readonly)
		{
			WebServiceResponse dummy = new WebServiceResponse ();
			Authenticate (remote_ip, db, login, dummy, @readonly);

			if (!dummy.IsInRole (role)) {
				Logger.Log (2, "The user '{0}' has the roles '{1}', and requested role is: {2}", login.User, dummy.UserRoles == null ? "<null>" : string.Join (",", dummy.UserRoles), role);
				throw new HttpException (403, "You don't have the required permissions.");
			}
		}
		public GetWorkHostHistoryResponse GetWorkHostHistory (WebServiceLogin login, int? host_id, string host, int limit, int offset)
		{
			GetWorkHostHistoryResponse response = new GetWorkHostHistoryResponse ();

			using (DB db = new DB ()) {
				Authenticate (db, login, response, true);

				response.Host = FindHost (db, host_id, host);
				response.RevisionWorks = new List<DBRevisionWork> ();
				response.Lanes = new List<string> ();
				response.Revisions = new List<string> ();
				response.StartTime = new List<DateTime> ();
				response.Hosts = new List<string> ();
				response.Durations = new List<int> ();

				using (IDbCommand cmd = db.CreateCommand ()) {
					cmd.CommandText = @"
SELECT RevisionWork.*, Host.host, Lane.lane, Revision.revision, MIN (Work.starttime) AS order_date,
-- calculate the duration of each work and add them up
   SUM (EXTRACT (EPOCH FROM (
		(CASE
			WHEN (Work.starttime = '-infinity' OR Work.starttime < '2001-01-01') AND (Work.endtime = '-infinity' OR Work.endtime < '2001-01-01') THEN LOCALTIMESTAMP - LOCALTIMESTAMP
			WHEN (Work.endtime = '-infinity' OR Work.endtime < '2001-01-01') THEN CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - Work.starttime
			ELSE Work.endtime - Work.starttime
			END)
		))) AS duration
FROM RevisionWork
INNER JOIN Revision ON RevisionWork.revision_id = Revision.id
INNER JOIN Lane ON RevisionWork.lane_id = Lane.id
INNER JOIN Work ON RevisionWork.id = Work.revisionwork_id
INNER JOIN Host ON RevisionWork.host_id = Host.id
WHERE RevisionWork.workhost_id = @host_id AND (Work.starttime > '2001-01-01' AND Work.endtime > '2001-01-01') 
GROUP BY RevisionWork.id, RevisionWork.lane_id, RevisionWork.host_id, RevisionWork.workhost_id, RevisionWork.revision_id, RevisionWork.state, RevisionWork.lock_expires, RevisionWork.completed, RevisionWork.endtime, Lane.lane, Revision.revision, Host.host ";
					cmd.CommandText += " ORDER BY RevisionWork.completed ASC, order_date DESC ";
					if (limit > 0)
						cmd.CommandText += " LIMIT " + limit.ToString ();
					if (offset > 0)
						cmd.CommandText += " OFFSET " + offset.ToString ();
					cmd.CommandText += ";";
					DB.CreateParameter (cmd, "host_id", response.Host.id);

					using (IDataReader reader = cmd.ExecuteReader ()) {
						int lane_idx = reader.GetOrdinal ("lane");
						int revision_idx = reader.GetOrdinal ("revision");
						int starttime_idx = reader.GetOrdinal ("order_date");
						int host_idx = reader.GetOrdinal ("host");
						int duration_idx = reader.GetOrdinal ("duration");
						while (reader.Read ()) {
							response.RevisionWorks.Add (new DBRevisionWork (reader));
							response.Lanes.Add (reader.GetString (lane_idx));
							response.Revisions.Add (reader.GetString (revision_idx));
							response.StartTime.Add (reader.GetDateTime (starttime_idx));
							response.Hosts.Add (reader.GetString (host_idx));
							response.Durations.Add ((int) reader.GetDouble (duration_idx));
						}
					}
				}
			}

			return response;
		}
Example #29
0
		public static void Authenticate (string user_host_address, DB db, WebServiceLogin login, WebServiceResponse response, bool @readonly)
		{
			string ip = user_host_address;
			int person_id;
			DBLoginView view = null;

			Logger.Log (2, "WebService.Authenticate (Ip4: {0}, UserHostAddress: {1}, User: {2}, Cookie: {3}, Password: {4}", login == null ? null : login.Ip4, user_host_address, login == null ? null : login.User, login == null ? null : login.Cookie, login == null ? null : login.Password);

			// Check if credentials were passed in
			if (login == null || string.IsNullOrEmpty (login.User) || (string.IsNullOrEmpty (login.Password) && string.IsNullOrEmpty (login.Cookie))) {
				Logger.Log (2, "No credentials.");
				VerifyAnonymousAllowed ();
				return;
			}

			if (!string.IsNullOrEmpty (login.Ip4)) {
				ip = login.Ip4;
			} else {
				ip = user_host_address;
			}

			if (!string.IsNullOrEmpty (login.Password)) {
				DBLogin result = DBLogin_Extensions.Login (db, login.User, login.Password, ip, @readonly);
				if (result != null) {
					if (@readonly) {
						person_id = result.person_id;
					} else {
						view = DBLoginView_Extensions.VerifyLogin (db, login.User, result.cookie, ip);
						if (view == null) {
							Logger.Log (2, "Invalid cookie");
							VerifyAnonymousAllowed();
							return;
						}
						person_id = view.person_id;
					}
				} else {
					Logger.Log (2, "Invalid user/password");
					VerifyAnonymousAllowed ();
					return;
				}
			} else {
				view = DBLoginView_Extensions.VerifyLogin (db, login.User, login.Cookie, ip);
				if (view == null) {
					Logger.Log (2, "Invalid cookie");
					VerifyAnonymousAllowed ();
					return;
				}
				person_id = view.person_id;
				Logger.Log (2, "Verifying login, cookie: {0} user: {1} ip: {2}", login.Cookie, login.User, ip);
			}

			Logger.Log (2, "Valid credentials");

			if (response == null)
				return;

			DBPerson person = DBPerson_Extensions.Create (db, person_id);
			LoginResponse login_response = response as LoginResponse;
			if (login_response != null) {
				login_response.Cookie = view != null ? view.cookie : null;
				login_response.FullName = person.fullname;
				login_response.ID = person_id;
			}

			response.UserName = person.login;
			response.UserRoles = person.Roles;
			Logger.Log (2, "Authenticate2 Roles are: {0}", response.UserRoles == null ? "null" : string.Join (";", response.UserRoles));
		}
		private void VerifyUserInRole (DB db, WebServiceLogin login, string role, bool @readonly)
		{
			Authentication.VerifyUserInRole (Context, db, login, role, @readonly);
		}