Ejemplo n.º 1
0
def update_user(g, data):
    user_up = g.token.user
    if ('username' in data and data['username'] is not None):
        user = User.query.getByName(data['username'], False)
        if user is not None:
            raise DbException(400, "This username is already in use.",
                              ['username'])
        else:
            user_up.name = data['username']

    if ('email' in data and data['email'] is not None):
        if not re.match('[^@]+@[^@]+\.[^@]+', data["email"]):  # noqa W605
            raise ApiException(400, "Supplied email is not valid.", ['email'])
        user = User.query.getByEmail(data['email'], False)
        if user is not None:
            raise DbException(400, "This email is already in use.", ['email'])
        else:
            user_up.email = data['email']

    if ('name' in data and data['name'] is not None):
        user_up.fullname = data['name']

    app.db.session.flush()
    app.db.session.commit()

    return user_up
Ejemplo n.º 2
0
def create(g):
    """
    Creates module
        :param g: context
    """
    invalid = []
    g.project = Project.query.get_active(g.data['project'])
    if g.project is None:
        raise ApiException(404, "Project not found.", ['project'])

    if g.project.owner_id != g.token.user_id:
        contributor = 0
        for user in g.project.contributors:
            if user.id == g.token.user_id:
                contributor = 1
                break
        if contributor == 0:
            raise ApiException(403, "Access denied (no rights)", ['project'])
    pattern = re.compile(r'^[\w\s\-\_]{2,}$', re.U)
    if (not re.match(pattern, g.data['name'].strip()) or  # noqa W605
            Module.query.filter_by(project_id=g.project.id,
                                   name=g.data['name']).first() is not None):
        invalid.append("name")

    if ((not isinstance(g.data['dependency'], list))
            and g.data['dependency'] != 'independent'):
        invalid.append("dependency")

    if 'body' not in g.data['content']:
        invalid.append("content")

    if invalid != []:
        raise ApiException(400, "Module data are invalid or non-unique.",
                           invalid)

    g.module = Module(g.data['name'], g.data['description'], g.project.id,
                      g.token.user_id)

    if g.data['dependency'] != 'independent':
        for each in g.data['dependency']:
            dependency = Module.query.filter_by(project_id=g.project.id,
                                                name=each).first()
            if (dependency is None) or (dependency in g.module.dependencies):
                raise DbException(400,
                                  "Module data are invalid or non-unique.",
                                  ['dependency'])
            g.module.dependencies.append(dependency)

    if 'type' in g.data['content']:
        g.module.contentType = g.data['content']['type']

    app.db.session.add(g.module)
    app.db.session.commit()

    with open(
            conf.FILE_PATH + '/' + str(g.project.id) + '/' + str(g.module.id) +
            '.txt', 'w+') as file:
        file.write(str(g.data['content']['body']))
Ejemplo n.º 3
0
def view_modules(g):
    project = Project.query.filter(
        Project.id == g.id, Project.delete.is_(None)).first()

    if project is None:
        raise DbException(400,
                          "Project does not exist.",
                          invalid=['id'])

    return project.modules
Ejemplo n.º 4
0
 def get_user_all(cls, raiseFlag = True):
     """
         Returns all users.
         :param cls: User
         :param raiseFlag: If true and no User is found raises DbException.
     """
     user = cls.query.all()
     if (user == None or user == []) and raiseFlag:
         raise DbException(404, "No user found.")
     return user
Ejemplo n.º 5
0
 def get_token_all(cls, raiseFlag = True):
     """
         Returns all tokens.
         :param cls: UserToken
         :param raiseFlag:If true and no tokens are found raises DbException.
     """
     userToken = cls.query.all()
     if (userToken == None) & raiseFlag:
         raise DbException(404, "No userToken found.")
     return userToken
Ejemplo n.º 6
0
 def get_type_all(cls, raiseFlag = True):
     """
         Returns list of all types.
         :param cls: UserType
         :param raiseFlag: If true and no UserType is found raises DbException.
     """ 
     userType = cls.query.all()
     if (userType == None or userType == []) & raiseFlag:
         raise DbException(404, "No userType found.")
     return userType
Ejemplo n.º 7
0
 def get_user_all_by_user_type_id(cls, userType, raiseFlag = True):
     """
         Returns all users with one user type.
         :param cls: User
         :param userType: UserType ID
         :param raiseFlag: If true and no User is found raises DbException.
     """
     user = User.query.filter_by(user_type_id=userType).all()
     if (user == None or user == []) & raiseFlag:
         raise DbException(404, "No user found.")
     return user
