/// <summary> /// Evaluates if menu item should be visible to current user with access to <see cref="Roles"/>. /// </summary> /// <param name="parameter"> /// Data used by the <see cref="MenuCommand"/>. If the <see cref="MenuCommand"/> does not require /// data to be passed, this object can be set to <c>null</c>. /// </param> /// <returns><c>true</c> if this <see cref="MenuCommand"/> can be executed; otherwise, <c>false</c>.</returns> public bool CanExecute(object parameter) { SecurityPrincipal currentPrincipal = CommonFunctions.CurrentPrincipal; return(currentPrincipal.Identity.IsAuthenticated && (string.IsNullOrEmpty(Roles) || Roles == "*" || currentPrincipal.IsInRole(Roles))); }
/// <summary> /// Called when authorization is required. /// </summary> /// <param name="filterContext">The filter context.</param> public void OnAuthorization(AuthorizationContext filterContext) { SecurityPrincipal securityPrincipal = filterContext.HttpContext.User as SecurityPrincipal; if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null) { filterContext.Result = new HttpUnauthorizedResult($"Authentication failed for user \"{filterContext.HttpContext.User?.Identity.Name}\"."); filterContext.HttpContext.User = null; return; } // Get current user name string username = securityPrincipal.Identity.Name; // Verify that the current thread principal has been authenticated. if (!securityPrincipal.Identity.IsAuthenticated) { filterContext.Result = new HttpUnauthorizedResult($"User \"{username}\" is not authenticated."); filterContext.HttpContext.User = null; } else if (AllowedRoles.Length > 0 && !AllowedRoles.Any(role => securityPrincipal.IsInRole(role))) { filterContext.Result = new HttpUnauthorizedResult($"Access is denied for user \"{username}\": minimum required roles = {AllowedRoles.ToDelimitedString(", ")}."); filterContext.HttpContext.User = null; } else { ThreadPool.QueueUserWorkItem(start => AuthorizationCache.CacheAuthorization(username, SecuritySettingsCategory)); } }
/// <summary> /// Evaluates if menu item should be visible to current user with access to <see cref="Roles"/>. /// </summary> /// <param name="parameter"> /// Data used by the <see cref="MenuCommand"/>. If the <see cref="MenuCommand"/> does not require /// data to be passed, this object can be set to <c>null</c>. /// </param> /// <returns><c>true</c> if this <see cref="MenuCommand"/> can be executed; otherwise, <c>false</c>.</returns> public bool CanExecute(object parameter) { SecurityPrincipal currentPrincipal = CommonFunctions.CurrentPrincipal; ISecurityProvider securityProvider; if (!SecurityProviderCache.TryGetCachedProvider(currentPrincipal.Identity.Name, out securityProvider)) { securityProvider = SecurityProviderCache.CurrentProvider; } return(((object)securityProvider != null) && currentPrincipal.Identity.IsAuthenticated && securityProvider.UserData.Roles.Any() && (string.IsNullOrEmpty(Roles) || Roles == "*" || currentPrincipal.IsInRole(Roles))); }
private ActionResult ValidateAdminRequest() { string username = HttpContext.User.Identity.Name; ISecurityProvider securityProvider = SecurityProviderUtility.CreateProvider(username); securityProvider.PassthroughPrincipal = HttpContext.User; if (!securityProvider.Authenticate()) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden)); } SecurityIdentity approverIdentity = new SecurityIdentity(securityProvider); SecurityPrincipal approverPrincipal = new SecurityPrincipal(approverIdentity); if (!approverPrincipal.IsInRole("Administrator")) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden)); } return(null); }
/// <summary> /// Provides an entry point for custom authorization checks. /// </summary> /// <param name="user">The <see cref="IPrincipal"/> for the client being authorize</param> /// <returns> /// <c>true</c> if the user is authorized, otherwise, <c>false</c>. /// </returns> protected override bool UserAuthorized(IPrincipal user) { SecurityPrincipal securityPrincipal = user as SecurityPrincipal; if ((object)securityPrincipal == null) { return(false); } // Verify that the current thread principal has been authenticated. if (!securityPrincipal.Identity.IsAuthenticated) { return(false); } if (AllowedRoles.Length > 0 && !AllowedRoles.Any(role => securityPrincipal.IsInRole(role))) { return(false); } ThreadPool.QueueUserWorkItem(start => AuthorizationCache.CacheAuthorization(securityPrincipal.Identity.Name, SecuritySettingsCategory)); return(true); }
public IHttpActionResult DeleteRecord(int id, string modelName) { // Proxy all other requests SecurityPrincipal securityPrincipal = RequestContext.Principal as SecurityPrincipal; if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null || !securityPrincipal.IsInRole("Administrator")) { return(BadRequest($"User \"{RequestContext.Principal?.Identity.Name}\" is unauthorized.")); } using (DataContext dataContext = new DataContext("systemSettings")) { Type type = typeof(Meter).Assembly.GetType("openXDA.Model." + modelName); dataContext.Table(type).DeleteRecordWhere("ID = {0}", id); } return(Ok()); }
public IHttpActionResult GetRecordCount(string modelName) { // Proxy all other requests SecurityPrincipal securityPrincipal = RequestContext.Principal as SecurityPrincipal; if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null || !securityPrincipal.IsInRole("Viewer,Administrator")) { return(BadRequest($"User \"{RequestContext.Principal?.Identity.Name}\" is unauthorized.")); } object record; using (DataContext dataContext = new DataContext("systemSettings")) { try { Type type = typeof(Meter).Assembly.GetType("SOE.Model." + modelName); record = dataContext.Table(type).QueryRecordCount(); } catch (Exception ex) { return(BadRequest(ex.ToString())); } } return(Ok(record)); }
public IHttpActionResult GetIncidentData(string modelName, [FromBody] JObject record) { int meterId; int circuitId; DateTime startTime; DateTime endTime; int pixels; string type; DataTable table; // Proxy all other requests SecurityPrincipal securityPrincipal = RequestContext.Principal as SecurityPrincipal; if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null || !securityPrincipal.IsInRole("Viewer,Administrator")) { return(BadRequest($"User \"{RequestContext.Principal?.Identity.Name}\" is unauthorized.")); } try { meterId = record["meterId"]?.Value <int>() ?? 0; circuitId = record["circuitId"]?.Value <int>() ?? 0; startTime = DateTime.Parse(record["startDate"].ToString()); endTime = DateTime.Parse(record["endDate"].ToString()); pixels = record["pixels"]?.Value <int>() ?? 0; type = record["type"].Value <string>(); } catch (Exception ex) { return(BadRequest($"{ex.ToString()}")); } using (AdoDataConnection conn = new AdoDataConnection("systemSettings")) { try { Dictionary <string, List <double[]> > dict = new Dictionary <string, List <double[]> >(); string s = $"select Event.ID from GetNearbyIncidentsByCircuit({circuitId},'{startTime.ToString()}', '{endTime.ToString()}', 0)as incident join event on Incident.ID = event.IncidentID where event.MeterID = {meterId}"; table = conn.RetrieveData(s); foreach (DataRow row in table.Rows) { Dictionary <string, List <double[]> > temp = QueryEventData(int.Parse(row["ID"].ToString()), type); foreach (string key in temp.Keys) { if (dict.ContainsKey(key)) { dict[key] = dict[key].Concat(temp[key]).ToList(); } else { dict.Add(key, temp[key]); } } } Dictionary <string, List <double[]> > returnDict = new Dictionary <string, List <double[]> >(); foreach (string key in dict.Keys) { returnDict.Add(key, Downsample(dict[key].OrderBy(x => x[0]).ToList(), pixels, new Range <DateTime>(startTime, endTime))); } return(Ok(returnDict)); } catch (Exception ex) { return(BadRequest(ex.ToString())); } } }
public IHttpActionResult GetIncidentGroups(string modelName, [FromBody] JObject record) { int circuitID; DateTime startTime; DateTime endTime; DataTable table; // Proxy all other requests SecurityPrincipal securityPrincipal = RequestContext.Principal as SecurityPrincipal; if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null || !securityPrincipal.IsInRole("Viewer,Administrator")) { return(BadRequest($"User \"{RequestContext.Principal?.Identity.Name}\" is unauthorized.")); } try { circuitID = record["circuitId"]?.Value <int>() ?? 0; startTime = DateTime.Parse(record["startDate"].ToString()); endTime = DateTime.Parse(record["endDate"].ToString()); } catch (Exception ex) { return(BadRequest($"{ex.ToString()}")); } using (AdoDataConnection conn = new AdoDataConnection("systemSettings")) { try { string s = $"select * from GetNearbyIncidentsByCircuit({circuitID},'{startTime.ToString()}', '{endTime.ToString()}', 0)"; table = conn.RetrieveData(s); return(Ok(table)); } catch (Exception ex) { return(BadRequest(ex.ToString())); } } }
public IHttpActionResult GetView(string modelName, [FromBody] JObject record) { int numBuckets; string timeContext; DateTime startDate; DateTime endDate; string limits; string levels; string circuitName; string systemName; //var dates; // Proxy all other requests SecurityPrincipal securityPrincipal = RequestContext.Principal as SecurityPrincipal; if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null || !securityPrincipal.IsInRole("Viewer,Administrator")) { return(BadRequest($"User \"{RequestContext.Principal?.Identity.Name}\" is unauthorized.")); } try { numBuckets = record["numBuckets"]?.Value <int>() ?? 20; timeContext = record["timeContext"]?.Value <string>() ?? "Days"; startDate = record["date"]?.Value <DateTime>() ?? DateTime.Now.AddDays(-20); endDate = (DateTime)typeof(DateTime).GetMethod("Add" + timeContext).Invoke(startDate, new object[] { numBuckets }); limits = record["limits"]?.Value <string>() ?? ""; levels = record["levels"]?.Value <string>() ?? "Circuit"; circuitName = record["circuitName"]?.Value <string>(); systemName = record["systemName"]?.Value <string>(); } catch (Exception ex) { return(BadRequest($"{ex.ToString()}")); } string groupByString; string dates; string sumString; string sumDates; if (timeContext == "Months") { dates = string.Join(",", Enumerable.Range(0, 1 + numBuckets).Select(offset => (startDate).AddMonths(offset)).Select(x => "[" + x.Date.ToString("M/yyyy") + "]")); sumDates = string.Join(",", Enumerable.Range(0, 1 + numBuckets).Select(offset => (startDate).AddMonths(offset)).Select(x => "SUM([" + x.Date.ToString("M/yyyy") + "]) as [" + x.Date.ToString("M/yyyy") + "]")); groupByString = "cast(datepart(Month, IncidentQuery.StartTime) as varchar(max)) + '/' + cast(datepart(year,IncidentQuery.StartTime) as varchar(max))"; sumString = string.Join("+", Enumerable.Range(0, 1 + numBuckets).Select(offset => (startDate).AddMonths(offset)).Select(x => "COALESCE([" + x.Date.ToString("M/yyyy") + "],0)")); } else if (timeContext == "Days") { dates = string.Join(",", Enumerable.Range(0, 1 + numBuckets).Select(offset => (startDate).AddDays(offset)).Select(x => "[" + x.Date.ToString("MM/dd/yyyy") + "]")); sumDates = string.Join(",", Enumerable.Range(0, 1 + numBuckets).Select(offset => (startDate).AddDays(offset)).Select(x => "SUM([" + x.Date.ToString("MM/dd/yyyy") + "]) as [" + x.Date.ToString("MM/dd/yyyy") + "]")); groupByString = "Cast(IncidentQuery.StartTime as date)"; sumString = string.Join("+", Enumerable.Range(0, 1 + numBuckets).Select(offset => (startDate).AddDays(offset)).Select(x => "COALESCE([" + x.Date.ToString("MM/dd/yyyy") + "],0)")); } else { dates = string.Join(",", Enumerable.Range(0, 1 + numBuckets).Select(offset => (startDate).AddHours(offset)).Select(x => "[" + x.ToString("M/dd H:00") + "]")); sumDates = string.Join(",", Enumerable.Range(0, 1 + numBuckets).Select(offset => (startDate).AddHours(offset)).Select(x => "SUM([" + x.ToString("M/dd H:00") + "]) as [" + x.ToString("M/dd H:00") + "]")); groupByString = "cast(datepart(Month, IncidentQuery.StartTime) as varchar(max)) + '/' + cast(datepart(day, IncidentQuery.StartTime) as varchar(max)) + ' '+ cast(datepart(HOUR,IncidentQuery.StartTime) as varchar(max)) + ':00'"; sumString = string.Join("+", Enumerable.Range(0, 1 + numBuckets).Select(offset => (startDate).AddHours(offset)).Select(x => "COALESCE([" + x.ToString("M/dd H:00") + "],0)")); } using (AdoDataConnection conn = new AdoDataConnection("systemSettings")) { try { string s = $"SELECT {(limits.ToUpper() != "ALL" ? limits : "")} SystemName as System, {(levels.ToUpper() == "SYSTEM" ? "COUNT(DISTINCT CircuitName)" : "CircuitName")} as Circuit, {(levels.ToUpper() == "SYSTEM" ? "COUNT(MeterName)" : "")}{(levels.ToUpper() == "CIRCUIT" ? "COUNT(DISTINCT MeterName)" : "")}{(levels.ToUpper() == "DEVICE" ? "MeterName" : "")} as Device, {sumDates}, SUM({sumString}) as Total, SUM(FileCount) as [CT Files], SUM(SOECount) as SOE " + "FROM ( " + $"SELECT System.Name as SystemName, Circuit.Name as CircuitName, {(levels.ToUpper() == "SYSTEM" ? "COUNT(DISTINCT Meter.Name)": "Meter.Name")} as MeterName, COUNT(*) as Count, {groupByString} as date, SUM(IncidentQuery.FileCount) as FileCount, SUM(SOECount) as SOECount " + "FROM " + "( " + "SELECT Incident.Id, Incident.StartTime, Incident.MeterID, Count(EventQuery.FileGroupID) as FileCount, SUM(SOECount) as SOECount " + "FROM " + "Incident Join " + "( " + "SELECT Event.ID, Event.FileGroupID, Event.IncidentID, Count(SOEPoint.ID) as SOECount " + "FROM Event JOIN " + "CycleData ON CycleData.EventID = event.ID JOIN " + "SOEPoint ON SOEPoint.CycleDataID = CycleData.ID " + "Group By Event.ID, Event.FileGroupID, Event.IncidentID " + ") as EventQuery On Incident.ID = EventQuery.IncidentID " + $"Where Incident.StartTime BETWEEN '{startDate}' AND '{endDate}' " + "GROUP BY Incident.Id, Incident.StartTime, Incident.MeterID " + ") AS IncidentQuery Join " + "Meter ON Meter.ID = incidentquery.MeterID Join " + "Circuit ON Circuit.ID = Meter.CircuitNormalID JOIN " + "System ON System.ID = Circuit.SystemID " + (circuitName != null ? $"WHERE Circuit.Name LIKE '{circuitName}'" : "") + (systemName != null ? $"WHERE System.Name LIKE '{systemName}'" : "") + "GROUP BY " + $"System.Name, Circuit.Name, Meter.Name, {groupByString} " + " ) as t " + " PIVOT(SUM(count) " + $" FOR Date IN ({dates})) AS Pivoted " + $"Group By SystemName{(levels.ToUpper() != "SYSTEM" ? ", CircuitName" : "")}{(levels.ToUpper() == "DEVICE" ? ", MeterName" : "")}"; DataTable table = conn.RetrieveData(s); return(Ok(table)); } catch (Exception ex) { return(BadRequest(ex.ToString())); } } }
public IHttpActionResult CreateRecord(string modelName, [FromBody] JObject record) { // Proxy all other requests SecurityPrincipal securityPrincipal = RequestContext.Principal as SecurityPrincipal; if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null || !securityPrincipal.IsInRole("Administrator")) { return(BadRequest($"User \"{RequestContext.Principal?.Identity.Name}\" is unauthorized.")); } using (DataContext dataContext = new DataContext("systemSettings")) { try { Type type = typeof(Meter).Assembly.GetType("SOE.Model." + modelName); object obj = record.ToObject(type); dataContext.Table(typeof(Meter).Assembly.GetType("SOE.Model." + modelName)).AddNewRecord(obj); } catch (Exception ex) { return(BadRequest(ex.ToString())); } } return(Ok()); }
public IHttpActionResult GetRecords(string id, string modelName) { // Proxy all other requests SecurityPrincipal securityPrincipal = RequestContext.Principal as SecurityPrincipal; if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null || !securityPrincipal.IsInRole("Viewer,Administrator")) { return(BadRequest($"User \"{RequestContext.Principal?.Identity.Name}\" is unauthorized.")); } object record; string idList = ""; try { if (id != "all") { string[] ids = id.Split(','); if (ids.Count() > 0) { idList = $"ID IN ({ string.Join(",", ids.Select(x => int.Parse(x)))})"; } } } catch (Exception) { return(BadRequest("The id field must be a comma separated integer list.")); } using (DataContext dataContext = new DataContext("systemSettings")) { try { Type type = typeof(Meter).Assembly.GetType("SOE.Model." + modelName); if (idList.Length == 0) { record = dataContext.Table(type).QueryRecords(); } else { record = dataContext.Table(type).QueryRecordsWhere(idList); } } catch (Exception ex) { return(BadRequest(ex.ToString())); } } return(Ok(record)); }