Exemplo n.º 1
0
        public async Task <Response <DepartmentDTO> > Get(long id)
        {
            var currentUser = await _giraf._userManager.GetUserAsync(HttpContext.User);

            if (currentUser == null)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.UserNotFound));
            }

            var isSuperUser = await _giraf._userManager.IsInRoleAsync(currentUser, GirafRole.SuperUser);

            if (currentUser?.DepartmentKey != id && !isSuperUser)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.NotAuthorized));
            }

            //.Include is used to get information on members aswell when getting the Department
            var department = _giraf._context.Departments
                             .Where(dep => dep.Key == id);

            var depa = await department
                       .Include(dep => dep.Members)
                       .Include(dep => dep.Resources)
                       .FirstOrDefaultAsync();

            if (depa == null)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.NotFound));
            }

            var members = DepartmentDTO.FindMembers(depa.Members, _roleManager, _giraf);

            return(new Response <DepartmentDTO>(new DepartmentDTO(depa, members)));
        }
Exemplo n.º 2
0
        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)));
        }
Exemplo n.º 3
0
        public async Task <Response <DepartmentDTO> > AddUser(long departmentId, string userId)
        {
            //Fetch user and department and check that they exist
            if (userId == null)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.MissingProperties, "userId"));
            }

            var currentUser = await _giraf._userManager.GetUserAsync(HttpContext.User);

            if (currentUser == null)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.UserNotFound));
            }

            var role = await _roleManager.findUserRole(_giraf._userManager, currentUser);

            if (role == GirafRoles.Department || role == GirafRoles.Guardian)
            {
                // lets check that we are in the correct department
                if (currentUser.DepartmentKey != departmentId)
                {
                    return(new ErrorResponse <DepartmentDTO>(ErrorCode.NotAuthorized));
                }
            }

            var dep = await _giraf._context.Departments
                      .Where(d => d.Key == departmentId)
                      .Include(d => d.Members)
                      .Include(d => d.Resources)
                      .FirstOrDefaultAsync();

            if (dep == null)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.DepartmentNotFound));
            }

            //Check if the user is already in the department
            if (dep.Members.Any(u => u.Id == userId))
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.UserNameAlreadyTakenWithinDepartment));
            }


            var user = await _giraf._context.Users.Where(u => u.Id == userId).Include(u => u.Department)
                       .FirstOrDefaultAsync();

            var RoleOfUserToAdd = await _roleManager.findUserRole(_giraf._userManager, user);

            // only makes sense to add a guardian or citizen to a department
            if (RoleOfUserToAdd == GirafRoles.SuperUser || RoleOfUserToAdd == GirafRoles.Department)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.Forbidden));
            }

            if (user == null)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.UserNotFound));
            }

            if (user.Department != null)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.UserAlreadyHasDepartment));
            }

            user.DepartmentKey = dep.Key;
            dep.Members.Add(user);
            await _giraf._context.SaveChangesAsync();

            var members = DepartmentDTO.FindMembers(dep.Members, _roleManager, _giraf);

            return(new Response <DepartmentDTO>(new DepartmentDTO(dep, members)));
        }
Exemplo n.º 4
0
        public async Task <Response <DepartmentDTO> > AddResource(long departmentId, long resourceId)
        {
            var usr = await _giraf.LoadUserWithResources(HttpContext.User);

            //Fetch the department and check that it exists no need to load ressources already on user
            var department = await _giraf._context.Departments.Where(d => d.Key == departmentId)
                             .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 and that the user owns it.
            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.CheckPrivateOwnership(resource, usr);

            if (!resourceOwned)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.NotAuthorized));
            }

            //Check if the department already owns the resource
            var alreadyOwned = await _giraf._context.DepartmentResources
                               .Where(depres => depres.OtherKey == departmentId &&
                                      depres.PictogramKey == resourceId)
                               .AnyAsync();

            if (alreadyOwned)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.DepartmentAlreadyOwnsResource));
            }

            //Remove resource from user
            var usrResource = await _giraf._context.UserResources
                              .Where(ur => ur.PictogramKey == resource.Id && ur.OtherKey == usr.Id)
                              .FirstOrDefaultAsync();

            if (usrResource == null)
            {
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.ResourceNotFound));
            }

            usr.Resources.Remove(usrResource);
            await _giraf._context.SaveChangesAsync();

            //Change resource AccessLevel to Protected from Private
            resource.AccessLevel = AccessLevel.PROTECTED;

            //Create a relationship between the department and the resource.
            var dr = new DepartmentResource(usr.Department, resource);
            await _giraf._context.DepartmentResources.AddAsync(dr);

            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)));
        }