Ejemplo n.º 8
0
 def get_user_by_username_or_email(cls, username, raiseFlag = True):
     """
         Returns User found by username or email.
         :param cls: User
         :param username: username or email (String)
         :param raiseFlag: If true and no User is found raises DbException.
     """
     user = cls.query.filter((User.email == username) | (User.name == username)).first()
     if (user == None)  & raiseFlag:
         raise DbException(404, "User not found.")
     return user
Ejemplo n.º 9
0
 def get_token_all_by_user_id(cls, userId, raiseFlag = True):
     """
         Returns all tokens from one user.
         :param cls: UserToken
         :param userId: User ID
         :param raiseFlag: If true and no tokens are found raises DbException.
     """
     userToken = cls.query.filter_by(user_id=userId).all()
     if (userToken == None or userToken == []) & raiseFlag:
         raise DbException(404, "No userToken found.")
     return userToken
Ejemplo n.º 10
0
 def get_token_by_id(cls, tokenId, raiseFlag = True):
     """
         Returns token by its id.
         :param cls: UserToken
         :param tokenId: UserToken ID
         :param raiseFlag: If true and no token is found raises DbException.
     """
     userToken = cls.query.filter_by(id=tokenId).first()
     if (userToken == None) & raiseFlag:
         raise DbException(404, "UserToken not found.")
     return userToken
Ejemplo n.º 11
0
 def get_type_by_name(cls, typeName, raiseFlag = True):
     """
         Returns UserType found by its name.
         :param cls: UserType
         :param typeName: UserType name
         :param raiseFlag: If true and no UserType is found raises DbException.
     """ 
     userType = cls.query.filter_by(name=typeName).first()
     if (userType == None) & raiseFlag:
         raise DbException(404, "UserType not found.")
     return userType
Ejemplo n.º 12
0
 def get_type_by_id(cls, typeId, raiseFlag = True):
     """
         Returns UserType found by its ID.
         :param cls: UserType
         :param typeId: UserType ID
         :param raiseFlag: If true and no UserType is found raises DbException.
     """ 
     userType = cls.query.filter_by(id=typeId).first()
     if (userType == None) & raiseFlag:
         raise DbException(404, "UserType not found.")
     return userType
Ejemplo n.º 13
0
 def get_user_by_id(cls, userId, raiseFlag = True):
     """
         Returns User found by id.
         :param cls: User
         :param userId: id
         :param raiseFlag: If true and no User is found raises DbException.
     """
     user = User.query.filter_by(id=userId).first()
     if (user == None) & raiseFlag:
         raise DbException(404, "User not found.")
     return user
Ejemplo n.º 14
0
def view(g):
    """
    Returns list of modules in project
        :param g: context
    """
    g.project = Project.query.get_active(g.id)

    if g.project is None:
        raise DbException(404,
                          "Project doesn't exist.",
                          invalid=['id'])
Ejemplo n.º 15
0
 def get_user_by_email(cls, userEmail, raiseFlag = True):
     """
         Returns User found by email.
         :param cls: User
         :param userEmail: email (String)
         :param raiseFlag: If true and no User is found raises DbException.
     """
     user = User.query.filter_by(email=userEmail).first()
     if (user == None) & raiseFlag:
         raise DbException(404, "User not found.")
     return user
