示例#1
0
 public PaymentDetailsDTO GetPaymentDetails(Guid businesslocationid)
 {
     if (Is <PaymentFeature> .Enabled)
     {
         var busLocation = db.BusinessLocations.Find(businesslocationid);
         if (busLocation != null)
         {
             if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", busLocation.Id.ToString()))
             {
                 return(MapperFacade.MapperConfiguration.Map <PaymentDetails, PaymentDetailsDTO>(busLocation.PaymentDetails));
             }
             else
             {
                 throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
             }
         }
         else
         {
             throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
         }
     }
     else
     {
         throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotImplemented));
     }
 }
示例#2
0
        public HttpResponseMessage DisableInternalLocation(Guid Id)
        {
            try
            {
                //Find the internal location
                var internalLoc = db.InternalLocations.Find(Id);

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

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

                internalLoc.Enabled = false;
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
示例#3
0
        public HttpResponseMessage EnableRole(Guid Id)
        {
            try
            {
                //Find the Role
                var role = db.Roles.Find(Id);

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

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

                role.Enabled = true;
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
示例#4
0
        public HttpResponseMessage PostinternalLocation(Guid businesslocationId, Guid internalLocationId, InternalLocationDTO internalLocationDTO)
        {
            BusinessLocation businessLocation = db.BusinessLocations.Find(businesslocationId);

            if (businessLocation == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", businessLocation.Id.ToString()))
            {
                if (ModelState.IsValid)
                {
                    var location = MapperFacade.MapperConfiguration.Map <InternalLocationDTO, InternalLocation>(internalLocationDTO);
                    location.Id      = Guid.NewGuid(); //Assign new ID on save.
                    location.Enabled = true;

                    //Lookup Business and attach, so that no updates or inserts are performed on BusinessType lookup table
                    location.BusinessLocation = db.BusinessLocations.SingleOrDefault(b => b.Id == businesslocationId);

                    db.InternalLocations.Add(location);
                    db.SaveChanges();

                    return(Request.CreateResponse(HttpStatusCode.Created));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
        public TimesheetEntryDTO GetTimesheetEntry(Guid id)
        {
            if (Is <TimesheetFeature> .Enabled)
            {
                TimesheetEntry timesheetEntry = db.TimesheetEntries.Find(id);
                if (timesheetEntry == null)
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                }

                if (ClaimsAuthorization.CheckAccess("Put", "BusinessId", timesheetEntry.TimeCard.BusinessLocation.Business.Id.ToString()))
                {
                    var timesheetEntryDTO = MapperFacade.MapperConfiguration.Map <TimesheetEntry, TimesheetEntryDTO>(timesheetEntry);
                    timesheetEntryDTO.PayRate = timesheetEntry.TimeCard.Employee.PayRate.GetValueOrDefault();

                    var timeSpan = timesheetEntry.FinishDateTime - timesheetEntry.StartDateTime;
                    if (timeSpan.HasValue)
                    {
                        timesheetEntryDTO.Pay = (decimal)timeSpan.Value.TotalHours * timesheetEntryDTO.PayRate;
                    }

                    return(timesheetEntryDTO);
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotImplemented));
            }
        }
        public HttpResponseMessage CancelShift(Guid Id, ShiftChangeActionDTO shiftCancelDTO)
        {
            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()) ||
                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.ShiftChangeRequests.Where(sc => sc.Type == ShiftRequestType.Cancel &&
                                                                      sc.Shift.Id == Id &&
                                                                      sc.Status == RequestStatus.Pending);
                if (shiftCancelRequest.Count() > 0)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Existing cancellation request already for shift id:" + Id.ToString()));
                }

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

                //Get all managers for this busiess location
                var managers = db.Employees.Where(m => m.IsAdmin == true && m.BusinessLocation.Id == shift.Roster.BusinessLocation.Id);
                foreach (var mgr in managers)
                {
                    if (mgr.UserProfile != null)
                    {
                        //Send notifications to managers of the affected business location information that the employee has requested to cancel a shift
                        MessagingService.ShiftCancelRequest(mgr.UserProfile.Email, mgr.UserProfile.FirstName, shift.Employee.UserProfile.FirstName + ' ' + shift.Employee.UserProfile.LastName, shift.InternalLocation.BusinessLocation.Name, shift.StartTime, shift.FinishTime);
                    }
                }


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

                return(Request.CreateResponse(HttpStatusCode.Created, shiftChangeRequest.Id));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
        private HttpResponseMessage CreateTokenResponse(string userName, Client client, EndpointReference scope,
                                                        string tokenType, bool includeRefreshToken)
        {
            var auth = new AuthenticationHelper();

            var principal = auth.CreatePrincipal(userName, "OAuth2",
                                                 new[]
            {
                new Claim(Constants.Claims.Client, client.Name),
                new Claim(Constants.Claims.Scope, scope.Uri.AbsoluteUri)
            });

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

            var           sts = new STS();
            TokenResponse tokenResponse;

            if (sts.TryIssueToken(scope, principal, tokenType, out tokenResponse))
            {
                if (includeRefreshToken)
                {
                    tokenResponse.RefreshToken = CodeTokenRepository.AddCode(CodeTokenType.RefreshTokenIdentifier,
                                                                             client.ID, userName, scope.Uri.AbsoluteUri);
                }

                var resp = Request.CreateResponse(HttpStatusCode.OK, tokenResponse);
                return(resp);
            }
            return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidRequest));
        }
示例#8
0
        public async Task <IHttpActionResult> ReSendConfirmationMail(string username)
        {
            Log.Debug("Auth");
            var isAllowed = ClaimsAuthorization.CheckAccess("Resend", "User", username);

            if (!isAllowed)
            {
                return(StatusCode(HttpStatusCode.Unauthorized));
            }
            var dbUser = await _repo.FindByNameAsync(username);

            if (dbUser != null)
            {
                var code = await _repo.GenerateEmailConfirmationTokenAsync(dbUser.Id);

                var callbackUrl = string.Format("{0}/account/confirm?userid={1}&code={2}", MailService, HttpUtility.UrlEncode(dbUser.Id),
                                                HttpUtility.UrlEncode(code));

                try
                {
                    await _repo.SendEmailAsync(dbUser.Id,
                                               "Confirm your account",
                                               "Please confirm your account by clicking this link: <a href=\""
                                               + callbackUrl + "\">link</a>");
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
                return(Ok());
            }
            return(BadRequest());
        }
示例#9
0
        // GET api/rosterapi?businessId=1231232&startDate=12312&endDate=1232132
        public IEnumerable <RosterDTO> GetRostersForBusiness(Guid businessLocationId, string startDate, string endDate)
        {
            DateTime         sDate            = DateTime.Parse(startDate);
            DateTime         eDate            = DateTime.Parse(endDate);
            BusinessLocation businessLocation = db.BusinessLocations.Find(businessLocationId);

            if (businessLocation == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            if (ClaimsAuthorization.CheckAccess("Get", "BusinessId", businessLocation.Business.Id.ToString()))
            {
                var rosterList = db.Rosters.Where(r => r.BusinessLocation.Id == businessLocationId && r.WeekStartDate >= sDate && r.WeekStartDate <= eDate);

                if (rosterList == null)
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                }

                return(MapperFacade.MapperConfiguration.Map <IEnumerable <Roster>, IEnumerable <RosterDTO> >(rosterList.AsEnumerable()));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
示例#10
0
        public async Task <IHttpActionResult> PutUser(string username, UserPutDto userPutDto)
        {
            var isAllowed = ClaimsAuthorization.CheckAccess("Put", "User", username);

            if (!isAllowed)
            {
                return(StatusCode(HttpStatusCode.Unauthorized));
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!username.Equals(userPutDto.Username))
            {
                return(BadRequest());
            }
            var userModel = Mapper.Map <UserPutDto, UserModel>(userPutDto);
            var result    = await _repo.UpdateUser(userModel);

            if (result.Succeeded)
            {
                var user = Mapper.Map <UserPutDto, UserDto>(userPutDto);
                await _userService.UpdateAsync(user);
            }
            IHttpActionResult errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return(errorResult);
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
示例#11
0
        // DELETE api/<controller>/5
        public void Delete(Guid id)
        {
            if (Is <ShiftBlockFeature> .Enabled)
            {
                ShiftBlock shiftBlock = db.ShiftBlocks.Find(id);
                if (shiftBlock != null)
                {
                    if (ClaimsAuthorization.CheckAccess("Put", "BusinessId", shiftBlock.BusinessLocation.Business.Id.ToString()))
                    {
                        db.ShiftBlocks.Remove(shiftBlock);

                        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));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotImplemented));
            }
        }
        public HttpResponseMessage Put(Guid id, BusinessPreferencesDTO businessPrefDTO)
        {
            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", businessPrefDTO.BusinessLocationId.ToString()))
            {
                if (!ModelState.IsValid)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

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

                try
                {
                    var businessPreferences = MapperFacade.MapperConfiguration.Map <BusinessPreferencesDTO, BusinessPreferences>(businessPrefDTO, db.BusinessPreferences.Find(businessPrefDTO.Id));

                    db.Entry(businessPreferences).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));
            }
        }
示例#13
0
        public IEnumerable <ShiftDTO> GetConflictingShifts(Guid rosterId, DayOfWeek day)
        {
            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", db.Rosters.Find(rosterId).BusinessLocation.Id.ToString()))
            {
                List <ShiftDTO> conflictingShifts = new List <ShiftDTO>();

                int dow       = (int)day + 1; // SQL Day of week
                var conflicts = (from s1 in db.Shifts
                                 from s2 in db.Shifts
                                 where  s1.Id != s2.Id &&
                                 s1.Employee == s2.Employee &&
                                 s1.Roster.Id == rosterId &&
                                 s2.Roster.Id == rosterId &&
                                 SqlFunctions.DatePart("weekday", s1.StartTime) == dow &&
                                 SqlFunctions.DatePart("weekday", s2.StartTime) == dow &&
                                 s1.StartTime <= s2.FinishTime &&
                                 s1.FinishTime >= s2.FinishTime &&
                                 s1.IsPublished == false &&
                                 s1.Employee != null
                                 select s1);
                var conflictingShiftsForDay = MapperFacade.MapperConfiguration.Map <IEnumerable <Shift>, IEnumerable <ShiftDTO> >(conflicts);

                return(conflictingShiftsForDay);
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
        // 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));
            }
        }
示例#15
0
        //public IEnumerable<ShiftDTO> CheckUnassignedShifts([FromUri]Guid id, [FromBody]IEnumerable<RosterBroadcastDTO> shiftsToCheckForUnassigned)
        public IEnumerable <ShiftDTO> GetUnassignedShifts(Guid rosterId, Guid locationId, DayOfWeek day)
        {
            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", db.Rosters.Find(rosterId).BusinessLocation.Id.ToString()))
            {
                List <ShiftDTO> unassignedShifts = new List <ShiftDTO>();

                //if (shiftsToCheckForUnassigned.Count() > 0)
                //{
                //foreach (RosterBroadcastDTO rosterBroadcastDTO in shiftsToCheckForUnassigned)
                //{
                //int dow = (int)rosterBroadcastDTO.Day + 1; // SQL Day of week
                int dow = (int)day + 1;         // SQL Day of week

                //Find all shifts on given day for location where there is no assigned employee
                var unassignedShiftsForDay = MapperFacade.MapperConfiguration.Map <IEnumerable <Shift>, IEnumerable <ShiftDTO> >(db.Shifts.Where(s => s.Roster.Id == rosterId &&
                                                                                                                                                 s.InternalLocation.Id == locationId &&
                                                                                                                                                 s.Employee == null &&
                                                                                                                                                 s.IsPublished == false &&
                                                                                                                                                 SqlFunctions.DatePart("weekday", s.StartTime) == dow).AsEnumerable());

                return(unassignedShiftsForDay);
                // unassignedShifts.AddRange(unassignedShiftsForDay);

                //}
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
示例#16
0
        public Identity GetIdentity()
        {
            "\n\nRequest message:".ConsoleYellow();
            Console.WriteLine(OperationContext.Current.RequestContext.RequestMessage.ToString());

            var principal = ClaimsPrincipal.Current;

            var result = ClaimsAuthorization.CheckAccess(
                "Read",
                "Claims",
                "IdentityType",
                "PrincipalType");

            var id = new Identity
            {
                PrincipalType = principal.GetType().FullName,
                IdentityType  = principal.Identity.GetType().FullName,

                Claims = new List <ClaimDto>(
                    from claim in principal.Claims
                    select new ClaimDto
                {
                    Type           = claim.Type,
                    Value          = claim.Value,
                    Issuer         = claim.Issuer,
                    OriginalIssuer = claim.OriginalIssuer,
                })
            };

            return(id);
        }
        public IEnumerable <string> GetWorkingWithDetails(Guid Id)
        {
            var shift = db.Shifts.Find(Id);

            if (shift == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            if (ClaimsAuthorization.CheckAccess("Get", "BusinessId", shift.Roster.BusinessLocation.Business.Id.ToString()))
            {
                List <string> workingWithList = new List <string>();

                //Get all other shifts which overlap and are at the same internal location
                var nameList = db.Shifts.Where(s => s.Roster.BusinessLocation.Id == shift.Roster.BusinessLocation.Id &&
                                               s.InternalLocation.Id == shift.InternalLocation.Id &&
                                               s.Id != Id &&
                                               ((s.StartTime >= shift.StartTime && s.StartTime < shift.FinishTime) || //Start time overlaps
                                                (s.FinishTime > shift.StartTime && s.FinishTime <= shift.FinishTime) ||     //end time overlaps
                                                (s.FinishTime >= shift.FinishTime && s.StartTime <= shift.StartTime)))        //Start time and end time bother greater (ie shift is bigger than compareing shift)
                               .Select(s => (!String.IsNullOrEmpty(s.Employee.FirstName) && !String.IsNullOrEmpty(s.Employee.LastName)) ? (s.Employee.FirstName + " " + s.Employee.LastName) : "Open Shift").ToList();

                var nn = nameList.ToList <string>();

                return(nameList.ToList());
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
        public IEnumerable <EmployeeSummaryDTO> GetBusinessLocationManagerDetails(Guid Id)
        {
            var busLoc = db.BusinessLocations.Find(Id);

            if (busLoc == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            if (ClaimsAuthorization.CheckAccess("Get", "BusinessId", busLoc.Business.Id.ToString()))
            {
                List <EmployeeSummaryDTO> managerList = new List <EmployeeSummaryDTO>();

                //Get all other shifts which overlap and are at the same internal location
                var mgrList = db.Employees.Where(e => e.BusinessLocation.Id == Id &&
                                                 e.ManagerBusinessLocations.Any(bl => bl.Id == Id));

                //TODO: if a userprofile exists for mgr then the details in the profile should overwrite the employee table
                return(MapperFacade.MapperConfiguration.Map <IEnumerable <Employee>, IEnumerable <EmployeeSummaryDTO> >(mgrList.AsEnumerable()));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
示例#19
0
        public IEnumerable <ShiftBlockDTO> GetShiftBlocks(Guid businesslocationid)
        {
            if (Is <ShiftBlockFeature> .Enabled)
            {
                var busLocation = db.BusinessLocations.Find(businesslocationid);
                if (busLocation != null)
                {
                    if (ClaimsAuthorization.CheckAccess("Get", "BusinessId", busLocation.Business.Id.ToString()))
                    {
                        var shiftBlockList = db.ShiftBlocks.Where(sb => sb.BusinessLocation.Id == businesslocationid);

                        return(MapperFacade.MapperConfiguration.Map <IEnumerable <ShiftBlock>, IEnumerable <ShiftBlockDTO> >(shiftBlockList.AsEnumerable()));
                    }
                    else
                    {
                        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                    }
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotImplemented));
            }
        }
        /// <summary>
        /// Checks the access.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        /// <returns></returns>
        protected virtual bool CheckAccess(HttpActionContext actionContext)
        {
            var action   = actionContext.ActionDescriptor.ActionName;
            var resource = actionContext.ControllerContext.ControllerDescriptor.ControllerName;

            return(ClaimsAuthorization.CheckAccess(action, resource));
        }
示例#21
0
        protected virtual bool CheckAccess(System.Web.Mvc.AuthorizationContext filterContext)
        {
            var action     = filterContext.RouteData.Values["action"] as string;
            var controller = filterContext.RouteData.Values["controller"] as string;

            return(ClaimsAuthorization.CheckAccess(action, controller));
        }
        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));
            }
        }
示例#23
0
        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));
            }
        }
示例#24
0
        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));
            }
        }
示例#25
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));
            }
        }
示例#27
0
        // 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));
            }
        }
示例#28
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));
        }