Exemplo n.º 5
0
        public async Task <Response <DepartmentDTO> > Post([FromBody] DepartmentDTO depDTO)
        {
            try
            {
                if (depDTO?.Name == null)
                {
                    return(new ErrorResponse <DepartmentDTO>(ErrorCode.MissingProperties,
                                                             "Deparment name has to be specified!"));
                }

                var authenticatedUser = await _giraf.LoadBasicUserDataAsync(HttpContext.User);

                if (authenticatedUser == null)
                {
                    return(new ErrorResponse <DepartmentDTO>(ErrorCode.UserNotFound));
                }

                var userRole = await _roleManager.findUserRole(_giraf._userManager, authenticatedUser);

                if (userRole != GirafRoles.SuperUser)
                {
                    return(new ErrorResponse <DepartmentDTO>(ErrorCode.NotAuthorized));
                }

                //Add the department to the database.
                Department department = new Department(depDTO);

                //Add all members specified by either id or username in the DTO
                if (depDTO.Members != null)
                {
                    foreach (var mem in depDTO.Members)
                    {
                        var usr = await _giraf._context.Users
                                  .Where(u => u.UserName == mem.UserName || u.Id == mem.UserId)
                                  .FirstOrDefaultAsync();

                        if (usr == null)
                        {
                            return(new ErrorResponse <DepartmentDTO>(ErrorCode.InvalidProperties,
                                                                     "The member list contained an invalid id: " + mem));
                        }
                        department.Members.Add(usr);
                        usr.Department = department;
                    }
                }

                //Add all the resources with the given ids
                if (depDTO.Resources != null)
                {
                    foreach (var reso in depDTO.Resources)
                    {
                        var res = await _giraf._context.Pictograms
                                  .Where(p => p.Id == reso)
                                  .FirstOrDefaultAsync();

                        if (res == null)
                        {
                            return(new ErrorResponse <DepartmentDTO>(ErrorCode.InvalidProperties,
                                                                     "The list of resources contained an invalid resource id: " + reso));
                        }
                        var dr = new DepartmentResource(department, res);
                        await _giraf._context.DepartmentResources.AddAsync(dr);
                    }
                }

                await _giraf._context.Departments.AddAsync(department);

                //Create a new user with the supplied information

                var departmentUser = new GirafUser(depDTO.Name, department)
                {
                    IsDepartment = true
                };

                //department.Members.Add(user);

                var identityUser = await _giraf._userManager.CreateAsync(departmentUser, "0000");

                if (identityUser.Succeeded == false)
                {
                    return(new ErrorResponse <DepartmentDTO>(ErrorCode.CouldNotCreateDepartmentUser, string.Join("\n", identityUser.Errors)));
                }

                await _giraf._userManager.AddToRoleAsync(departmentUser, GirafRole.Department);

                //Save the changes and return the entity
                await _giraf._context.SaveChangesAsync();

                var members = DepartmentDTO.FindMembers(department.Members, _roleManager, _giraf);
                return(new Response <DepartmentDTO>(new DepartmentDTO(department, members)));
            }
            catch (System.Exception e)
            {
                var errorDescription = $"Exception in Post: {e.Message}, {e.InnerException}";
                _giraf._logger.LogError(errorDescription);
                return(new ErrorResponse <DepartmentDTO>(ErrorCode.Error, errorDescription));
            }
        }