Exemple #1
0
    def GET(self, group_type=None, group_data=None, user_type=None, user_data=None):
        try:
            if not ManagerTool.isAuthorized(cherrypy.request.cookie, self.keystoneAuthList, require_moderator=True):
                data = dict(current="Group manager", user_status="not authorized", require_moderator=True)
            else:
                session = self.keystoneAuthList[cherrypy.request.cookie["ReservationService"].value].token
                osGroup = OSGroup(session=session)
                osUser = OSUser(session=session)
                groupArray = []
                returnData = None
                if group_type is not None and group_data is not None:
                    if "id" in group_type:
                        group = osGroup.find(id=group_data)
                        if group is not None:
                            groupDict = Group().parseObject(group).to_dict()
                            groupDict["users"] = self._listUsersinGroup(group_id=group.id)
                            groupArray.append(groupDict)
                        else:
                            raise Exception("Group doesn't exists")
                    elif "name" in group_type:
                        for group in osGroup.find(name=group_data):
                            groupDict = Group().parseObject(group).to_dict()
                            groupDict["users"] = self._listUsersinGroup(group_id=group.id)
                            groupArray.append(groupDict)
                # Get all groups
                else:
                    for group in osGroup.list():
                        Group().parseObject(group)
                        groupArray.append(Group().parseObject(group).to_dict())

                # Check if specific user exists
                if user_type is not None and user_data is not None:
                    if "id" in user_type:
                        user = osUser.find(id=user_data)
                    elif "name" in user_type:
                        user = osUser.find(name=user_data)
                        if len(user) > 1:
                            raise Exception("Multiple user found not expected")
                        elif len(user) == 0:
                            raise Exception("No user found")
                        else:
                            user = user[0]
                    userObj = User().parseObject(user)
                    for group in groupArray:
                        for user in group["users"]:
                            if User(**user) == userObj:
                                returnData = True
                                break
                            else:
                                continue
                    if returnData is None:
                        returnData = False
                else:
                    returnData = groupArray
                data = dict(current="Group manager", response=returnData)
        except Exception as e:
            error = str(e) + ": " + str(traceback.print_exc())
            data = dict(current="Group manager", error=str(error))
        finally:
            return data
    def getTeam(self,
                session,
                userid,
                id=None,
                owner_id=None,
                team_id=None,
                admin=False):
        """

        :rtype: list
        """
        getAll = False
        if id is not None:
            teams = MySQL.mysqlConn.select_team(id=id)
        elif owner_id is not None:
            teams = MySQL.mysqlConn.select_team(owner_id=owner_id)
        elif team_id is not None:
            teams = MySQL.mysqlConn.select_team(team_id=team_id)
        else:
            getAll = True
            teams = MySQL.mysqlConn.select_team()

        teamList = []
        for team in teams:
            team = Team().parseDict(team)
            if not getAll:
                if self._isOwner(session=session, userid=userid,
                                 id=team.id) or admin:
                    osGroup = OSGroup(session=session.token)
                    group = Group().parseObject(osGroup.find(id=team.team_id))
                    users = osGroup.getUsers(group_id=group.id)
                    userArray = []
                    if users is not None and len(users) > 0:
                        for user in users:
                            userArray.append(
                                User().parseObject(user).to_dict())
                    teamList.append(dict(team=team.to_dict(), users=userArray))
                else:
                    teamList.append(dict(status="Not authorized"))
            else:
                osGroup = OSGroup(session=session.token)
                group = Group().parseObject(osGroup.find(id=team.team_id))
                users = osGroup.getUsers(group_id=group.id)
                userArray = []
                if users is not None and len(users) > 0:
                    for user in users:
                        userArray.append(User().parseObject(user).to_dict())
                teamList.append(dict(team=team.to_dict(), users=userArray))
        return teamList
 def POST(self, **vpath):
     try:
         if not ManagerTool.isAuthorized(cherrypy.request.cookie,
                                         self.keystoneAuthList,
                                         require_moderator=False):
             data = dict(current="Team manager",
                         user_status="not authorized",
                         require_moderator=False)
         else:
             # Don't user session as every where. Student role have no access to keystone
             # We control it with own policies:
             # - _isOwner
             session = self.adminKSAuth
             osGroup = OSGroup(session=session.token)
             osUser = OSUser(session=session.token)
             if hasattr(cherrypy.request, "json"):
                 team = Team().parseJSON(data=cherrypy.request.json)
                 # Owner is the user that created the team
                 user_session = self.keystoneAuthList[
                     cherrypy.request.cookie["ReservationService"].value]
                 # If team owner is none assume user who create is an owner
                 if team.owner_id is None:
                     team.owner_id = user_session.userid
                 team.id = MySQL.mysqlConn.insert_team(
                     owner_id=user_session.userid)
                 group = osGroup.create(name="team_" + str(team.owner_id) +
                                        "_" + str(team.id))
                 group = Group().parseObject(group)
                 MySQL.mysqlConn.update_team(id=team.id, team_id=group.id)
                 # Add users to group
                 userArray = []
                 osGroup.addUser(group_id=group.id,
                                 user_id=user_session.userid)
                 userArray.append(User().parseObject(
                     osUser.find(id=team.owner_id)).to_dict())
                 for user_object in team.users:
                     if hasattr(user_object, "name"):
                         user = osUser.find(name=user_object["name"])
                         if len(user) == 1:
                             user = User().parseObject(user[0])
                         osGroup.addUser(group_id=group.id, user_id=user.id)
                         userArray.append(User().parseObject(
                             osUser.find(id=user.id)).to_dict())
                     elif hasattr(user_object, "id"):
                         user = User().parseObject(
                             osUser.find(id=user_object["id"]))
                         osGroup.addUser(group_id=group.id, user_id=user.id)
                         userArray.append(User().parseObject(
                             osUser.find(id=user.id)).to_dict())
                 data = dict(team=team.to_dict(), users=userArray)
             else:
                 raise Exception("No POST data")
     except Exception as e:
         error = str(e) + ": " + str(traceback.print_exc())
         data = dict(current="Team manager", error=str(error))
     finally:
         MySQL.mysqlConn.close()
         MySQL.mysqlConn.commit()
         return data
