public async Task <Response <WeekPictogramDTO> > ReadPictogram(long id) { try { //Fetch the pictogram and check that it actually exists var pictogram = await _giraf._context.Pictograms .Where(p => p.Id == id) .FirstOrDefaultAsync(); if (pictogram == null) { return(new ErrorResponse <WeekPictogramDTO>(ErrorCode.PictogramNotFound)); } //Check if the pictogram is public and return it if so if (pictogram.AccessLevel == AccessLevel.PUBLIC) { return(new Response <WeekPictogramDTO>(new WeekPictogramDTO(pictogram))); } var usr = await _giraf.LoadBasicUserDataAsync(HttpContext.User); if (usr == null) { return(new ErrorResponse <WeekPictogramDTO>(ErrorCode.UserNotFound)); } var ownsResource = false; if (pictogram.AccessLevel == AccessLevel.PRIVATE) { ownsResource = await _giraf.CheckPrivateOwnership(pictogram, usr); } else if (pictogram.AccessLevel == AccessLevel.PROTECTED) { ownsResource = await _giraf.CheckProtectedOwnership(pictogram, usr); } if (ownsResource) { return(new Response <WeekPictogramDTO>(new WeekPictogramDTO(pictogram))); } else { return(new ErrorResponse <WeekPictogramDTO>(ErrorCode.NotAuthorized)); } } catch (Exception e) { var exceptionMessage = $"Exception occured in read:\n{e}"; _giraf._logger.LogError(exceptionMessage); return(new ErrorResponse <WeekPictogramDTO>(ErrorCode.Error)); } }
public async Task <Response <DepartmentDTO> > RemoveResource(long resourceId) { //Fetch the department and check that it exists. var usr = await _giraf.LoadUserWithResources(HttpContext.User); //Fetch the department and check that it exists. No need to fetch dep ressources they are already on user var department = await _giraf._context.Departments.Where(d => d.Key == usr.DepartmentKey) .Include(d => d.Members) .FirstOrDefaultAsync(); if (department == null) { return(new ErrorResponse <DepartmentDTO>(ErrorCode.DepartmentNotFound)); } //Fetch the resource with the given id, check that it exists. var resource = await _giraf._context.Pictograms .Where(f => f.Id == resourceId) .FirstOrDefaultAsync(); if (resource == null) { return(new ErrorResponse <DepartmentDTO>(ErrorCode.ResourceNotFound)); } var resourceOwned = await _giraf.CheckProtectedOwnership(resource, usr); if (!resourceOwned) { return(new ErrorResponse <DepartmentDTO>(ErrorCode.NotAuthorized)); } //Check if the department already owns the resource and remove if so. var drrelation = await _giraf._context.DepartmentResources .Where(dr => dr.PictogramKey == resource.Id && dr.OtherKey == department.Key) .FirstOrDefaultAsync(); if (drrelation == null) { return(new ErrorResponse <DepartmentDTO>(ErrorCode.ResourceNotOwnedByDepartment)); } usr.Department.Resources.Remove(drrelation); await _giraf._context.SaveChangesAsync(); //Return Ok and the department - the resource is now visible in deparment.Resources var members = DepartmentDTO.FindMembers(department.Members, _roleManager, _giraf); return(new Response <DepartmentDTO>(new DepartmentDTO(usr.Department, members))); }