// DELETE api/shifttemplateapi/5
        public void Delete(Guid id)
        {
            ShiftTemplate shiftTemplate = db.ShiftTemplates.Find(id);

            if (shiftTemplate != null)
            {
                if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", shiftTemplate.BusinessLocation.Id.ToString()))
                {
                    shiftTemplate.Enabled = false;

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, ex));
                    }
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
        }
        public HttpResponseMessage ApproveTimesheetEntry([FromBody] TimesheetEntryDTO timesheetEntryDTO)
        {
            if (Is <TimesheetFeature> .Enabled)
            {
                TimesheetEntry timesheetEntry = db.TimesheetEntries.Find(timesheetEntryDTO.Id);
                if (timesheetEntry == null)
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                }

                var email = HttpContext.Current.User.Identity.Name;

                UserProfile userProfile = db.UserProfiles.FirstOrDefault(usr => usr.Email == email);
                if (userProfile == null)
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                }

                //Check business rules
                if (!timesheetEntryDTO.FinishDateTime.HasValue)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Finish time for shift must be specified"));
                }

                if (timesheetEntryDTO.FinishDateTime.Value < timesheetEntryDTO.StartDateTime)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Finish time for shift must be AFTER start time"));
                }

                if (ClaimsAuthorization.CheckAccess("Put", "BusinessId", timesheetEntry.TimeCard.BusinessLocation.Business.Id.ToString()))
                {
                    timesheetEntry.Approved         = true;
                    timesheetEntry.ApprovedDateTime = WebUI.Common.Common.DateTimeNowLocal();
                    timesheetEntry.ApprovedBy       = userProfile;
                    timesheetEntry.StartDateTime    = timesheetEntryDTO.StartDateTime;
                    timesheetEntry.FinishDateTime   = timesheetEntryDTO.FinishDateTime;

                    try
                    {
                        db.Entry(timesheetEntry).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotImplemented));
            }
        }
        public HttpResponseMessage ApproveShiftChangeRequest(string id, ShiftChangeActionDTO acceptDTO)
        {
            try
            {
                var requestId = Guid.Parse(id);
                var email     = HttpContext.Current.User.Identity.Name;

                var scRequest = db.ShiftChangeRequests.FirstOrDefault(er => er.Id == requestId && er.Status == RequestStatus.Pending);

                if (scRequest == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Unable to find pending shift change request."));
                }

                //Ensure user has "Put" manager permissions for the business which the request corresponds to
                if (!ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", scRequest.Shift.Roster.BusinessLocation.Id.ToString()))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have permissions."));
                }


                //Update Request object
                scRequest.Status          = RequestStatus.Approved;
                scRequest.ActionedDate    = WebUI.Common.Common.DateTimeNowLocal();
                scRequest.ActionedComment = acceptDTO.Reason;
                //Attach the Employee record which matches the logged in user profile and business id.
                scRequest.ActionedBy = db.UserProfiles.FirstOrDefault(usr => usr.Email == email).Employees.FirstOrDefault(emp => emp.BusinessLocation.Id == scRequest.Shift.InternalLocation.BusinessLocation.Id);

                if (scRequest.Type == ShiftRequestType.Cancel)
                {
                    //Update shift to be cancelled, ie set to not have an employee assigned and become and open shift
                    scRequest.Shift.Employee.Shifts.Remove(scRequest.Shift);
                }

                //If this is an open shift Take request, then need to reject all other requests for same shift
                // and send notification
                if (scRequest.Type == ShiftRequestType.TakeOpenShift)
                {
                    scRequest.Shift.Employee = scRequest.CreatedBy; //Assign the open shift to the employee
                    foreach (var openShiftRequest in db.ShiftChangeRequests.Where(scr => scr.Shift.Id == scRequest.Shift.Id && scr.Id != scRequest.Id))
                    {
                        openShiftRequest.Status          = RequestStatus.Denied;
                        openShiftRequest.ActionedDate    = WebUI.Common.Common.DateTimeNowLocal();
                        openShiftRequest.ActionedComment = acceptDTO.Reason;
                    }

                    MessagingService.OpenShiftRequestAccept(scRequest.CreatedBy.Email, scRequest.CreatedBy.FirstName, scRequest.Shift.StartTime.ToString() + " - " + scRequest.Shift.FinishTime.ToString() + " @ " + scRequest.Shift.InternalLocation.BusinessLocation.Name);
                }

                db.SaveChanges();


                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
        public HttpResponseMessage PutShift(Guid id, ShiftDTO shiftDTO)
        {
            var businessLocId = db.Shifts.Find(id).Roster.BusinessLocation.Id;

            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", businessLocId.ToString()))
            {
                if (!ModelState.IsValid)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

                if (id != shiftDTO.Id)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Id provided does not match object."));
                }
                try
                {
                    var shift = MapperFacade.MapperConfiguration.Map <ShiftDTO, Shift>(shiftDTO, db.Shifts.Single(s => s.Id == id));

                    //If an already published shift is being edited need to send notifications for any changes to employee as a cancel notification
                    if (shift.IsPublished)
                    {
                        //Notify employee that the shift is being taken from as a cancellation
                        if (shift.Employee != null && shift.Employee.UserProfile != null && shift.Employee.Id != shiftDTO.EmployeeId)
                        {
                            MessagingService.ShiftCancelled(shift.Employee.UserProfile.Email, shift.Employee.UserProfile.FirstName, shift.InternalLocation.BusinessLocation.Name, shift.StartTime, shift.FinishTime);
                        }
                    }

                    //If the employee assigned to the shift has changed, need to notify them that they have a shift broadcast
                    var employeeAdded = (shiftDTO.EmployeeId != null && (shift.Employee == null || shift.Employee.Id != shiftDTO.EmployeeId));

                    shift.Employee = db.Employees.Find(shiftDTO.EmployeeId);

                    //Notify the employee they have been added to a published shift
                    if (shift.IsPublished && employeeAdded && shift.Employee.UserProfile != null)
                    {
                        MessagingService.ShiftBroadcast(shift.Employee.UserProfile.Email, shift.Employee.UserProfile.FirstName);
                    }

                    shift.InternalLocation = db.InternalLocations.Find(shiftDTO.InternalLocationId);
                    shift.Role             = db.Roles.Find(shiftDTO.RoleId);

                    db.Entry(shift).State = EntityState.Modified;

                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
Exemple #5
0
 protected override bool IsAuthorized(HttpActionContext actionContext)
 {
     if (!string.IsNullOrWhiteSpace(_action))
     {
         return(ClaimsAuthorization.CheckAccess(_action, _resources));
     }
     return(CheckAccess(actionContext));
 }
        public void Put(Guid id, [FromBody] ShiftTemplateDTO shiftTemplateDTO)
        {
            if (ModelState.IsValid)
            {
                if (ClaimsAuthorization.CheckAccess("Put", "BusinessId", shiftTemplateDTO.BusinessId.ToString()))
                {
                    var shiftTemplate = MapperFacade.MapperConfiguration.Map <ShiftTemplateDTO, ShiftTemplate>(shiftTemplateDTO, db.ShiftTemplates.Find(shiftTemplateDTO.Id));

                    //Business rules
                    if (shiftTemplateDTO.StartTime > shiftTemplateDTO.FinishTime && !shiftTemplateDTO.FinishNextDay)
                    {
                        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Shift start time must be before end time"));
                    }
                    //Role selected must be applicable to the Employee
                    if (shiftTemplateDTO.EmployeeId != null && shiftTemplateDTO.RoleId.HasValue && db.Employees.Find(shiftTemplateDTO.EmployeeId).Roles.FirstOrDefault(r => r.Id == shiftTemplateDTO.RoleId) == null)
                    {
                        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Employee does not have the role specified"));
                    }


                    if (shiftTemplateDTO.InternalLocationId.HasValue)
                    {
                        shiftTemplate.InternalLocation = db.InternalLocations.Find(shiftTemplateDTO.InternalLocationId);
                    }
                    else
                    {
                        db.Entry(shiftTemplate).Reference(r => r.InternalLocation).CurrentValue = null;
                    }
                    if (shiftTemplateDTO.RoleId.HasValue)
                    {
                        shiftTemplate.Role = db.Roles.Find(shiftTemplateDTO.RoleId);
                    }
                    else
                    {
                        db.Entry(shiftTemplate).Reference(r => r.Role).CurrentValue = null;
                    }
                    if (shiftTemplateDTO.EmployeeId.HasValue)
                    {
                        shiftTemplate.Employee = db.Employees.Find(shiftTemplateDTO.EmployeeId);
                    }
                    else
                    {
                        db.Entry(shiftTemplate).Reference(r => r.Employee).CurrentValue = null;
                    }

                    db.Entry(shiftTemplate).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Exemple #7
0
        protected virtual bool CheckAccess(HttpActionContext actionContext)
        {
            var action   = actionContext.ActionDescriptor.ActionName;
            var resource = actionContext.ControllerContext.ControllerDescriptor.ControllerName;

            return(ClaimsAuthorization.CheckAccess(
                       action,
                       resource));
        }
        // DELETE api/EmployeeAPI/5
        public HttpResponseMessage DeleteEmployee(Guid id)
        {
            Employee employee = db.Employees.Find(id);

            if (employee == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", employee.BusinessLocation.Id.ToString()))
            {
                employee.IsActive = false;

                //If there is a user profile login attached, then remove this so they can no longer access the business information
                if (employee.UserProfile != null)
                {
                    employee.UserProfile.Employees.Remove(employee);
                }

                //When removing and employee set any of their currently assigned shifts to be Open shifts for shifts after NOW
                DateTime dtNow  = WebUI.Common.Common.DateTimeNowLocal();
                var      shifts = db.Shifts.Where(s => s.StartTime > dtNow && s.Employee.Id == employee.Id);
                foreach (var shift in shifts)
                {
                    shift.Employee        = null;
                    db.Entry(shift).State = EntityState.Modified;
                }

                var shiftTemplates = db.ShiftTemplates.Where(st => st.Employee.Id == employee.Id);
                foreach (var shiftTemplate in shiftTemplates)
                {
                    shiftTemplate.Enabled         = false;
                    db.Entry(shiftTemplate).State = EntityState.Modified;
                }

                db.Entry(employee).State = EntityState.Modified;

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                }
                catch (Exception ex)
                {
                    var sds = ex.Message;
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
Exemple #9
0
        public HomeSummaryDTO GetSites()
        {
            HomeSummaryDTO model = new HomeSummaryDTO();
            var            email = HttpContext.Current.User.Identity.Name;

            var employee = db.Employees.FirstOrDefault(x => x.Email == email);

            if (employee != null)
            {
                model.SiteSearch = new List <DropDownDTO>();
                //if user is a manager then he can find all the businesses, Employee of there own business and can get all the external users
                if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", employee.BusinessLocation.Id.ToString()))
                {
                    //Get the exernal users which are registered for get the ExternalBroadCast Shift.
                    model.SiteSearch = db.UserProfiles.Where(x => x.Email != email && x.IsRegisteredExternal == true).Select(a => new DropDownDTO
                    {
                        Text      = a.FirstName.ToLower() + " " + a.LastName.ToLower(),
                        ValueGuid = a.Id
                    }).ToList();
                }

                //if user is an employee then he can find his co-employee and all the business
                var BusinessLocationIds = (from e in db.Employees
                                           where e.Email == email
                                           select e.BusinessLocation.Id).ToList();
                foreach (var businesslocationid in BusinessLocationIds)
                {
                    var emps = db.Employees.Where(a => a.BusinessLocation.Id == businesslocationid && a.Email != email && a.UserProfile.Id != null).Select(y => new DropDownDTO {
                        Text = y.FirstName.ToLower() + " " + y.LastName.ToLower(), ValueGuid = y.Id
                    }).ToList();
                    foreach (var emp in emps)
                    {
                        model.SiteSearch.Add(emp);
                    }
                }

                //get all businesses
                var business = db.Businesses.Select(a => new DropDownDTO {
                    Text = a.Name.ToLower(), ValueGuid = a.Id
                }).ToList();
                foreach (var item in business)
                {
                    model.SiteSearch.Add(item);
                }
            }
            //if user is a Externaluser then he can only find the all Businesses
            else
            {
                model.SiteSearch = db.Businesses.Select(a => new DropDownDTO
                {
                    Text      = a.Name.ToLower(),
                    ValueGuid = a.Id
                }).ToList();
            }
            return(model);
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Container.Current.SatisfyImportsOnce(this);

            filterContext.Controller.ViewBag.SiteName        = ConfigurationRepository.Global.SiteName;
            filterContext.Controller.ViewBag.IsAdministrator = ClaimsAuthorization.CheckAccess(Constants.Actions.Administration, Constants.Resources.UI);
            filterContext.Controller.ViewBag.IsSignedIn      = filterContext.HttpContext.User.Identity.IsAuthenticated;

            base.OnActionExecuting(filterContext);
        }
        public static bool CheckAccess(IClaimsPrincipal principal, string action, string resource, params string[] additionalResources)
        {
            var context = CreateAuthorizationContext(
                principal,
                action,
                resource,
                additionalResources);

            return(ClaimsAuthorization.CheckAccess(context));
        }
Exemple #12
0
        // POST api/shiftapi
        //Create a new shift
        public HttpResponseMessage PostRoster([FromBody] RosterCreateDTO rosterCreateDTO)
        {
            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", rosterCreateDTO.BusinessLocationId.ToString()))
            {
                if (ModelState.IsValid)
                {
                    Roster existingRoster = db.Rosters.Where(r => r.BusinessLocation.Id == rosterCreateDTO.BusinessLocationId &&
                                                             r.WeekStartDate == rosterCreateDTO.WeekStartDate.Date).FirstOrDefault();
                    //Business rules
                    if (existingRoster != null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "A roster already exists for the week starting " + rosterCreateDTO.WeekStartDate.ToShortDateString()));
                    }
                    //Cannot create a roster for a weeks starting in the past EXCEPT if it is the current week.
                    if (rosterCreateDTO.WeekStartDate.Date < WebUI.Common.Common.GetNextWeekday(WebUI.Common.Common.DateTimeNowLocal(), DayOfWeek.Monday).Date.AddDays(-7))
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "A roster cannot be created for a week starting in the past"));
                    }

                    var rosterList  = new List <Roster>();
                    var businessLoc = db.BusinessLocations.Find(rosterCreateDTO.BusinessLocationId);
                    var rosterWeek1 = CreateRosterForWeekStarting(rosterCreateDTO, businessLoc);
                    db.Rosters.Add(rosterWeek1);

                    //If rosters are being created for a month or fortnight.
                    if (rosterCreateDTO.RostersToCreate == RosterToCreateEnum.Fortnight ||
                        rosterCreateDTO.RostersToCreate == RosterToCreateEnum.Month)
                    {
                        var rosterWeek2 = CreateRosterForWeekStarting(rosterCreateDTO, businessLoc, 1);
                        db.Rosters.Add(rosterWeek2);
                        //For month, add remaining two weeks
                        if (rosterCreateDTO.RostersToCreate == RosterToCreateEnum.Month)
                        {
                            var rosterWeek3 = CreateRosterForWeekStarting(rosterCreateDTO, businessLoc, 2);
                            db.Rosters.Add(rosterWeek3);
                            var rosterWeek4 = CreateRosterForWeekStarting(rosterCreateDTO, businessLoc, 3);
                            db.Rosters.Add(rosterWeek4);
                        }
                    }

                    db.SaveChanges();

                    return(Request.CreateResponse(HttpStatusCode.Created));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have appropriate permission"));
            }
        }
Exemple #13
0
        // http://localhost:1096/api/customers/1
        public string Get(int id)
        {
            var allowed = ClaimsAuthorization.CheckAccess("Get", "Customer", id.ToString());

            if (allowed)
            {
                return("OK " + id.ToString());
            }

            return("NOK");
        }
        public HttpResponseMessage PostShiftTemplate(ShiftTemplateDTO shiftTemplateDTO)
        {
            if (ModelState.IsValid)
            {
                if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", shiftTemplateDTO.BusinessLocationId.ToString()))
                {
                    //Business rules
                    if (shiftTemplateDTO.StartTime > shiftTemplateDTO.FinishTime && !shiftTemplateDTO.FinishNextDay)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Shift start time must be before end time"));
                    }
                    //Role selected must be applicable to the Employee
                    if (shiftTemplateDTO.EmployeeId != null && shiftTemplateDTO.RoleId.HasValue && db.Employees.Find(shiftTemplateDTO.EmployeeId).Roles.FirstOrDefault(r => r.Id == shiftTemplateDTO.RoleId) == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Employee does not have the role specified"));
                    }

                    var shiftTemplate = MapperFacade.MapperConfiguration.Map <ShiftTemplateDTO, ShiftTemplate>(shiftTemplateDTO);
                    shiftTemplate.Id = Guid.NewGuid(); //Assign new ID on save.

                    shiftTemplate.Enabled = true;      //default to enabled

                    shiftTemplate.BusinessLocation = db.BusinessLocations.Find(shiftTemplateDTO.BusinessLocationId);
                    if (shiftTemplateDTO.InternalLocationId.HasValue)
                    {
                        shiftTemplate.InternalLocation = db.InternalLocations.Find(shiftTemplateDTO.InternalLocationId);
                    }
                    if (shiftTemplateDTO.RoleId.HasValue)
                    {
                        shiftTemplate.Role = db.Roles.Find(shiftTemplateDTO.RoleId);
                    }
                    if (shiftTemplateDTO.EmployeeId.HasValue)
                    {
                        shiftTemplate.Employee = db.Employees.Find(shiftTemplateDTO.EmployeeId);
                    }

                    db.ShiftTemplates.Add(shiftTemplate);
                    db.SaveChanges();

                    shiftTemplateDTO = MapperFacade.MapperConfiguration.Map <ShiftTemplate, ShiftTemplateDTO>(shiftTemplate);
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, shiftTemplateDTO);
                    response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = shiftTemplateDTO.Id }));
                    return(response);
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Exemple #15
0
 protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
 {
     if (!string.IsNullOrWhiteSpace(_action))
     {
         return(ClaimsAuthorization.CheckAccess(_action, _resources));
     }
     else
     {
         var filterContext = httpContext.Items[_label] as System.Web.Mvc.AuthorizationContext;
         return(CheckAccess(filterContext));
     }
 }
 public IEnumerable <EmployeeDTO> GetEmployees(Guid businessLocationid)
 {
     if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", businessLocationid.ToString()))
     {
         //Get all active employees for a given businessid
         return(MapperFacade.MapperConfiguration.Map <IEnumerable <Employee>, IEnumerable <EmployeeDTO> >(db.Employees.Where(e => e.BusinessLocation.Id == businessLocationid && e.IsActive).AsEnumerable()));
     }
     else
     {
         throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have appropriate permission"));
     }
 }
        public HttpResponseMessage ApproveEmployerRequest(string id)
        {
            try
            {
                var requestId = Guid.Parse(id);
                var email     = HttpContext.Current.User.Identity.Name;

                //Create Employee under business
                var empRequest = db.EmployerRequests.FirstOrDefault(er => er.Id == requestId && er.Status == RequestStatus.Pending);

                //Ensure user has "Put" manager permissions for the business which the request corresponds to
                if (!ClaimsAuthorization.CheckAccess("Put", "BusinessId", empRequest.BusinessLocation.Business.Id.ToString()))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have permissions."));
                }

                if (empRequest == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Unable to find pending request."));
                }

                //Create new Employee object
                Employee employee = new Employee();
                employee.Id = Guid.NewGuid(); //Assign new ID on save.

                //Copy details from UserProfile
                employee.Email       = empRequest.UserProfile.Email;
                employee.FirstName   = empRequest.UserProfile.FirstName;
                employee.LastName    = empRequest.UserProfile.LastName;
                employee.MobilePhone = empRequest.UserProfile.MobilePhone;
                employee.Type        = EmployeeType.Casual; //Default to Casual employee type

                employee.UserProfile      = empRequest.UserProfile;
                employee.BusinessLocation = empRequest.BusinessLocation;

                db.Employees.Add(employee);

                //Update Request object
                empRequest.Employee     = employee;
                empRequest.Status       = RequestStatus.Approved;
                empRequest.ActionedDate = WebUI.Common.Common.DateTimeNowLocal();
                //Attach the EMployee record which matches the logged in user profile and business id.
                empRequest.ActionedBy = db.UserProfiles.FirstOrDefault(usr => usr.Email == email).Employees.FirstOrDefault(emp => emp.BusinessLocation.Id == empRequest.BusinessLocation.Id);

                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Exemple #18
0
        public HttpResponseMessage PutBusiness(Guid id, BusinessDetailsDTO businessDTO)
        {
            if (ClaimsAuthorization.CheckAccess("Put", "BusinessId", id.ToString()))
            {
                if (!ModelState.IsValid)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

                if (id != businessDTO.Id)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }

                try
                {
                    var business = MapperFacade.MapperConfiguration.Map <BusinessDetailsDTO, Business>(businessDTO, db.Businesses.Single(b => b.Id == id));

                    //Lookup BusinessType and attach, so that no updates or inserts are performed on BusinessType lookup table
                    business.Type = db.BusinessTypes.Single(t => t.Id == businessDTO.TypeId);

                    ////Apply any role updates or inserts
                    //foreach (RoleDTO roleDTO in businessDTO.Roles)
                    //{
                    //    Role role = business.Roles.FirstOrDefault(r => r.Id == roleDTO.Id);
                    //    //If there is a role, then need to update
                    //    if (role != null)
                    //        role.Name = roleDTO.Name;
                    //    else //This is a new role being added
                    //    {
                    //        var newRole = MapperFacade.MapperConfiguration.Map<RoleDTO, Role>(roleDTO);
                    //        newRole.Id = Guid.NewGuid();
                    //        business.Roles.Add(newRole);
                    //    } //Note: deletion of roles is not supported here
                    //}

                    db.Entry(business).State = EntityState.Modified;

                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
Exemple #19
0
        // POST: api/FileImportAPI
        public LogFileDTO PostFile(FileImportDTO filedto)
        {
            if (ModelState.IsValid)
            {
                if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", filedto.BusinessLocationId.ToString()))
                {
                    MemoryStream stream = new MemoryStream(filedto.FileUpload);

                    if (filedto.DataType == UploadTypesDTO.Employees)
                    {
                        Tuple <List <EmployeeDTO>, LogFileDTO> result = ValidateCSV(stream, filedto.BusinessLocationId);

                        if (result.Item2.ErrorLines == 0)
                        {
                            foreach (EmployeeDTO employeeDTO in result.Item1)
                            {
                                employeeDTO.BusinessId         = filedto.BusinessId;
                                employeeDTO.BusinessLocationId = filedto.BusinessLocationId;

                                using (var employeeAPIController = new EmployeeAPIController())
                                {
                                    employeeAPIController.CreateNewEmployee(employeeDTO, true);
                                }

                                result.Item2.LoadedSuccesfully++;
                            }
                        }
                        return(result.Item2);
                    }
                    else if (filedto.DataType == UploadTypesDTO.Roles)
                    {
                        throw new NotImplementedException();
                    }
                    else
                    {
                        return(new LogFileDTO
                        {
                            Status = "Failed",
                            LinesRead = 0
                        });
                    }
                }
                else
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have appropriate permission"));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
        public ActionResult About()
        {
            if (ClaimsAuthorization.CheckAccess("Show", "Code"))
            {
                ViewBag.Message = "This is the secret code.";
            }
            else
            {
                ViewBag.Message = "Too bad.";
            }

            return(View());
        }
Exemple #21
0
        public IEnumerable <BusinessLocationDTO> GetBusinessLocations(Guid businessid)
        {
            if (ClaimsAuthorization.CheckAccess("Get", "BusinessId", businessid.ToString()))
            {
                var businessLocations = db.BusinessLocations.Where(sb => sb.Business.Id == businessid);

                return(MapperFacade.MapperConfiguration.Map <IEnumerable <BusinessLocation>, IEnumerable <BusinessLocationDTO> >(businessLocations.AsEnumerable()));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
        public void AddTokenDetails([FromBody] PaymentDetailsDTO paymentDetailsDTO)
        {
            if (Is <PaymentFeature> .Enabled)
            {
                var employee = db.Employees.Find(paymentDetailsDTO.EmployeeID);
                if (employee != null)
                {
                    if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", employee.BusinessLocation.Id.ToString()))
                    {
                        var paymentdetails = new PaymentDetails
                        {
                            Id = Guid.NewGuid()
                        };

                        if (employee.PaymentDetails != null)
                        {
                            paymentdetails = employee.PaymentDetails;
                        }

                        paymentdetails.TokenCustomerID  = paymentDetailsDTO.TokenCustomerID;
                        paymentdetails.BusinessLocation = employee.BusinessLocation;
                        paymentdetails.CreatedDate      = WebUI.Common.Common.DateTimeNowLocal();

                        //If there is another payment detail from a different employee then delete
                        if (employee.BusinessLocation.PaymentDetails != null &&
                            employee.BusinessLocation.PaymentDetails.Employee.Id != employee.Id)
                        {
                            //employee.BusinessLocation.PaymentDetails.
                            db.Entry(employee.BusinessLocation.PaymentDetails).State = EntityState.Deleted;
                        }

                        employee.PaymentDetails = paymentdetails;

                        db.SaveChanges();
                    }
                    else
                    {
                        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                    }
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotImplemented));
            }
        }
        public HttpResponseMessage CancelRecurringShiftInstance(Guid Id, RecurringShiftChangeActionDTO shiftCancelDTO)
        {
            var shift = db.ShiftTemplates.Find(Id);

            if (shift == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Recurring shift not found"));
            }

            //Only the staff member assigned to the shift can request to cancel the shift
            if (ClaimsAuthorization.CheckAccess("Get", "BusinessId", shift.BusinessLocation.Business.Id.ToString()) ||
                shift.Employee.UserProfile.Email != User.Identity.Name)
            {
                if (shiftCancelDTO.Reason == String.Empty)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Reason cannot be blank"));
                }

                //Check to see if there is already a pending cancellation request
                var shiftCancelRequest = db.RecurringShiftChangeRequests.Where(sc => sc.Type == ShiftRequestType.Cancel &&
                                                                               sc.ShiftTemplate.Id == Id &&
                                                                               sc.Status == RequestStatus.Pending &&
                                                                               sc.OccurenceDate == shiftCancelDTO.OccurenceDate);
                if (shiftCancelRequest.Count() > 0)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Existing cancellation request already pending for recurring shift"));
                }

                RecurringShiftChangeRequest shiftChangeRequest = new RecurringShiftChangeRequest
                {
                    Id            = Guid.NewGuid(),
                    Reason        = shiftCancelDTO.Reason,
                    ShiftTemplate = shift,
                    Type          = ShiftRequestType.Cancel,
                    OccurenceDate = shiftCancelDTO.OccurenceDate,
                    Status        = RequestStatus.Pending,
                    CreatedDate   = WebUI.Common.Common.DateTimeNowLocal()
                };

                db.RecurringShiftChangeRequests.Add(shiftChangeRequest);
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.Created, shiftChangeRequest.Id));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
        public async Task <IHttpActionResult> DeleteBreweryMember(int id, string username)
        {
            var isAllowed = ClaimsAuthorization.CheckAccess("Delete", "BreweryId", id.ToString());

            if (!isAllowed)
            {
                return(StatusCode(HttpStatusCode.Unauthorized));
            }
            var breweryMember = await _breweryService.DeleteMember(id, username);

            if (breweryMember == null)
            {
                return(NotFound());
            }
            return(Ok(breweryMember));
        }
        //Get a roster with Shifts for one day of the week
        public IEnumerable <ShiftDTO> GetShiftsForDay(Guid businessLocationId, DateTime date)
        {
            DateTime eDate = date.AddDays(1);

            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", businessLocationId.ToString()))
            {
                var shiftList = db.Shifts.Where(s => s.Roster.BusinessLocation.Id == businessLocationId &&
                                                s.StartTime >= date && s.StartTime < eDate);
                var shiftDTOList = MapperFacade.MapperConfiguration.Map <IEnumerable <Shift>, IEnumerable <ShiftDTO> >(shiftList);
                return(shiftDTOList);
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
        public async Task <IHttpActionResult> PostBreweryMember(int id, BreweryMemberDto breweryMember)
        {
            var isAllowed = ClaimsAuthorization.CheckAccess("Post", "BreweryId", id.ToString());

            if (!isAllowed)
            {
                return(StatusCode(HttpStatusCode.Unauthorized));
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var result = await _breweryService.AddBreweryMember(id, breweryMember);

            return(Ok(result));
        }
        public async Task <IHttpActionResult> DeleteBeer(int id)
        {
            var isAllowed = ClaimsAuthorization.CheckAccess("Delete", "BeerId", id.ToString());

            if (!isAllowed)
            {
                return(StatusCode(HttpStatusCode.Unauthorized));
            }
            var beerDto = await _beerService.DeleteAsync(id);

            if (beerDto == null)
            {
                return(NotFound());
            }
            return(Ok(beerDto));
        }
        public async Task <IHttpActionResult> DeleteBrewery(int id)
        {
            var isAllowed = ClaimsAuthorization.CheckAccess("Post", "BreweryId", id.ToString());

            if (!isAllowed)
            {
                return(StatusCode(HttpStatusCode.Unauthorized));
            }
            var brewery = await _breweryService.DeleteAsync(id);

            if (brewery == null)
            {
                return(NotFound());
            }
            return(Ok(brewery));
        }
        public HttpResponseMessage RequestOpenShift(Guid Id, ShiftChangeActionDTO shiftRequestDTO)
        {
            var shift = db.Shifts.Find(Id);

            if (shift == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Shift not found"));
            }

            //Only the staff member assigned to the shift can request to cancel the shift
            if (ClaimsAuthorization.CheckAccess("Get", "BusinessId", shift.Roster.BusinessLocation.Business.Id.ToString()))
            {
                var email = HttpContext.Current.User.Identity.Name;

                var employee = db.Employees.First(emp => emp.UserProfile.Email == email && emp.BusinessLocation.Id == shift.Roster.BusinessLocation.Id);

                //Check to see if there is already a pending shift request
                var shiftRequest = db.ShiftChangeRequests.Where(sc => sc.Type == ShiftRequestType.TakeOpenShift &&
                                                                sc.Shift.Id == Id &&
                                                                sc.Status == RequestStatus.Pending &&
                                                                sc.CreatedBy.Id == employee.Id);
                if (shiftRequest.Count() > 0)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Existing request already pending for shift id:" + Id.ToString()));
                }

                ShiftChangeRequest shiftChangeRequest = new ShiftChangeRequest
                {
                    Id          = Guid.NewGuid(),
                    Shift       = shift,
                    Type        = ShiftRequestType.TakeOpenShift,
                    Status      = RequestStatus.Pending,
                    Reason      = shiftRequestDTO.Reason,
                    CreatedDate = WebUI.Common.Common.DateTimeNowLocal(),
                    CreatedBy   = employee
                };

                db.ShiftChangeRequests.Add(shiftChangeRequest);
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.Created, shiftChangeRequest.Id));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
Exemple #30
0
        private HttpResponseMessage ProcessResourceOwnerCredentialRequest(string userName, string password, EndpointReference appliesTo, string tokenType, Client client)
        {
            Tracing.Information("Starting resource owner password credential flow for client: " + client.Name);

            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                Tracing.Error("Invalid resource owner credentials for: " + appliesTo.Uri.AbsoluteUri);
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant));
            }

            var             auth = new AuthenticationHelper();
            ClaimsPrincipal principal;

            if (UserRepository.ValidateUser(userName, password))
            {
                principal = auth.CreatePrincipal(userName, "OAuth2",
                                                 new Claim[]
                {
                    new Claim(Constants.Claims.Client, client.Name),
                    new Claim(Constants.Claims.Scope, appliesTo.Uri.AbsoluteUri)
                });

                if (!ClaimsAuthorization.CheckAccess(principal, Constants.Actions.Issue, Constants.Resources.OAuth2))
                {
                    Tracing.Error("OAuth2 endpoint authorization failed for user: "******"Resource owner credential validation failed: " + userName);
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant));
            }

            var           sts = new STS();
            TokenResponse tokenResponse;

            if (sts.TryIssueToken(appliesTo, principal, tokenType, out tokenResponse))
            {
                var resp = Request.CreateResponse <TokenResponse>(HttpStatusCode.OK, tokenResponse);
                return(resp);
            }
            else
            {
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidRequest));
            }
        }