Exemple #4
0
 def DELETE(self, group_type=None, group_data=None, user_type=None, user_data=None):
     try:
         if not ManagerTool.isAuthorized(cherrypy.request.cookie, self.keystoneAuthList, require_moderator=True):
             data = dict(current="Group manager", user_status="not authorized", require_moderator=True)
         else:
             session = self.keystoneAuthList[cherrypy.request.cookie["ReservationService"].value].token
             osGroup = OSGroup(session=session)
             osUser = OSUser(session=session)
             if group_type is not None and group_data is not None and user_type is not None and user_data is not None:
                 if "id" in group_type:
                     group = osGroup.find(id=group_data)
                     if group is None:
                         raise Exception("Group doesn't exists")
                 elif "name" in group_type:
                     group = osGroup.find(name=group_data)
                     if len(group) > 1:
                         raise Exception("Multiple groups found not expected")
                     elif len(group) == 0:
                         raise Exception("No groups found")
                     else:
                         group = group[0]
                 group = Group().parseObject(group)
                 if "id" in user_type:
                     user = osUser.find(id=user_data)
                 elif "name" in user_type:
                     user = osUser.find(name=user_data)
                     if len(user) > 1:
                         raise Exception("Multiple user found not expected")
                     elif len(user) == 0:
                         raise Exception("No user found")
                     else:
                         user = user[0]
                 user = User().parseObject(user)
                 # Grant access and check if already exists
                 osGroup.removeUser(group_id=group.id, user_id=user.id)
                 data = dict(current="Group manager", response="OK")
             else:
                 data = dict(current="Group manager", response="Invalid request")
     except Exception as e:
         data = dict(current="Group manager", error=str(e))
     finally:
         return data
Exemple #5
0
 def _listUsersinGroup(self, group_id=None):
     try:
         session = self.keystoneAuthList[cherrypy.request.cookie["ReservationService"].value].token
         userArray = []
         # Find lab group id
         osGroup = OSGroup(session=session)
         group = osGroup.find(id=group_id)
         if group is not None:
             group = Group().parseObject(group)
         elif group is not None:
             raise Exception("Group doesn't exists")
         users = osGroup.getUsers(group_id=group.id)
         if users is not None and len(users) > 0:
             for user in users:
                 userArray.append(User().parseObject(user).to_dict())
         data = userArray
     except Exception as e:
         data = dict(current="Group manager", error=e)
     finally:
         return data