Ejemplo n.º 16
0
    def update_user_by_id_from_array(cls, id, dataArray):
        """
            Updates User found by users ID.
            :param cls: User
            :param id: User ID
            :param dataArray: Array of data containing variable amout of informations. Contained informations are then updated and informatons not included are left untouched.
            :param raiseFlag: If true and no User or UserType is found raises DbException.
        """
        changed = 0
        userEntity = cls.get_user_by_id(id)
        # Name change
        if 'name' in dataArray and dataArray["name"] != None:
            userCheck = cls.get_user_by_name(dataArray["name"], False)
            if userCheck != None and userCheck.id != id:
                raise DbException(400, "username")
            userEntity.name = dataArray["name"]
            changed = 1

        if 'email' in dataArray and dataArray["email"] != None:
            userCheck = cls.get_user_by_email(dataArray["email"], False)
            if userCheck != None and userCheck.id != id:
                raise DbException(400, "email")
            userEntity.email = dataArray["email"]
            changed = 1

        if 'user_type_id' in dataArray and dataArray["user_type_id"] != None:
            userType = UserType.get_type_by_id(dataArray["user_type_id"], False)
            if userType == None:
                raise DbException(400, "usertype")
            userEntity.user_type_id = dataArray["user_type_id"]
            changed = 1

        if 'password' in dataArray and dataArray["password"] != None:
            userEntity.password = bcrypt.hashpw(dataArray["password"].encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
            changed = 1

        if (changed == 1):
            userEntity.update = datetime.datetime.utcnow()

        db.session.commit() 
        return userEntity
Ejemplo n.º 17
0
    def check_unique(cls, username, email, raiseFlag = False):
        """
            Check if username and email are not presented in database (check unique)
            :param self:
            :param username:
            :param email:
            :param raiseFlag=False: if its true this function raise exception if email or username are already presented
        """

        userEmail = User.get_user_by_email(email, False)
        userName = User.get_user_by_name(username, False)

        if raiseFlag:
            if userEmail != None:
                raise DbException(400, "email")
            if userName != None:
                raise DbException(400, "username")
            return True
        else:
            if userEmail != None:
                return False
            if userName != None:
                return False
            return True
Ejemplo n.º 18
0
    def serialize(self):
        """
        Serialize object for json
            :param self:
        """
        contrib = []
        for each in self.contributors:
            contrib.append([
                each.name,
                hashlib.md5(each.email.lower().encode('utf-8')).hexdigest(),
                'contributor',
            ])

        colab = {
            'label': [
                "username",
                "emailhash",
                "role",
            ],
            'data': contrib,
        }
        owner = User.query.get_or(self.owner_id)
        if owner is None:
            raise DbException(404, "Owner not found.", ['owner_id'])
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'owner': {
                'id': self.owner_id,
                'username': owner.name,
                'emailhash': hashlib.md5(
                    owner.email.lower().encode('utf-8')
                ).hexdigest(),
            },
            'collaborators': colab,
            'active': self.active,
            'created': self.create,
            'updated': self.update
        }
Ejemplo n.º 19
0
def update(g):
    """
    Updates module by data provided in g.data
        :param g: context
    """
    invalid = []
    g.module = Module.query.get_active(g.id)
    if g.module is None:
        raise ApiException(404, "Module not found.", ['module'])

    g.project = Project.query.get_active(g.module.project_id)
    if g.project is None:
        raise ApiException(404, "Project not found.", ['project'])

    if g.project.owner_id != g.token.user_id:
        contributor = 0
        for user in g.project.contributors:
            if user.id == g.token.user_id:
                contributor = 1
                break
        if contributor == 0:
            raise ApiException(403, "Access denied (no rights)", ['project'])
    pattern = re.compile(r'^[\w\s\-\_]{2,}$', re.U)
    if 'name' in g.data:
        if ((not re.match(pattern, g.data['name'].strip())) or  # noqa W605
                Module.query.filter_by(project_id=g.project.id,
                                       name=g.data['name']).first()
                not in [None, g.module]):
            invalid.append("name")
        else:
            g.module.name = g.data['name']

    if 'description' in g.data:
        g.module.description = g.data['description']

    if 'dependency' in g.data:
        if ((not isinstance(g.data['dependency'], list))
                and (g.data['dependency'] != 'independent')):
            invalid.append("dependency")
        if g.data['dependency'] == 'independent':
            g.module.dependencies = []
        else:
            for each in g.data['dependency']:
                flag = 0
                for x in g.module.dependencies:
                    if x.name == each:
                        flag = 1
                        break
                if flag == 0:
                    dependency = Module.query.filter_by(
                        project_id=g.project.id, name=each).first()
                    if ((dependency is None)
                            or (dependency in g.module.dependencies)):
                        invalid.append('dependency')
                        break
                    g.module.dependencies.append(dependency)
    if 'content' in g.data:
        if 'body' not in g.data['content']:
            invalid.append('content')
            raise DbException(400, "Module data are invalid or non-unique.",
                              invalid)
        with open(
                FILE_PATH + '/' + str(g.project.id) + '/' + str(g.module.id) +
                '.txt', 'w+') as file:
            file.write(str(g.data['content']['body']))
        if 'type' in g.data['content']:
            g.module.contentType = g.data['content']['type']

    if invalid != []:
        raise DbException(400, "Module data are invalid or non-unique.",
                          invalid)

    app.db.session.merge(g.module)
    app.db.session.flush()
    app.db.session.commit()