예제 #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
예제 #2
0
 def __isAuthorized(self, reservation):
     authorize = False
     session = self.adminKSAuth
     user_session = self.keystoneAuthList[
         cherrypy.request.cookie["ReservationService"].value]
     if reservation.team_id is not None:
         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)
         if user_session.userid in usersid:
             authorize = True
     # Reservation is made by user
     elif reservation.user_id is not None:
         osUser = OSUser(session=session.token)
         user = osUser.find(id=user_session.userid)
         if user is not None:
             user = User().parseObject(user)
         else:
             raise Exception("No user found!")
         if user.id == reservation.user_id:
             authorize = True
     else:
         raise Exception("No user or team_id in reservation. Not expected!")
     return authorize
예제 #3
0
 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
예제 #4
0
 def PATCH(self, user_type=None, user_data=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)
             userResult = []
             if user_type is not None and user_data is not None:
                 if hasattr(cherrypy.request, "json"):
                     userUpdate = User().parseJSON(
                         data=cherrypy.request.json)
                     userUpdate.to_dict()
                     if "id" in user_type:
                         user = osUser.find(id=user_data)
                         if user is not None:
                             userObj = User().parseObject(user)
                             userResult.append(User().parseObject(
                                 osUser.update(
                                     userObj.id,
                                     **userUpdate.to_dict())).to_dict())
                     elif "name" in user_type:
                         for user in osUser.find(name=user_data):
                             userObj = User().parseObject(user)
                             userResult.append(User().parseObject(
                                 osUser.update(
                                     userObj.id,
                                     **userUpdate.to_dict())).to_dict())
                 else:
                     raise Exception("Not JSON data!")
             else:
                 raise Exception(
                     "Not allowed on: /user! Specify id or name")
             data = dict(current="User manager", result=userResult)
     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
예제 #5
0
    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
예제 #6
0
    def DELETE(self, user_type=None, user_data=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)
                if user_type is not None and user_data is not None:
                    user_obj = None
                    if "id" in user_type:
                        user = osUser.find(id=user_data)
                        if user is not None:
                            user_obj = User().parseObject(user)
                    elif "name" in user_type:
                        for user in osUser.find(name=user_data):
                            user_obj = User().parseObject(user)
                    if user_obj is not None:
                        # Remove user
                        osUser.delete(user_obj.id)
                    else:
                        raise Exception("No user found!")
                else:
                    raise Exception(
                        "User /user/id or /user/name to specify id or name")

                data = dict(current="User manager", response="OK")
        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:
            return data
예제 #7
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
예제 #8
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
예제 #9
0
    def _isOwner(self, session, userid, id):
        team = MySQL.mysqlConn.select_team(id=id)
        if team is not None and len(team) == 1:
            team = Team().parseDict(team[0])
        elif team is not None and len(team) == 0:
            raise Exception("No team with id" + str() + " found!")
        else:
            raise Exception(
                "More than one team found with given id. This was not expected!"
            )

        osUser = OSUser(session=session.token)
        userFind = osUser.find(id=userid)
        if userFind is not None:
            user = User().parseObject(userFind)
        else:
            raise Exception(
                "More than one user found with given username. This was not expected!"
            )

        if team.owner_id == user.id:
            return True
        else:
            return False