Exemple #6
0
    def GET(self, vpath=None):
        try:
            if not ManagerTool.isAuthorized(cherrypy.request.cookie, self.keystoneAuthList, require_admin=True):
                data = dict(current="System manager", user_status="not authorized")
            else:
                MySQL.mysqlConn.commit()
                studRole = None
                labRole = None
                modRole = None
                defProject = None
                groupStud = None
                groupModer = None
                defaults = MySQL.mysqlConn.select_defaults()
                session = self.keystoneAuthList[cherrypy.request.cookie["ReservationService"].value].token
                osRole = OSRole(session=session)
                osProject = OSProject(session=session)
                osGroup = OSGroup(session=session)

                if len(defaults) > 0:
                    defaults = defaults[0]
                    studRole = osRole.find(id=defaults["role_student"])
                    if len(studRole) == 1:
                        studRole = studRole[0]
                    if studRole is None:
                        studRole = Role().parseObject(osRole.create(name="student"))

                    labRole = osRole.find(id=defaults["role_lab"])
                    if len(labRole) == 1:
                        labRole = labRole[0]
                    if labRole is None:
                        labRole = Role().parseObject(osRole.create(name="lab"))

                    modRole = osRole.find(id=defaults["role_moderator"])
                    if len(modRole) == 1:
                        modRole = modRole[0]
                    if modRole is None:
                        modRole = Role().parseObject(osRole.create(name="moderator"))

                    defProject = osProject.find(id=defaults["project"])
                    if defProject is None:
                        defProject = osProject.create(name="reservation_system")
                    groupStud = osGroup.find(id=defaults["group_student"])
                    if groupStud is None:
                        osProject = OSProject(session=session, id=defProject.id)
                        groupStud = Group().parseObject(osGroup.create(name="students"))
                        osProject.allowGroup(group_id=groupStud.id, role="student")
                    groupModer = osGroup.find(id=defaults["group_moderator"])
                    if groupModer is None:
                        osProject = OSProject(session=session, id=defProject.id)
                        groupModer = Group().parseObject(osGroup.create(name="moderators"))
                        osProject.allowGroup(group_id=groupStud.id, role="moderators")

                    MySQL.mysqlConn.update_defaults(project_id=defProject.id,
                                                    role_student=studRole.id,
                                                    role_lab=labRole.id,
                                                    role_moderator=modRole.id,
                                                    group_student=groupStud.id,
                                                    group_moderator=groupModer.id)
                else:
                    roleFind = osRole.find(name="student")
                    if len(roleFind) > 0:
                        studRole = Role().parseObject(roleFind[0])
                    else:
                        studRole = Role().parseObject(osRole.create(name="student"))

                    roleFind = osRole.find(name="moderator")
                    if len(roleFind) > 0:
                        modRole = Role().parseObject(roleFind[0])
                    else:
                        modRole = Role().parseObject(osRole.create(name="moderator"))

                    roleFind = osRole.find(name="lab")
                    if len(roleFind) > 0:
                        labRole = Role().parseObject(roleFind[0])
                    else:
                        labRole = Role().parseObject(osRole.create(name="lab"))

                    projFind = osProject.find(name="reservation_system")
                    if len(projFind) > 0:
                        defProject = projFind[0]
                    else:
                        defProject = osProject.create(name="reservation_system")

                    groupFind = osGroup.find(name="students")
                    if len(groupFind) > 0:
                        groupStud = Group().parseObject(groupFind[0])
                    else:
                        groupStud = Group().parseObject(osGroup.create(name="students"))

                    groupFind = osGroup.find(name="moderators")
                    if len(groupFind) > 0:
                        groupModer = Group().parseObject(groupFind[0])
                    else:
                        groupModer = Group().parseObject(osGroup.create(name="moderators"))

                    osRole.grantGroup(group_id=groupStud.id,role_id=studRole.id)
                    osRole.grantGroup(group_id=groupModer.id, role_id=modRole.id)

                    osProject = OSProject(session=session, id=defProject.id)
                    osProject.allowGroup(group_id=groupStud.id, role="student")
                    osProject.allowGroup(group_id=groupModer.id, role="moderator")

                    MySQL.mysqlConn.insert_defaults(project_id=defProject.id,
                                                    role_student=studRole.id,
                                                    role_lab=labRole.id,
                                                    role_moderator=modRole.id,
                                                    group_student=groupStud.id,
                                                    group_moderator=groupModer.id)

                data = dict(current="System manager",
                            default_project=OSTools.prepareJSON(defProject),
                            role_student=studRole.to_dict(),
                            role_lab=labRole.to_dict(),
                            role_moderator=modRole.to_dict(),
                            group_students=groupStud.to_dict(),
                            group_moderator=groupModer.to_dict())
                MySQL.mysqlConn.commit()
        except Exception as e:
            if not len(defaults) > 0:
                if studRole is not None and osRole is not None:
                    osRole.delete(studRole.id)
                if labRole is not None and osRole is not None:
                    osRole.delete(labRole.id)
                if modRole is not None and osRole is not None:
                    osRole.delete(modRole.id)
                if defProject is not None and osProject is not None:
                    osProject.delete(defProject.id)
                if groupStud is not None and osGroup is not None:
                    osGroup.delete(groupStud.id)
                if groupModer is not None and osGroup is not None:
                    osGroup.delete(groupModer.id)
            error = str(e) + ": " + str(traceback.print_exc())
            data = dict(current="System manager", error=error)

        finally:
            MySQL.mysqlConn.close()
            return data
