def populateDefaultUsers(): userService = support.entityFor(IUserService) assert isinstance(userService, IUserService) userRbacService = support.entityFor(IUserRbacService) assert isinstance(userRbacService, IUserRbacService) for name in (('Janet', 'Admin'), ('Diane', 'Editor'), ('Andrew', 'Reporter'), ('Christine', 'Journalist')): loginName = name[1].lower() users = userService.getAll(limit=1, q=QUser(name=loginName)) if not users: user = User() user.FirstName = name[0] user.LastName = name[1] user.EMail = '*****@*****.**' % name user.Name = loginName user.Password = hashlib.sha512(b'a').hexdigest() user.Id = userService.insert(user) else: user = next(iter(users)) if user.Name == 'admin': userRbacService.assignRole(user.Id, blogRoleAdministratorId()) elif user.Name == 'editor': userRbacService.assignRole(user.Id, blogRoleEditorId()) else: userRbacService.assignRole(user.Id, blogRoleCollaboratorId())
def getUsersIds(): userService = entityFor(IUserService) assert isinstance(userService, IUserService) if not _cache_users: users = _cache_users for name in USERS: usrs = userService.getAll(adminId=None, q=QUser(name=name)) if usrs: users[name] = next(iter(usrs)).Id else: usr = User() usr.Name = name usr.Password = hashlib.sha512(b'a').hexdigest() usr.FirstName, usr.LastName, usr.EMail = USERS[name] users[name] = userService.insert(adminId=None, user=usr) return _cache_users
def getUsersIds(): userService = entityFor(IUserService) assert isinstance(userService, IUserService) if not _cache_users: users = _cache_users for name in USERS: usrs = userService.getAll(q=QUser(name=name)) if usrs: users[name] = next(iter(usrs)).Id else: usr = User() usr.Name = name usr.Password = hashlib.sha512(b'a').hexdigest() usr.FirstName, usr.LastName, usr.EMail = USERS[name] users[name] = userService.insert(usr) return _cache_users
def populateRootUser(): userService = support.entityFor(IUserService) assert isinstance(userService, IUserService) userRbacService = support.entityFor(IUserRbacService) assert isinstance(userRbacService, IUserRbacService) users = userService.getAll(limit=1, q=QUser(name='Janet')) if not users: user = User() user.Name = 'root' user.Password = hashlib.sha512(b'root').hexdigest() user.Id = userService.insert(user) else: user = users[0] userRbacService.assignRole(user.Id, rootRoleId())
def populateRootUser(): userService = support.entityFor(IUserService) assert isinstance(userService, IUserService) userRbacService = support.entityFor(IUserRbacService) assert isinstance(userRbacService, IUserRbacService) roleService = support.entityFor(IRoleService) assert isinstance(roleService, IRoleService) users = userService.getAll(limit=1, q=QUser(name='root')) if not users: user = User() user.Name = 'root' user.Password = hashlib.sha512(b'root').hexdigest() user.Id = userService.insert(user) else: user = users[0] userRbacService.assignRole(user.Id, roleService.getByName(NAME_ROOT).Id)
def setIcon(self, personId, metaDataId, update): ''' @see: IPersonIconService.setIcon ''' if update: user = User() user.Id = personId self.userService.update(user) entityDb = PersonIconMapped() entityDb.Id, entityDb.MetaData = personId, metaDataId try: self.session().merge(entityDb) self.session().flush((entityDb,)) except SQLAlchemyError as e: handle(e, entityDb) return entityDb.Id
def _getCollaboratorForAuthor(self, author, source): ''' Returns a collaborator identifier for the user/source defined in the post. If the post was not created by a user it returns a collaborator for the source identified in the post and the default user. The default user should be the sync entry creator. If the source from the post does not exist locally raises Exception. @param author: dict The author data in JSON decoded format @param source: Source The source from which the blog synchronization is done @return: integer The collaborator identifier. ''' assert isinstance(source, Source) try: userJSON = author['User'] user = User() user.Name = sha1((userJSON.get('Name', '') + source.URI).encode(self.encodingType)).hexdigest() user.FirstName, user.LastName = userJSON.get('FirstName', ''), userJSON.get('LastName', '') user.EMail, user.Password = userJSON.get('EMail', ''), '*' user.Type = self.user_type_key try: userId = self.userService.insert(user) except InputError: localUser = self.userService.getAll(q=QUser(name=user.Name)) userId = localUser[0].Id c = Collaborator() c.User, c.Source = userId, source.Id try: return [self.collaboratorService.insert(c), userId] except InputError: collabs = self.collaboratorService.getAll(userId, source.Id) return [collabs[0].Id, userId] except KeyError: q = QSource(name=author['Source']['Name'], isModifiable=False) sources = self.sourceService.getAll(q=q) if not sources: raise Exception('Invalid source %s' % q.name) collabs = self.collaboratorService.getAll(userId=None, sourceId=sources[0].Id) if collabs: return [collabs[0].Id, None] else: c = Collaborator() c.Source = sources[0].Id return [self.collaboratorService.insert(c), None]
def _getCollaboratorForAuthor(self, author, source): ''' Returns a collaborator identifier for the user/source defined in the post. If the post was not created by a user it returns a collaborator for the source identified in the post and the default user. The default user should be the sync entry creator. If the source from the post does not exist locally raises Exception. @param author: dict The author data in JSON decoded format @param source: Source The source from which the blog synchronization is done @return: integer The collaborator identifier. ''' assert isinstance(source, Source) try: userJSON = author['User'] user = User() user.Name = sha1((userJSON.get('Name', '') + source.URI).encode( self.encodingType)).hexdigest() user.FirstName, user.LastName = userJSON.get('FirstName', ''), userJSON.get( 'LastName', '') user.EMail, user.Password = userJSON.get('EMail', ''), '*' user.Type = self.user_type_key try: userId = self.userService.insert(user) except InputError: localUser = self.userService.getAll(q=QUser(name=user.Name)) userId = localUser[0].Id c = Collaborator() c.User, c.Source = userId, source.Id try: return [self.collaboratorService.insert(c), userId] except InputError: collabs = self.collaboratorService.getAll(userId, source.Id) return [collabs[0].Id, userId] except KeyError: q = QSource(name=author['Source']['Name'], isModifiable=False) sources = self.sourceService.getAll(q=q) if not sources: raise Exception('Invalid source %s' % q.name) collabs = self.collaboratorService.getAll(userId=None, sourceId=sources[0].Id) if collabs: return [collabs[0].Id, None] else: c = Collaborator() c.Source = sources[0].Id return [self.collaboratorService.insert(c), None]
def _getCollaboratorForAuthor(self, author, creator, source): ''' Returns a collaborator identifier for the user/source defined in the post. If the post was not created by a user (it is twitter, facebook, etc. post) it returns a collaborator for the user that has added the post. @param author: dict The author data in JSON decoded format @param creator: dict The creator data in JSON decoded format @param source: Source The source from which the blog synchronization is done @return: integer The collaborator identifier. ''' assert isinstance(source, Source) user = User() isAuthor = False if 'User' in author: userJSON = author['User'] isAuthor = True else: userJSON = creator #To support old instances that don't have Uuid attribute if 'Uuid' in userJSON: user.Uuid = userJSON.get('Uuid', '') else: user.Uuid = str(uuid4().hex) if 'Cid' in userJSON: cid = int(userJSON.get('Cid', '')) else: cid = None user.Name = user.Uuid user.FirstName, user.LastName = userJSON.get('FirstName', ''), userJSON.get( 'LastName', '') user.Address, user.PhoneNumber = userJSON.get('Address', ''), userJSON.get( 'PhoneNumber', '') user.EMail, user.Password = userJSON.get('EMail', ''), '~' user.Type = self.user_type_key needUpdate = True try: userId = self.userService.insert(user) except InputError: localUser = self.userService.getByUuid(user.Uuid) userId = localUser.Id if localUser.Type == self.user_type_key and (cid is None or localUser.Cid < cid): user.Id = localUser.Id user.Type = localUser.Type user.Cid = cid self.userService.update(user) else: needUpdate = False collaborator = Collaborator() collaborator.User, collaborator.Source = userId, source.Id try: collaboratorId = self.collaboratorService.insert(collaborator) except InputError: collaborators = self.collaboratorService.getAll(userId, source.Id) collaboratorId = collaborators[0].Id if isAuthor: return [collaboratorId, userId, needUpdate, isAuthor] else: q = QSource(name=author['Source']['Name'], isModifiable=False) sources = self.sourceService.getAll(q=q) if not sources: raise Exception('Invalid source %s' % q.name) collaborators = self.collaboratorService.getAll( userId=None, sourceId=sources[0].Id) if collaborators: return [collaborators[0].Id, userId, needUpdate, isAuthor] else: collaborator = Collaborator() collaborator.Source = sources[0].Id return [ self.collaboratorService.insert(collaborator), userId, needUpdate, isAuthor ]
def addComment(self, blogId, comment): ''' @see: IBlogCommentService.addComment ''' # checking if the blog exists # checking whether comments are allowed shall be done in gateway if not self.session().query(exists().where(BlogMapped.Id == blogId)).scalar(): raise InputError(Ref(_('Specified blog does not exist'),)) userName = comment.UserName commentText = comment.CommentText commentSource = comment.CommentSource if comment.CommentSource else self.source_name_default # checking the necessary info: user name and comment text if not userName: raise InputError(Ref(_('No value for the mandatory UserName'),)) if not commentText: raise InputError(Ref(_('No value for the mandatory CommentText'),)) # take (or make) the user (for user name) part of creator and collaborator userTypeId, = self.session().query(UserTypeMapped.id).filter(UserTypeMapped.Key == self.user_type_key).one() try: sql = self.session().query(UserMapped.userId, UserMapped.Active) sql = sql.filter(UserMapped.typeId == userTypeId) sql = sql.filter(UserMapped.FirstName == userName) userId, isActive = sql.one() if not isActive: raise InputError(Ref(_('The commentator user was inactivated'),)) except: user = User() user.FirstName = userName user.LastName = self.user_last_name user.Name = self._freeCommentUserName() user.Password = binascii.b2a_hex(os.urandom(32)).decode() user.Type = self.user_type_key userId = self.userService.insert(user) # make the source (for inlet type) part of collaborator try: sql = self.session().query(SourceMapped.Id).join(SourceTypeMapped) sql = sql.filter(SourceTypeMapped.Key == self.source_type_key).filter(SourceMapped.Name == commentSource) sourceId, = sql.one() except NoResultFound: source = Source() source.Type = self.source_type_key source.Name = commentSource source.URI = '' source.IsModifiable = True sourceId = self.sourceService.insert(source) # make the collaborator sql = self.session().query(CollaboratorMapped.Id) sql = sql.filter(CollaboratorMapped.Source == sourceId) sql = sql.filter(CollaboratorMapped.User == userId) try: collabId, = sql.one() except NoResultFound: collab = Collaborator() collab.Source = sourceId collab.User = userId collabId = self.collaboratorService.insert(collab) # create post request post = Post() post.Type = self.post_type_key post.Creator = userId post.Author = collabId post.Content = commentText post.CreatedOn = datetime.now() # insert the blog post postId = self.blogPostService.insert(blogId, post) return postId
def _getCollaboratorForAuthor(self, author, creator, source): ''' Returns a collaborator identifier for the user/source defined in the post. If the post was not created by a user (it is twitter, facebook, etc. post) it returns a collaborator for the user that has added the post. @param author: dict The author data in JSON decoded format @param creator: dict The creator data in JSON decoded format @param source: Source The source from which the blog synchronization is done @return: integer The collaborator identifier. ''' assert isinstance(source, Source) user = User() isAuthor = False if 'User' in author: userJSON = author['User'] isAuthor = True else: userJSON = creator #To support old instances that don't have Uuid attribute if 'Uuid' in userJSON: user.Uuid = userJSON.get('Uuid', '') else: user.Uuid = str(uuid4().hex) if 'Cid' in userJSON: cid = int(userJSON.get('Cid', '')) else: cid = None user.Name = user.Uuid user.FirstName, user.LastName = userJSON.get('FirstName', ''), userJSON.get('LastName', '') user.Address, user.PhoneNumber = userJSON.get('Address', ''), userJSON.get('PhoneNumber', '') user.EMail, user.Password = userJSON.get('EMail', ''), '~' user.Type = self.user_type_key needUpdate = False try: userId = self.userService.insert(user) except InputError: localUser = self.userService.getByUuid(user.Uuid) userId = localUser.Id if localUser.Type == self.user_type_key and (cid is None or localUser.Cid < cid): needUpdate = True user.Id = localUser.Id user.Type = localUser.Type user.Cid = cid self.userService.update(user) collaborator = Collaborator() collaborator.User, collaborator.Source = userId, source.Id try: collaboratorId = self.collaboratorService.insert(collaborator) except InputError: collaborators = self.collaboratorService.getAll(userId, source.Id) collaboratorId = collaborators[0].Id if isAuthor: return [collaboratorId, userId, needUpdate, isAuthor] else: q = QSource(name=author['Source']['Name'], isModifiable=False) sources = self.sourceService.getAll(q=q) if not sources: raise Exception('Invalid source %s' % q.name) collaborators = self.collaboratorService.getAll(userId=None, sourceId=sources[0].Id) if collaborators: return [collaborators[0].Id, userId, needUpdate, isAuthor] else: collaborator = Collaborator() collaborator.Source = sources[0].Id return [self.collaboratorService.insert(collaborator), userId, needUpdate, isAuthor]
def pushMessage(self, typeKey, phoneNumber=None, messageText=None, timeStamp=None): ''' @see: IInletService.pushMessage ''' # checking the necessary info: phone number and message text if (phoneNumber is None) or (phoneNumber == ''): raise InputError(Ref(_('No value for the mandatory phoneNumber parameter'),)) if (messageText is None) or (messageText == ''): raise InputError(Ref(_('No value for the mandatory messageText parameter'),)) # take (or make) the user (for phone number) part of creator and collaborator try: userId, = self.session().query(PersonMapped.Id).filter(PersonMapped.PhoneNumber == phoneNumber).one() except: user = User() user.PhoneNumber = phoneNumber user.Name = self._freeSMSUserName() user.Password = binascii.b2a_hex(os.urandom(32)).decode() user.Type = self.user_type_key userId = self.userService.insert(user) # make the source (for inlet type) part of collaborator try: sql = self.session().query(SourceMapped.Id).join(SourceTypeMapped) sql = sql.filter(SourceTypeMapped.Key == self.sms_source_type_key).filter(SourceMapped.Name == typeKey) sourceId, = sql.one() except NoResultFound: source = Source() source.Type = self.sms_source_type_key source.Name = typeKey source.URI = '' source.IsModifiable = True sourceId = self.sourceService.insert(source) # make the collaborator sql = self.session().query(CollaboratorMapped.Id) sql = sql.filter(CollaboratorMapped.Source == sourceId) sql = sql.filter(CollaboratorMapped.User == userId) try: collabId, = sql.one() except NoResultFound: collab = Collaborator() collab.Source = sourceId collab.User = userId collabId = self.collaboratorService.insert(collab) # take / make time stamp if timeStamp: try: timeStamp = datetime.strptime(timeStamp, '%Y-%m-%d %H:%M:%S.%f') except: timeStamp = None if not timeStamp: timeStamp = datetime.now() # create post request post = Post() post.Type = self.sms_post_type_key post.Creator = userId post.Author = collabId post.Content = messageText post.CreatedOn = timeStamp # insert the post postId = self.postService.insert(post) return (self.postService.getById(postId),)
def pushMessage(self, typeKey, phoneNumber=None, messageText=None, timeStamp=None): ''' @see: IInletService.pushMessage ''' # checking the necessary info: phone number and message text if (phoneNumber is None) or (phoneNumber == ''): raise InputError( Ref(_('No value for the mandatory phoneNumber parameter'), )) if (messageText is None) or (messageText == ''): raise InputError( Ref(_('No value for the mandatory messageText parameter'), )) # take (or make) the user (for phone number) part of creator and collaborator try: userId, = self.session().query(PersonMapped.Id).filter( PersonMapped.PhoneNumber == phoneNumber).one() except: user = User() user.PhoneNumber = phoneNumber user.Name = self._freeSMSUserName() user.Password = binascii.b2a_hex(os.urandom(32)).decode() user.Type = self.user_type_key userId = self.userService.insert(user) # make the source (for inlet type) part of collaborator try: sql = self.session().query(SourceMapped.Id).join(SourceTypeMapped) sql = sql.filter( SourceTypeMapped.Key == self.sms_source_type_key).filter( SourceMapped.Name == typeKey) sourceId, = sql.one() except NoResultFound: source = Source() source.Type = self.sms_source_type_key source.Name = typeKey source.URI = '' source.IsModifiable = True sourceId = self.sourceService.insert(source) # make the collaborator sql = self.session().query(CollaboratorMapped.Id) sql = sql.filter(CollaboratorMapped.Source == sourceId) sql = sql.filter(CollaboratorMapped.User == userId) try: collabId, = sql.one() except NoResultFound: collab = Collaborator() collab.Source = sourceId collab.User = userId collabId = self.collaboratorService.insert(collab) # take / make time stamp if timeStamp: try: timeStamp = datetime.strptime(timeStamp, '%Y-%m-%d %H:%M:%S.%f') except: timeStamp = None if not timeStamp: timeStamp = datetime.now() # create post request post = Post() post.Type = self.sms_post_type_key post.Creator = userId post.Author = collabId post.Content = messageText post.CreatedOn = timeStamp # insert the post postId = self.postService.insert(post) return (self.postService.getById(postId), )
def addComment(self, blogId, comment): ''' @see: IBlogCommentService.addComment ''' # checking if the blog exists # checking whether comments are allowed shall be done in gateway if not self.session().query( exists().where(BlogMapped.Id == blogId)).scalar(): raise InputError(Ref(_('Specified blog does not exist'), )) userName = comment.UserName commentText = comment.CommentText commentSource = comment.CommentSource if comment.CommentSource else self.source_name_default # checking the necessary info: user name and comment text if not userName: raise InputError(Ref(_('No value for the mandatory UserName'), )) if not commentText: raise InputError(Ref( _('No value for the mandatory CommentText'), )) # take (or make) the user (for user name) part of creator and collaborator userTypeId, = self.session().query(UserTypeMapped.id).filter( UserTypeMapped.Key == self.user_type_key).one() try: sql = self.session().query(UserMapped.userId, UserMapped.Active) sql = sql.filter(UserMapped.typeId == userTypeId) sql = sql.filter(UserMapped.FirstName == userName) userId, isActive = sql.one() if not isActive: raise InputError( Ref(_('The commentator user was inactivated'), )) except: user = User() user.FirstName = userName user.LastName = self.user_last_name user.Name = self._freeCommentUserName() user.Password = binascii.b2a_hex(os.urandom(32)).decode() user.Type = self.user_type_key userId = self.userService.insert(user) # make the source (for inlet type) part of collaborator try: sql = self.session().query(SourceMapped.Id).join(SourceTypeMapped) sql = sql.filter( SourceTypeMapped.Key == self.source_type_key).filter( SourceMapped.Name == commentSource) sourceId, = sql.one() except NoResultFound: source = Source() source.Type = self.source_type_key source.Name = commentSource source.URI = '' source.IsModifiable = True sourceId = self.sourceService.insert(source) # make the collaborator sql = self.session().query(CollaboratorMapped.Id) sql = sql.filter(CollaboratorMapped.Source == sourceId) sql = sql.filter(CollaboratorMapped.User == userId) try: collabId, = sql.one() except NoResultFound: collab = Collaborator() collab.Source = sourceId collab.User = userId collabId = self.collaboratorService.insert(collab) # create post request post = Post() post.Type = self.post_type_key post.Creator = userId post.Author = collabId post.Content = commentText post.CreatedOn = datetime.now() # insert the blog post postId = self.blogPostService.insert(blogId, post) return postId