예제 #10
0
 def GET(self, reserv_type=None, reserv_id=None):
     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:
             reservArray = []
             session = self.adminKSAuth
             user_session = self.keystoneAuthList[
                 cherrypy.request.cookie["ReservationService"].value]
             # List specific
             if reserv_type is not None and reserv_id is not None:
                 if reserv_type == "id":
                     # Get reservation
                     reservations = MySQL.mysqlConn.select_reservation(
                         id=reserv_id)
                     # Check if reservation is connected with user
                     if reservations is not None and len(reservations) > 0:
                         for reserv in reservations:
                             reservation = Reservation().parseDict(reserv)
                             # Reservation id belong to one user
                             if reservation.team_id is None and reservation.user_id is not None:
                                 osUser = OSUser(session=session.token)
                                 user = osUser.find(id=user_session.userid)
                                 if user is not None:
                                     user = User().parseObject(user)
                                     if reservation.user_id == user.id:
                                         reservArray.append(
                                             reservation.to_dict())
                                     else:
                                         raise Exception(
                                             "Not authorized to get this reservation"
                                         )
                             # Reservation belong to team
                             elif reservation.team_id is not None:
                                 managerTeam = ManagerTeam(
                                     self.keystoneAuthList,
                                     self.adminKSAuth)
                                 teams = managerTeam.getTeam(
                                     session=session,
                                     userid=user_session.userid,
                                     id=reservation.team_id,
                                     admin=True)
                                 if teams is not None and len(teams) > 0:
                                     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)
                                 if user_session.userid in usersid:
                                     reservArray.append(
                                         reservation.to_dict())
                                 else:
                                     raise Exception(
                                         "Not authorized to get this reservation"
                                     )
                     else:
                         raise Exception(
                             "Unable to find resrvation with this id")
                 else:
                     raise Exception("Malformed request")
             # List all
             elif reserv_type is None:
                 if ManagerTool.isAdminOrMod(cherrypy.request.cookie,
                                             self.keystoneAuthList):
                     reservations = MySQL.mysqlConn.select_reservation()
                     # Prepare data
                     for reserv in reservations:
                         reservArray.append(
                             Reservation().parseDict(reserv).to_dict())
                 else:
                     data = dict(current="Reservation manager",
                                 user_status="not authorized",
                                 require_moderator=False)
             else:
                 raise Exception("Malformed request")
             data = dict(current="Reservation manager",
                         response=reservArray)
     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
예제 #11
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
예제 #12
0
    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
예제 #13
0
 def GET(self, user_type=None, user_data=None):
     try:
         if not ManagerTool.isAuthorized(cherrypy.request.cookie,
                                         self.keystoneAuthList,
                                         require_moderator=False):
             data = dict(current="User manager",
                         user_status="not authorized",
                         require_moderator=False)
         else:
             session = self.keystoneAuthList[
                 cherrypy.request.cookie["ReservationService"].value]
             osUser = OSUser(session=session.token)
             userDict = []
             if user_type is not None and user_data is not None:
                 if "id" in user_type:
                     user = osUser.find(id=user_data)
                     if user is not None:
                         user = User().parseObject(user)
                         if not ManagerTool.isAdminOrMod(
                                 cherrypy.request.cookie,
                                 self.keystoneAuthList):
                             if user.id == session.userid:
                                 userDict.append(user.to_dict())
                             else:
                                 data = dict(current="User manager",
                                             user_status="not authorized",
                                             require_moderator=True)
                         else:
                             userDict.append(user.to_dict())
                 elif "name" in user_type:
                     for user in osUser.find(name=user_data):
                         user = User().parseObject(user)
                         if not ManagerTool.isAdminOrMod(
                                 cherrypy.request.cookie,
                                 self.keystoneAuthList):
                             if user.id == session.userid:
                                 userDict.append(user.to_dict())
                             else:
                                 data = dict(current="User manager",
                                             user_status="not authorized",
                                             require_moderator=True)
                         else:
                             userDict.append(user.to_dict())
                 data = dict(current="User manager", response=userDict)
             # Get all
             elif ManagerTool.isAdminOrMod(cherrypy.request.cookie,
                                           self.keystoneAuthList):
                 for user in osUser.list():
                     userDict.append(User().parseObject(user).to_dict())
                 data = dict(current="User manager", response=userDict)
             else:
                 data = dict(current="User manager",
                             user_status="not authorized",
                             require_moderator=True)
     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:
         return data