Exemple #7
0
    def POST(self):
        try:
            if not ManagerTool.isAuthorized(cherrypy.request.cookie,
                                            self.keystoneAuthList,
                                            require_moderator=False):
                data = dict(current="Reservation manager",
                            user_status="not authorized",
                            require_moderator=False)
            else:
                if hasattr(cherrypy.request, "json"):
                    request = cherrypy.request.json
                    reservation = Reservation().parseJSON(data=request)
                else:
                    raise Exception("JSON data not valid")

                MySQL.mysqlConn.commit()
                # Find laboratory
                labs = MySQL.mysqlConn.select_lab(id=reservation.laboratory_id)
                if len(labs) == 1:
                    lab = Laboratory().parseDict(labs[0])
                else:
                    raise Exception(
                        "No lab found with this ID. Cannnot make reservation")

                # Does laboratory is active?
                # Get periods
                lab_periods = MySQL.mysqlConn.select_period(
                    lab_id=reservation.laboratory_id)

                # Check if periods expired?
                labActive = False
                for period in lab_periods:
                    period = Period().parseDict(period)
                    currentTime = datetime.datetime.now()
                    if period.start <= currentTime and currentTime <= period.stop:
                        labActive = True
                        break
                #This laboratory is not active
                if labActive is False:
                    raise Exception(
                        "Laboratory is not active during requested reservation time"
                    )
                # Does reservation time fit in laboratory periods
                reservationFit = False
                for period in lab_periods:
                    period = Period().parseDict(period)
                    if period.start <= reservation.start and reservation.start + lab.duration <= period.stop:
                        reservationFit = True
                        break
                # It does not fit
                if reservationFit is False:
                    raise Exception("Reservation outside of lab period")

                # Check allowance for making reservation
                reservationUserAllow = False
                session = self.adminKSAuth
                user_session = self.keystoneAuthList[
                    cherrypy.request.cookie["ReservationService"].value]
                osUser = OSUser(session=session.token)
                osGroup = OSGroup(session=session.token)
                group = osGroup.find(name=lab.group)
                if group is not None and len(group) == 1:
                    group = Group().parseObject(group[0])
                else:
                    raise Exception("No group found for lab - not expected")

                # If no user id or team id use user session
                if reservation.team_id is None and reservation.user_id is None:
                    reservation.user_id = user_session.userid

                # If reservation is for team
                if reservation.team_id is not None:
                    team_reservations = MySQL.mysqlConn.select_reservation(
                        team=reservation.team_id, lab=lab.id)
                    if len(team_reservations) == 0:
                        managerTeam = ManagerTeam(self.keystoneAuthList,
                                                  self.adminKSAuth)
                        teams = managerTeam.getTeam(session=session,
                                                    userid=user_session.userid,
                                                    id=reservation.team_id,
                                                    admin=True)
                        for team in teams:
                            usersid = []
                            if len(team["users"]) == 0:
                                raise Exception("No user in team")
                            for user in team["users"]:
                                user = User().parseDict(user)
                                usersid.append(user.id)

                            groupusersid = []
                            groupusers = osGroup.getUsers(group_id=group.id)
                            if groupusers is None or len(groupusers) == 0:
                                groupusers = []
                            else:
                                for groupuser in groupusers:
                                    groupusersid.append(groupuser.id)
                                if all(userid in groupusersid
                                       for userid in usersid):
                                    reservationUserAllow = True
                                else:
                                    reservationUserAllow = False
                    else:
                        raise Exception(
                            "Team already have reseravtion for this lab")
                # If reservation is for one user
                elif reservation.user_id is not None:
                    # Use admin privilages
                    users_reservations = MySQL.mysqlConn.select_reservation(
                        user=reservation.user_id, lab=lab.id)
                    if len(users_reservations) == 0:
                        reservationUserAllow = osGroup.checkUserIn(
                            group_id=group.id, user_id=user_session.userid)
                    else:
                        raise Exception(
                            "User already have reseravtion for this lab")
                else:
                    raise Exception("No user id or team id in request!")
                if reservationUserAllow is False:
                    raise Exception(
                        "User or team not allowed to reserve this lab")

                # Check if user or team have already reservation

                # Is there any other reservation for this lab in that period
                # From database reservation for this lab
                # check limit of lab (allow multiple)
                overlap_reservation = []
                otherReservations = MySQL.mysqlConn.select_reservation(
                    lab=lab.id)
                for otherReservation in otherReservations:
                    otherReservation = Reservation().parseDict(
                        otherReservation)
                    if (reservation.start + lab.duration >=
                            otherReservation.start
                            and reservation.start < otherReservation.start):
                        overlap_reservation.append(otherReservation)
                    if (reservation.start <=
                            otherReservation.start + lab.duration
                            and reservation.start >= otherReservation.start):
                        overlap_reservation.append(otherReservation)
                if len(overlap_reservation) < lab.limit:
                    reservationAllow = True
                else:
                    reservationAllow = False

                if reservationAllow is False:
                    raise Exception(
                        "Unable to make reservation, limit for reservation overused"
                    )

                # Create this reservation
                if reservation.user_id is not None:
                    reservation.id = MySQL.mysqlConn.insert_reservation(
                        user=reservation.user_id,
                        start=reservation.start,
                        laboratory_id=reservation.laboratory_id)
                elif reservation.team_id is not None:
                    reservation.id = MySQL.mysqlConn.insert_reservation(
                        team_id=reservation.team_id,
                        start=reservation.start,
                        laboratory_id=reservation.laboratory_id)
                else:
                    # Not expected
                    raise Exception("No user id or team id not expected")

                data = dict(current="Reservation manager",
                            response=reservation.to_dict())
        except Exception as e:
            traceback_output = traceback.print_exc()
            if traceback_output is None:
                error = str(e)
            else:
                error = str(e) + ": " + str(traceback.print_exc())
            print(error)
            data = dict(current="Reservation manager", error=str(error))
        finally:
            MySQL.mysqlConn.close()
            MySQL.mysqlConn.commit()
            return data
    def POST(self, vpath=None):
        try:
            if not ManagerTool.isAuthorized(cherrypy.request.cookie,
                                            self.keystoneAuthList,
                                            require_moderator=True):
                data = dict(current="User manager",
                            user_status="not authorized",
                            require_moderator=True)
            else:
                session = self.keystoneAuthList[
                    cherrypy.request.cookie["ReservationService"].value].token
                osUser = OSUser(session=session)
                osGroup = OSGroup(session=session)

                if vpath is not None:
                    raise Exception("Not allowed on: /user/" + str(vpath))
                else:
                    # Get defaults
                    defaults = ManagerTool.getDefaults()

                    # Parse incoming JSON
                    if hasattr(cherrypy.request, "json"):
                        request = cherrypy.request.json
                        user = User().parseJSON(data=request)
                        group = Group().parseJSON(data=request)
                    else:
                        raise Exception("No data in POST")

                    if user is not None:
                        user = osUser.create(name=user.name,
                                             password=user.password,
                                             project_id=defaults["project"],
                                             mail=user.mail)
                        user = User().parseObject(user)
                        # Find lab group id
                        if group is not None:
                            if group.id is not None:
                                group = Group.parseObject(
                                    osGroup.find(id=group.id))
                            elif group.name is not None:
                                findGroup = osGroup.find(name=group.name)
                                if findGroup is not None and len(
                                        findGroup) == 1:
                                    group = Group().parseObject(findGroup[0])
                                elif len(findGroup) > 0:
                                    osUser.delete(user_id=user.id)
                                    raise Exception(
                                        "Found more than one group with given name. This is not expected"
                                    )
                                else:
                                    osUser.delete(user_id=user.id)
                                    raise Exception(
                                        "Group doesn't exists. This is not expected"
                                    )
                            if group.id != defaults[
                                    "group_moderator"] and group.id != defaults[
                                        "group_student"]:
                                osUser.delete(user_id=user.id)
                                raise Exception(
                                    "Group doesn't match any of system defaults"
                                )
                            else:
                                osGroup.addUser(group_id=group.id,
                                                user_id=user.id)
                        result = user.to_dict()
                    else:
                        raise Exception("Invalid request")
                    data = dict(current="User manager", response=result)
        except Exception as e:
            traceback_output = traceback.print_exc()
            if traceback_output is None:
                error = str(e)
            else:
                error = str(e) + ": " + str(traceback.print_exc())
            print(error)
            data = dict(current="User manager", error=str(error))
        finally:
            MySQL.mysqlConn.close()
            MySQL.mysqlConn.commit()
            return data