'Create a remote user with the email remote_user_email and return it'

def get_or_create_remote_user(self, remote_user_email):

    if (not self.app.config.use_remote_user):
        return None
    if getattr(self.app.config, 'normalize_remote_user_email', False):
        remote_user_email = remote_user_email.lower()
    user = self.sa_session.query(self.app.model.User).filter((self.app.model.User.table.c.email == remote_user_email)).first()
    if user:
        if (not self.app.security_agent.get_private_user_role(user)):
            self.app.security_agent.create_private_user_role(user)
        if (('webapp' not in self.environ) or (self.environ['webapp'] != 'tool_shed')):
            if (not user.default_permissions):
                self.app.security_agent.user_set_default_permissions(user)
                self.app.security_agent.user_set_default_permissions(user, history=True, dataset=True)
    elif (user is None):
        username = remote_user_email.split('@', 1)[0].lower()
        random.seed()
        user = self.app.model.User(email=remote_user_email)
        user.set_password_cleartext(''.join(random.sample((string.letters + string.digits), 12)))
        user.external = True
        for char in filter((lambda x: (x not in ((string.ascii_lowercase + string.digits) + '-'))), username):
            username = username.replace(char, '-')
        if self.sa_session.query(self.app.model.User).filter_by(username=username).first():
            i = 1
            while self.sa_session.query(self.app.model.User).filter_by(username=((username + '-') + str(i))).first():
                i += 1
            username += ('-' + str(i))
        user.username = username
        self.sa_session.add(user)
        self.sa_session.flush()
        self.app.security_agent.create_private_user_role(user)
        if (('webapp' not in self.environ) or (self.environ['webapp'] != 'tool_shed')):
            self.app.security_agent.user_set_default_permissions(user)
    return user