예제 #14
0
 def PUT(self,
         team_type=None,
         team_data=None,
         user=None,
         user_type=None,
         user_data=None):
     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)
             user_session = self.keystoneAuthList[
                 cherrypy.request.cookie["ReservationService"].value]
             if team_type is not None and team_data is not None:
                 if "id" in team_type:
                     team = MySQL.mysqlConn.select_team(id=team_data)
                     if team is not None and len(team) == 1:
                         team = Team().parseDict(team[0])
                     elif team is not None and len(team) == 0:
                         raise Exception("No team with id" + str() +
                                         " found!")
                     else:
                         raise Exception(
                             "More than one team found with given id. This was not expected!"
                         )
                 else:
                     raise Exception("Not allowed without /team/id/")
             if user_type is not None and user_data is not None:
                 if ManagerTool.isAdminOrMod(
                         cherrypy.request.cookie,
                         self.keystoneAuthList) or self._isOwner(
                             session=session,
                             userid=user_session.userid,
                             id=team_data):
                     # Remove specific user
                     if "id" in user_type:
                         user = User().parseObject(
                             osUser.find(id=user_data))
                         osGroup.addUser(group_id=team.team_id,
                                         user_id=user.id)
                         data = self.getTeam(session=session,
                                             team_id=team.team_id,
                                             userid=user_session.userid)
                     elif "name" in user_type:
                         user = osUser.find(name=user_data)
                         if len(user) > 1:
                             raise Exception("Multiple users found")
                         elif len(user) == 0:
                             raise Exception("No user found!")
                         else:
                             user = User().parseObject(user[0])
                         osGroup.addUser(group_id=team.team_id,
                                         user_id=user.id)
                         data = self.getTeam(session=session,
                                             team_id=team.team_id,
                                             userid=user_session.userid)
                 else:
                     data = dict(
                         current="Team manager",
                         response="Not owned by this user or not mod,admin")
     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
예제 #15
0
    def POST(self, vpath=None):
        """Authenticate
         :returns: JSON response
         :rtype: {string}
         """
        try:
            # Parse json input auth
            if hasattr(cherrypy.request, "json"):
                request = cherrypy.request.json
                auth = Auth().parseJSON(data=request)
            else:
                raise Exception("No data in POST")
            # Bind admin and check group
            osKSUser = OSKeystone.OSUser(session=self.adminKSAuth.token)
            osKSRoles = OSKeystone.OSRole(session=self.adminKSAuth.token)
            # Find user from json input
            userFind = osKSUser.find(name=auth.username)
            if userFind is not None and len(userFind) == 1:
                user = User().parseObject(userFind[0])
            elif userFind is not None and len(userFind) > 1:
                raise Exception("Duplicate username found")
            else:
                raise Exception("User does not exist")
            # Check role of auth user
            osUserRoles = osKSRoles.getUserRole(user_id=user.id)
            if "admin" in osUserRoles:
                auth.role = "admin"
            elif "moderator" in osUserRoles:
                auth.role = "moderator"
            elif "student" in osUserRoles:
                auth.role = "student"
            elif "user" in osUserRoles:
                auth.role = "user"

            osKSProject = OSKeystone.OSProject(session=self.adminKSAuth.token)
            if auth.role is not "admin":
                project = osKSProject.find(name="reservation_system")
            else:
                project = osKSProject.find(name="admin")
            if len(project) == 1:
                project = project[0]
            osKSAuth = OSKeystone.OSAuth(
                username=auth.username,
                user_domain_name=ConfigParser.configuration["openstack"]
                ["user_domain_name"],
                password=auth.password,
                project_id=project.id,
                project_name=project.name,
                project_domain_name=project.domain_id,
                auth_url=ConfigParser.configuration["openstack"]["auth_url"])
            # Check pass
            auth.token = osKSAuth.createKeyStoneSession()
            auth.token.get_token()
            session = Session(userid=user.id,
                              username=auth.username,
                              role=auth.role,
                              token=auth.token,
                              auth=osKSAuth)
            self.keystoneAuthList[str(cherrypy.session.id)] = session
            data = dict(current="Authorization manager",
                        user_status="authorized",
                        username=session.username,
                        type=session.role)
            return data
        except Exception as e:
            error = str(e) + ": " + str(traceback.print_exc())
            print(error)
            data = dict(current="Authorization manager",
                        user_status="error",
                        error=str(error))
            return data