Exemplo n.º 1
0
    def handler(self, request, path):
        if 'auto_authenticate' in request.session:
            username = request.session['auto_authenticate']
        else:
            if not request.post:
                return self.evaluate_form(session=request.session)
            username = request.post.get('username', '')
            password = request.post.get('password', '')
            if '' in (username, password):
                return self.evaluate_form(session=request.session)

        invalid_login = True
        u = None
        try:
            u = user.User(username)
            invalid_login = False
        except UnknownUserError as e:
            pass

        if 'auto_authenticate' in request.session:
            del request.session['auto_authenticate']
            request.session['change_password_hint'] = True
        else:
            try:
                if not u or not u.check_password(password):
                    return self.evaluate_form(
                        'Not a valid username and password combination')
            except NoMD5PasswordError as e:
                return self.evaluate_form(str(e))

            if invalid_login:
                return self.evaluate_form(
                    'Not a valid username and password combination')

        if not database_isuptodate():
            localvalues = {}
            request.session['upgrade_user'] = True
            base_url = options.url_path('base_url_submin')
            localvalues['base_url'] = str(base_url)
            localvalues['session_user'] = u
            return Response(evaluate('database_upgrade.html', localvalues))

        url = options.url_path('base_url_submin')
        if 'redirected_from' in request.session:
            login_url = options.url_path('base_url_submin') + 'login'
            url = request.session['redirected_from']
            if url.startswith(login_url):
                url = options.url_path('base_url_submin')

        session_user = u.session_object()
        session_user['is_authenticated'] = True
        request.session['user'] = session_user
        request.session.cleanup()

        return Redirect(url, request, store_url=False)
Exemplo n.º 2
0
	def handler(self, request, path):
		if 'auto_authenticate' in request.session:
			username = request.session['auto_authenticate']
		else:
			if not request.post:
				return self.evaluate_form(session=request.session)
			username = request.post.get('username', '')
			password = request.post.get('password', '')

		invalid_login = True
		u = None
		try:
			u = user.User(username)
			invalid_login = False
		except UnknownUserError as e:
			pass

		if 'auto_authenticate' in request.session:
			del request.session['auto_authenticate']
			request.session['change_password_hint'] = True
		else:
			try:
				if not u or not u.check_password(password):
					return self.evaluate_form('Not a valid username and password combination')
			except NoMD5PasswordError as e:
				return self.evaluate_form(str(e))

			if invalid_login:
				return self.evaluate_form('Not a valid username and password combination')

		if not database_isuptodate():
			localvalues = {}
			request.session['upgrade_user'] = True
			base_url = options.url_path('base_url_submin')
			localvalues['base_url'] = str(base_url)
			localvalues['session_user'] = u
			return Response(evaluate('database_upgrade.html', localvalues))

		url = options.url_path('base_url_submin')
		if 'redirected_from' in request.session:
			login_url = options.url_path('base_url_submin') + 'login'
			url = request.session['redirected_from']
			if url.startswith(login_url):
				url = options.url_path('base_url_submin')

		session_user = u.session_object()
		session_user['is_authenticated'] = True
		request.session['user'] = session_user
		request.session.cleanup()

		return Redirect(url, request, store_url=False)
Exemplo n.º 3
0
def upgrade_user_required(fun):
	"""Test if the upgrade_user is set (by the login view), otherwise
	redirect to login, or if the user is logged in, redirect to main url"""
	login_url = options.url_path('base_url_submin') + 'login'
	main_url = options.url_path('base_url_submin')

	def _decorator(self, *args, **kwargs):
		if 'upgrade_user' not in self.request.session:
			if 'user' in self.request.session:
				return Redirect(main_url, self.request)

			return Redirect(login_url, self.request)

		return fun(self, *args, **kwargs)
	return _decorator
Exemplo n.º 4
0
    def add(self, req, path, localvars):
        base_url = options.url_path('base_url_submin')
        groupname = ''

        if req.post and req.post['groupname']:
            import re

            groupname = req.post.get('groupname').strip().lower()
            if re.findall('[^a-zA-Z0-9_-]', groupname):
                return self.showAddForm(req, groupname,
                                        'Invalid characters in groupname')
            if groupname == '':
                return self.showAddForm(req, groupname,
                                        'Groupname not supplied')

            url = base_url + '/groups/show/' + groupname

            try:
                group.add(groupname)
            except IOError:
                return ErrorResponse('File permission denied', request=req)
            except GroupExistsError:
                return self.showAddForm(req, groupname,
                                        'Group %s already exists' % groupname)

            return Redirect(url, req)

        return self.showAddForm(req, groupname)
Exemplo n.º 5
0
	def __init__(self, environ):
		Request.__init__(self)
		self.__environ = environ

		if 'REQUEST_URI' in environ:
			self.url = environ['REQUEST_URI']
		else:
			self.url = environ['PATH_INFO']

		self.method = environ['REQUEST_METHOD']
		input = environ['wsgi.input']
		self.post = CGIFieldStorage(input, environ=environ, keep_blank_values=1)
		self.get = CGIGet(self.__environ['QUERY_STRING'])

		# Mimic CGI behaviour
		for key, value in self.get.variables.iteritems():
			self.post[key] = value

		if self.__environ.get('HTTP_COOKIE'):
			self._incookies.load(self.__environ.get('HTTP_COOKIE', ''))
		self.path_info = unicode(self.__environ.get('PATH_INFO', ''), 'utf-8')

		# When running from stand-alone WSGI-server, we have no Alias.
		# Instead, we can define part of the URL to be cut so we can
		# use e.g. /submin/ in front of the URL.
		if 'SUBMIN_REMOVE_BASE_URL' in environ:
			self.remove_base_url = True
			alias = options.url_path('base_url_submin')
			if self.path_info.startswith(alias):
				self.path_info = self.path_info[len(alias):]

		self.remote_address = self.__environ.get('REMOTE_ADDR')
Exemplo n.º 6
0
    def email_user(self, key=None, password=None, origin=None):
        """Email the user a key (to reset her password) OR a password (if the
		user followed a link with the key in it). The origin shows where the request
		came from (string)"""
        from submin.template.shortcuts import evaluate
        from submin.email import sendmail

        if key and password:
            raise ValueError('Ambiguous input: both key and password are set')

        templatevars = {
            'from': options.value('smtp_from', 'root@localhost'),
            'to': self.email,
            'username': self.name,
            'key': key,
            'password': password,
            'http_vhost': options.http_vhost(),
            'base_url': options.url_path("base_url_submin"),
            'origin': origin,
        }
        if key:
            template = 'email/prepare_reset.txt'
        else:
            template = 'email/reset_password.txt'

        message = evaluate(template, templatevars)
        sendmail(templatevars['from'], templatevars['to'], message)
Exemplo n.º 7
0
    def __init__(self, environ):
        Request.__init__(self)
        self.__environ = environ

        if 'REQUEST_URI' in environ:
            self.url = environ['REQUEST_URI']
        else:
            self.url = environ['PATH_INFO']

        self.method = environ['REQUEST_METHOD']
        input = environ['wsgi.input']
        self.post = CGIFieldStorage(input,
                                    environ=environ,
                                    keep_blank_values=1)
        self.get = CGIGet(self.__environ['QUERY_STRING'])

        # Mimic CGI behaviour
        for key, value in self.get.variables.items():
            self.post[key] = value

        if self.__environ.get('HTTP_COOKIE'):
            self._incookies.load(self.__environ.get('HTTP_COOKIE', ''))
        self.path_info = str(self.__environ.get('PATH_INFO', ''))

        # When running from stand-alone WSGI-server, we have no Alias.
        # Instead, we can define part of the URL to be cut so we can
        # use e.g. /submin/ in front of the URL.
        if 'SUBMIN_REMOVE_BASE_URL' in environ:
            self.remove_base_url = True
            alias = options.url_path('base_url_submin')
            if self.path_info.startswith(alias):
                self.path_info = self.path_info[len(alias):]

        self.remote_address = self.__environ.get('REMOTE_ADDR')
Exemplo n.º 8
0
	def add(self, req, path, localvars):
		base_url = options.url_path('base_url_submin')
		groupname = ''

		if req.post and req.post['groupname']:
			import re

			groupname = req.post.get('groupname').strip()
			if re.findall('[^a-zA-Z0-9_-]', groupname):
				return self.showAddForm(req, groupname, 'Invalid characters in groupname')
			if groupname == '':
				return self.showAddForm(req, groupname, 'Groupname not supplied')

			url = base_url + '/groups/show/' + groupname

			try:
				group.add(groupname)
			except IOError:
				return ErrorResponse('File permission denied', request=req)
			except GroupExistsError:
				return self.showAddForm(req, groupname, 'Group %s already exists' % groupname)

			return Redirect(url, req)

		return self.showAddForm(req, groupname)
Exemplo n.º 9
0
	def email_user(self, key=None, password=None, origin=None):
		"""Email the user a key (to reset her password) OR a password (if the
		user followed a link with the key in it). The origin shows where the request
		came from (string)"""
		from submin.template.shortcuts import evaluate
		from submin.email import sendmail
		
		if key and password:
			raise ValueError('Ambiguous input: both key and password are set')

		templatevars = {
			'from': options.value('smtp_from', 'root@localhost'),
			'to': self.email,
			'username': self.name,
			'key': key,
			'password': password,
			'http_vhost': options.http_vhost(),
			'base_url': options.url_path("base_url_submin"),
			'origin': origin,
		}
		if key:
			template = 'email/prepare_reset.txt'
		else:
			template = 'email/reset_password.txt'
		
		message = evaluate(template, templatevars)
		sendmail(templatevars['from'], templatevars['to'], message)
Exemplo n.º 10
0
def upgrade_user_required(fun):
    """Test if the upgrade_user is set (by the login view), otherwise
	redirect to login, or if the user is logged in, redirect to main url"""
    login_url = options.url_path('base_url_submin') + 'login'
    main_url = options.url_path('base_url_submin')

    def _decorator(self, *args, **kwargs):
        if 'upgrade_user' not in self.request.session:
            if 'user' in self.request.session:
                return Redirect(main_url, self.request)

            return Redirect(login_url, self.request)

        return fun(self, *args, **kwargs)

    return _decorator
Exemplo n.º 11
0
    def handler(self, req, path):
        localvars = {}

        if not req.session['user']['is_admin']:
            base_url = options.url_path('base_url_submin')
            username = req.session['user']['name']
            return Redirect(base_url + '/users/show/' + username, req)

        formatted = evaluate_main('intro.html', localvars, request=req)
        return Response(formatted)
Exemplo n.º 12
0
	def evaluate_form(self, msg='', session=None):
		localvalues = {}
		localvalues['msg'] = msg
		localvalues['base_url'] = options.url_path('base_url_submin')
		if session and 'user' in session and 'is_authenticated' in session['user']:
			if session['user']['is_authenticated']:
				localvalues['is_authenticated'] = True
				localvalues['username'] = session['user']['name']

		return Response(evaluate('login.html', localvalues))
Exemplo n.º 13
0
	def handler(self, req, path):
		localvars = {}

		if not req.session['user']['is_admin']:
			base_url = options.url_path('base_url_submin')
			username = req.session['user']['name']
			return Redirect(base_url + '/users/show/' + username, req)

		formatted = evaluate_main('intro.html', localvars, request=req)
		return Response(formatted)
Exemplo n.º 14
0
    def add(self, req, path, localvars):
        import re

        base_url = options.url_path('base_url_submin')
        username = ''
        email = ''
        fullname = ''

        if not req.post or not req.post['username'] \
            or not req.post['email']    \
            or not req.post['fullname']:
            return self.showAddForm(req, username, email, fullname)

        username = req.post.get('username').strip()
        email = req.post.get('email').strip()
        fullname = req.post.get('fullname').strip()
        send_mail = 'send_password' in req.post

        # check these before we add the user, the rest is checked when adding
        try:
            validators.validate_email(email)
            validators.validate_fullname(fullname)
        except validators.InvalidEmail:
            return self.showAddForm(req, username, email, fullname,
                                    'Email is not valid')
        except validators.InvalidFullname:
            return self.showAddForm(req, username, email, fullname,
                                    'Invalid characters in full name')

        if username == '':
            return self.showAddForm(req, username, email, fullname,
                                    'Username not supplied')

        if email == '':
            return self.showAddForm(req, username, email, fullname,
                                    'Email must be supplied')

        try:
            u = user.add(username,
                         email,
                         send_mail=send_mail,
                         origin=req.remote_address)
            u.fullname = fullname
        except IOError:
            return ErrorResponse('File permission denied', request=req)
        except UserExistsError:
            return self.showAddForm(req, username, email, fullname,
                                    'User %s already exists' % username)
        except validators.InvalidUsername:
            return self.showAddForm(req, username, email, fullname,
                                    'Invalid characters in username')

        url = base_url + '/users/show/' + username
        return Redirect(url, req)
Exemplo n.º 15
0
    def updateCookie(self):
        base_url = str(options.url_path('base_url_submin'))
        http = 'http://'
        if http in base_url:
            try:
                base_url = base_url[base_url.index('/', len(http)):]
            except ValueError:
                # ok, this is weird, apparently, base_url is just a hostname
                # assume virtual_host specifically for submin
                base_url = '/'

        self.request.setCookie('SubminSessionID', self.sessionid, \
         str(base_url), expires=rfc822.formatdate(self.expires))
Exemplo n.º 16
0
def login_required(fun):
    login_url = options.url_path('base_url_submin') + 'login'

    def _decorator(self, *args, **kwargs):
        if 'user' not in self.request.session:
            return Redirect(login_url, self.request)

        if not self.request.session['user']['is_authenticated']:
            return Redirect(login_url, self.request)

        return fun(self, *args, **kwargs)

    return _decorator
Exemplo n.º 17
0
def login_required(fun):
	login_url = options.url_path('base_url_submin') + 'login'

	def _decorator(self, *args, **kwargs):
		if 'user' not in self.request.session:
			return Redirect(login_url, self.request)

		if not self.request.session['user']['is_authenticated']:
			return Redirect(login_url, self.request)

		return fun(self, *args, **kwargs)

	return _decorator
Exemplo n.º 18
0
def setCommitEmailHook(reponame, enable):
    prepare(reponame)

    reposdir = repository.directory('git', reponame)
    hook_dir = reposdir + 'hooks' + 'post-receive.d'
    mkdirs(hook_dir)
    hook_dest = hook_dir + '001-commit-email.hook'

    if enable:
        variables = {
            'submin_lib_dir': options.lib_path(),
            'base_url': options.url_path('base_url_submin'),
            'http_vhost': options.http_vhost(),
            'hook_version': HOOK_VERSIONS['commit-email'],
        }
        hook = evaluate('plugins/vcs/git/post-receive', variables)
        try:
            os.unlink(hook_dest)
        except OSError as e:
            if e.errno != errno.ENOENT:
                raise

        try:
            with file(hook_dest, 'w') as f:
                f.write(hook)

            os.chmod(hook_dest, 0o755)
        except OSError as e:
            raise repository.PermissionError("Enabling hook failed: %s" %
                                             (str(e), ))
        try:
            cfg = repository.directory('git', reponame) + 'config'
            email = options.value(
                'commit_email_from',
                'Please configure commit_email_from <*****@*****.**>')

            set_git_config(cfg, 'multimailhook.emailmaxlines', '2000')
            prefix = '[%s]' % reponame
            set_git_config(cfg, 'multimailhook.emailprefix', prefix)
            set_git_config(cfg, 'multimailhook.envelopesender', email)
        except SetGitConfigError as e:
            raise repository.PermissionError(
                "Enabling hook succeeded, but configuring it failed: %s" %
                (str(e)))
    else:
        try:
            os.unlink(hook_dest)
        except OSError as e:
            if e.errno != errno.ENOENT:
                raise repository.PermissionError("Removing hook failed: %s" %
                                                 (str(e), ))
Exemplo n.º 19
0
	def add(self, req, path, localvars):
		import re

		base_url = options.url_path('base_url_submin')
		username = ''
		email = ''
		fullname = ''

		if not req.post or not req.post['username'] \
						or not req.post['email']    \
						or not req.post['fullname']:
			return self.showAddForm(req, username, email, fullname)

		username = req.post.get('username').strip()
		email = req.post.get('email').strip()
		fullname = req.post.get('fullname').strip()
		send_mail = 'send_password' in req.post

		# check these before we add the user, the rest is checked when adding
		try:
			validators.validate_email(email)
			validators.validate_fullname(fullname)
		except validators.InvalidEmail:
			return self.showAddForm(req, username, email, fullname,
				'Email is not valid')
		except validators.InvalidFullname:
			return self.showAddForm(req, username, email, fullname,
				'Invalid characters in full name')

		if username == '':
			return self.showAddForm(req, username, email, fullname,
				'Username not supplied')

		if email == '':
			return self.showAddForm(req, username, email, fullname,
				'Email must be supplied')

		try:
			u = user.add(username, email, send_mail=send_mail, origin=req.remote_address)
			u.fullname = fullname
		except IOError:
			return ErrorResponse('File permission denied', request=req)
		except UserExistsError:
			return self.showAddForm(req, username, email, fullname,
				'User %s already exists' % username)
		except validators.InvalidUsername:
			return self.showAddForm(req, username, email, fullname,
				'Invalid characters in username')

		url = base_url + '/users/show/' + username
		return Redirect(url, req)
Exemplo n.º 20
0
def setCommitEmailHook(reponame, enable):
	prepare(reponame)

	reposdir = repository.directory('git', reponame)
	hook_dir = reposdir + 'hooks' + 'post-receive.d'
	mkdirs(hook_dir)
	hook_dest = hook_dir + '001-commit-email.hook'

	if enable:
		variables = {
			'submin_lib_dir': options.lib_path(),
			'base_url': options.url_path('base_url_submin'),
			'http_vhost': options.http_vhost(),
			'hook_version': HOOK_VERSIONS['commit-email'],
		}
		hook = evaluate('plugins/vcs/git/post-receive', variables)
		try:
			os.unlink(hook_dest)
		except OSError as e:
			if e.errno != errno.ENOENT:
				raise

		try:
			with file(hook_dest, 'w') as f:
				f.write(hook)

			os.chmod(hook_dest, 0o755)
		except OSError as e:
			raise repository.PermissionError(
				"Enabling hook failed: %s" % (str(e),))
		try:
			cfg = repository.directory('git', reponame) + 'config'
			email = options.value('commit_email_from',
				'Please configure commit_email_from <*****@*****.**>')

			set_git_config(cfg, 'multimailhook.emailmaxlines', '2000')
			prefix = '[%s]' % reponame
			set_git_config(cfg, 'multimailhook.emailprefix', prefix)
			set_git_config(cfg, 'multimailhook.envelopesender', email)
		except SetGitConfigError as e:
			raise repository.PermissionError(
				"Enabling hook succeeded, but configuring it failed: %s" %
				(str(e)))
	else:
		try:
			os.unlink(hook_dest)
		except OSError as e:
			if e.errno != errno.ENOENT:
				raise repository.PermissionError(
					"Removing hook failed: %s" % (str(e),))
Exemplo n.º 21
0
def evaluate_main(templatename, templatevariables={}, request=None):
	templatevariables['main_include'] = templatename

	is_admin = False
	session_user = None
	if not request or 'user' not in request.session:
		raise UnknownUserError

	session_user = User(request.session['user']['name'])

	templatevariables['main_base_url'] = str(options.url_path('base_url_submin'))
	templatevariables['session_user'] = session_user

	return evaluate('main.html', templatevariables)
Exemplo n.º 22
0
    def updateCookie(self):
        base_url = str(options.url_path("base_url_submin"))
        http = "http://"
        if http in base_url:
            try:
                base_url = base_url[base_url.index("/", len(http)) :]
            except ValueError:
                # ok, this is weird, apparently, base_url is just a hostname
                # assume virtual_host specifically for submin
                base_url = "/"

        self.request.setCookie(
            "SubminSessionID", self.sessionid, str(base_url), expires=rfc822.formatdate(self.expires)
        )
Exemplo n.º 23
0
    def subcmd_hook(self, argv):
        """This is hidden from help because it is not meant to be run, except
		from commit/receive hooks
		"""
        from submin.path.path import Path
        from submin.models import hookjobs
        from submin.models import options
        from submin.subminadmin import trac
        #import urllib2
        from urllib import request, error

        if argv[0] != 'queue' or len(argv) != 4:
            print('Unknown command')
            return

        vcs_type, repository, hooktype = argv[1:]
        content = ''.join(sys.stdin.readlines())
        print('Notifying Trac of changes...')
        if hooktype == 'trac-sync' and 'refs/tags' in content:
            print('Skipping tag (no sync needed)')
            return

        hookjobs.queue(vcs_type, repository, hooktype, content)

        baseurl = Path(options.http_vhost() +
                       options.url_path('base_url_submin'))
        joburl = str(baseurl + 'hooks' + hooktype + vcs_type + repository)

        try:
            response = urllib2.urlopen(joburl)
        except urllib2.HTTPError as e:
            print('Job queued, but could not sync to "%s", HTTP error %u' % (
                joburl,
                e.code,
            ))
        except urllib2.URLError as e:
            print('Job queued, but URL invalid %s: %s' % (joburl, str(e)))
        else:
            xml = response.read()
            if 'success="True"' not in xml:
                print('Failed to sync:\n%s' % xml)
            # TODO: don't process XML with regexps...
            messages = re.sub('.*<errormsgs>(.*)</errormsgs>.*',
                              '\\1',
                              xml,
                              flags=re.DOTALL)
            messages = re.sub('<msg>(.*)</msg>', '\\1\n', messages)
            if "" != messages:
                print('WARNING: Synced, but got some messages:\n%s' % messages)
Exemplo n.º 24
0
	def handler(self, req, path):
		# we only handle ajax requests
		if not req.is_ajax():
			return Redirect(options.url_path('base_url_submin'), req)

		if 'listAll' in req.post:
			return self.listAll(req)
		if 'listUsers' in req.post:
			return self.listUsers(req)
		if 'listGroups' in req.post:
			return self.listGroups(req)
		if 'listRepositories' in req.post:
			return self.listRepositories(req)

		return XMLStatusResponse('', False, 'Unknown command')
Exemplo n.º 25
0
	def send_email(self, req, path):
		templatevars = { 'base_url': options.url_path('base_url_submin') }
		username = req.post.get('username', '')
		if username:
			try:
				u = user.User(username)
				u.prepare_password_reset(req.remote_address)
				templatevars['sent'] = True
			except UnknownUserError:
				templatevars['sent'] = True
		else:
			templatevars['form'] = True

		formatted = evaluate('password.html', templatevars)
		return Response(formatted)
Exemplo n.º 26
0
    def add(self, req, path, templatevars):
        base_url = options.url_path('base_url_submin')
        reposname = ''

        if req.post and req.post['repository']:
            import re

            reposname = req.post.get('repository').strip()
            if re.findall('[^a-zA-Z0-9_-]', reposname):
                return self.showAddForm(
                    req, reposname, 'Invalid characters in repository name')

            if "vcs" not in req.post or req.post.get("vcs").strip() == "":
                return self.showAddForm(
                    req, reposname,
                    "No repository type selected. Please select a repository type."
                )

            vcs_type = req.post.get("vcs").strip()

            if reposname == '':
                return self.showAddForm(req, reposname,
                                        'Repository name not supplied')

            if vcs_type not in vcs_list():
                return self.showAddForm(req, reposname,
                                        "Invalid repository type supplied.")

            try:
                a = Repository(reposname, vcs_type)
                return self.showAddForm(
                    req, reposname, 'Repository %s already exists' % reposname)
            except DoesNotExistError:
                pass

            try:
                asking_user = user.User(req.session['user']['name'])
                Repository.add(vcs_type, reposname, asking_user)
            except PermissionError as e:
                return ErrorResponse('could not create repository',
                                     request=req,
                                     details=str(e))

            url = '%s/repositories/show/%s/%s' % (base_url, vcs_type,
                                                  reposname)
            return Redirect(url, req)

        return self.showAddForm(req, reposname)
Exemplo n.º 27
0
    def show(self, req, vcs_type, path, templatevars):
        import os.path

        u = user.User(req.session['user']['name'])
        try:
            repos = Repository(path[0], vcs_type)

            # Lie if user has no permission to read
            if not u.is_admin and not repository.userHasReadPermissions(
                    u.name, path[0], vcs_type):
                raise DoesNotExistError
        except DoesNotExistError:
            return ErrorResponse('This repository does not exist.',
                                 request=req)

        trac_enabled = options.value('enabled_trac', 'no') != 'no'

        if trac_enabled:
            templatevars['trac_config_ok'] = True
            templatevars['trac_exists'] = False
            try:
                if trac.exists(path[0]):
                    templatevars['trac_exists'] = True
            except MissingConfig as e:
                templatevars['trac_config_ok'] = False
                templatevars['trac_msg'] = \
                 'There is something missing in your config: %s' % str(e)

            trac_base_url = options.url_path('base_url_trac')
            trac_http_url = str(trac_base_url + repos.name)
            templatevars['trac_http_url'] = trac_http_url

        try:
            vcs_url = repos.url()
        except MissingConfig as e:
            vcs_url = ""
            templatevars['vcs_url_error'] = str(e)

        templatevars['vcs_url'] = vcs_url
        templatevars['repository'] = repos
        templatevars['vcs_type'] = vcs_type
        formatted = evaluate_main('repositories.html',
                                  templatevars,
                                  request=req)
        return Response(formatted)
Exemplo n.º 28
0
	def subcmd_hook(self, argv):
		"""This is hidden from help because it is not meant to be run, except
		from commit/receive hooks
		"""
		from submin.path.path import Path
		from submin.models import hookjobs
		from submin.models import options
		from submin.subminadmin import trac
		import urllib2

		if argv[0] != 'queue' or len(argv) != 4:
			print 'Unknown command'
			return

		vcs_type, repository, hooktype = argv[1:]
		content = ''.join(sys.stdin.readlines())
		print 'Notifying Trac of changes...'
		if hooktype == 'trac-sync' and 'refs/tags' in content:
			print('Skipping tag (no sync needed)')
			return

		hookjobs.queue(vcs_type, repository, hooktype, content)

		baseurl = Path(options.http_vhost()
					+ options.url_path('base_url_submin'))
		joburl = str(baseurl + 'hooks' + hooktype + vcs_type + repository)

		try:
			response = urllib2.urlopen(joburl)
		except urllib2.HTTPError as e:
			print('Job queued, but could not sync to "%s", HTTP error %u' %
				(joburl, e.code, ))
		except urllib2.URLError as e:
			print('Job queued, but URL invalid %s: %s' %
				(joburl, str(e)))
		else:
			xml = response.read()
			if 'success="True"' not in xml:
				print('Failed to sync:\n%s' % xml)
			# TODO: don't process XML with regexps...
			messages = re.sub('.*<errormsgs>(.*)</errormsgs>.*', '\\1', xml, flags=re.DOTALL)
			messages = re.sub('<msg>(.*)</msg>', '\\1\n', messages)
			if "" != messages:
				print('WARNING: Synced, but got some messages:\n%s' % messages)
Exemplo n.º 29
0
	def reset_password(self, req, username, key):
		templatevars = { 'base_url': options.url_path('base_url_submin') }
		if 'auto_authenticate' in req.session:
			del req.session['auto_authenticate']

		try:
			u = user.User(username)
		except UnknownUserError:
			raise

		if not u.valid_password_reset_key(key):
			templatevars['invalid'] = True
		else:
			templatevars['reset'] = True
			req.session['auto_authenticate'] = username
			u.clear_password_reset_key()

		formatted = evaluate('password.html', templatevars)
		return Response(formatted)
Exemplo n.º 30
0
	def show(self, req, vcs_type, path, templatevars):
		import os.path

		u = user.User(req.session['user']['name'])
		try:
			repos = Repository(path[0], vcs_type)

			# Lie if user has no permission to read
			if not u.is_admin and not repository.userHasReadPermissions(u.name, path[0], vcs_type):
				raise DoesNotExistError
		except DoesNotExistError:
			return ErrorResponse('This repository does not exist.', request=req)

		trac_enabled = options.value('enabled_trac', 'no') != 'no'

		if trac_enabled:
			templatevars['trac_config_ok'] = True
			templatevars['trac_exists'] = False
			try:
				if trac.exists(path[0]):
					templatevars['trac_exists'] = True
			except MissingConfig as e:
				templatevars['trac_config_ok'] = False
				templatevars['trac_msg'] = \
					'There is something missing in your config: %s' % str(e)

			trac_base_url = options.url_path('base_url_trac')
			trac_http_url = str(trac_base_url + repos.name)
			templatevars['trac_http_url'] = trac_http_url

		try:
			vcs_url = repos.url()
		except MissingConfig as e:
			vcs_url = ""
			templatevars['vcs_url_error'] = str(e)

		templatevars['vcs_url'] = vcs_url
		templatevars['repository'] = repos
		templatevars['vcs_type'] = vcs_type
		formatted = evaluate_main('repositories.html', templatevars, request=req)
		return Response(formatted)
Exemplo n.º 31
0
	def add(self, req, path, templatevars):
		base_url = options.url_path('base_url_submin')
		reposname = ''

		if req.post and req.post['repository']:
			import re, commands

			reposname = req.post.get('repository').strip()
			if re.findall('[^a-zA-Z0-9_-]', reposname):
				return self.showAddForm(req, reposname, 'Invalid characters in repository name')

			if "vcs" not in req.post or req.post.get("vcs").strip() == "":
				return self.showAddForm(req, reposname, "No repository type selected. Please select a repository type.")

			vcs_type = req.post.get("vcs").strip()

			if reposname == '':
				return self.showAddForm(req, reposname, 'Repository name not supplied')

			if vcs_type not in vcs_list():
				return self.showAddForm(req, reposname, "Invalid repository type supplied.")

			try:
				a = Repository(reposname, vcs_type)
				return self.showAddForm(req, reposname, 'Repository %s already exists' % reposname)
			except DoesNotExistError:
				pass

			try:
				asking_user = user.User(req.session['user']['name'])
				Repository.add(vcs_type, reposname, asking_user)
			except PermissionError as e:
				return ErrorResponse('could not create repository',
					request=req, details=str(e))

			url = '%s/repositories/show/%s/%s' % (base_url, vcs_type,
					reposname)
			return Redirect(url, req)

		return self.showAddForm(req, reposname)
Exemplo n.º 32
0
    def handler(self, req, path):
        localvars = {}

        if req.is_ajax():
            return self.ajaxhandler(req, path)

        if len(path) < 1:
            return ErrorResponse('Invalid path', request=req)

        if len(path) > 0:
            localvars['selected_type'] = 'users'
        if len(path) > 1:
            localvars['selected_object'] = path[1]

        try:
            if path[0] == 'show':
                return self.show(req, path[1:], localvars)
            if path[0] == 'add':
                return self.add(req, path[1:], localvars)
        except Unauthorized:
            return Redirect(options.url_path('base_url_submin'), req)

        return ErrorResponse('Unknown path', request=req)
Exemplo n.º 33
0
def evaluate_main(templatename, templatevariables={}, request=None):
    templatevariables['main_include'] = templatename

    is_admin = False
    session_user = None
    if not request or 'user' not in request.session:
        raise UnknownUserError

    session_user = User(request.session['user']['name'])

    templatevariables['main_base_url'] = str(
        options.url_path('base_url_submin'))
    templatevariables['session_user'] = session_user
    templatevariables['users_exp_col'] = request.getCookie(
        'usersExpCol', 'collapsed')
    templatevariables['groups_exp_col'] = request.getCookie(
        'groupsExpCol', 'collapsed')
    templatevariables['repositories_exp_col'] = request.getCookie(
        'repositoriesExpCol', 'collapsed')
    templatevariables['enabled_external'] = options.value(
        'enabled_external', 'no') != 'no'

    return evaluate('main.html', templatevariables)
Exemplo n.º 34
0
	def handler(self, req, path):
		localvars = {}

		if req.is_ajax():
			return self.ajaxhandler(req, path)

		if len(path) < 1:
			return ErrorResponse('Invalid path', request=req)

		if len(path) > 0:
			localvars['selected_type'] = 'groups'
		if len(path) > 1:
			localvars['selected_object'] = path[1]

		try:
			if path[0] == 'show':
				return self.show(req, path[1:], localvars)
			if path[0] == 'add':
				return self.add(req, path[1:], localvars)
		except Unauthorized:
			return Redirect(options.url_path('base_url_submin'), req)

		return ErrorResponse('Unknown path', request=req)
Exemplo n.º 35
0
def have_trac_sync_access():
	baseurl = Path(options.http_vhost() + options.url_path('base_url_submin'))
	# because we don't specify a full path, this will never succeed, but
	# it will set the 'inacl' attribute to True/False
	joburl = str(baseurl + 'hooks' + 'trac-sync')

	try:
		response = urllib2.urlopen(joburl, timeout=2)
	except urllib2.HTTPError as e:
		raise SyncError('HTTP error: %s' % str(e))
	except urllib2.URLError as e:
		raise SyncError('URL invalid %u: %s' % (e.reason[0], e.reason[1]))
	except socket.timeout as e:
		raise SyncError('Timeout: are we running a single-threaded server?')

	root = ET.fromstring(response.read())
	command = root.find('./command')
	if command is None:
		raise SyncError(root)

	if 'inacl' not in command.attrib or command.attrib['inacl'].lower() == 'false':
		msgnodes = root.findall('./command/errormsgs/msg')
		raise SyncError('\n'.join([x.text for x in msgnodes]))
Exemplo n.º 36
0
def have_trac_sync_access():
    baseurl = Path(options.http_vhost() + options.url_path('base_url_submin'))
    # because we don't specify a full path, this will never succeed, but
    # it will set the 'inacl' attribute to True/False
    joburl = str(baseurl + 'hooks' + 'trac-sync')

    try:
        response = urllib2.urlopen(joburl, timeout=2)
    except urllib2.HTTPError as e:
        raise SyncError('HTTP error: %s' % str(e))
    except urllib2.URLError as e:
        raise SyncError('URL invalid %u: %s' % (e.reason[0], e.reason[1]))
    except socket.timeout as e:
        raise SyncError('Timeout: are we running a single-threaded server?')

    root = ET.fromstring(response.read())
    command = root.find('./command')
    if command is None:
        raise SyncError(root)

    if 'inacl' not in command.attrib or command.attrib['inacl'].lower(
    ) == 'false':
        msgnodes = root.findall('./command/errormsgs/msg')
        raise SyncError('\n'.join([x.text for x in msgnodes]))
Exemplo n.º 37
0
def url(reposname):
	try:
		return str(options.url_path('base_url_svn') + reposname)
	except UnknownKeyError as e:
		raise MissingConfig('Please make sure base_url_svn is set in config')
Exemplo n.º 38
0
def diagnostics():
    results = {}
    results['enabled_trac'] = options.value('enabled_trac', 'no') != 'no'

    if not results['enabled_trac']:
        results['enabled_trac_label'] = 'disabled'
        results['trac_all_label'] = 'disabled'
        return results

    results['installed_trac'] = trac.has_trac_admin()

    results['trac_acl_hook'] = options.value('acl_hook', '') != ''
    results['trac_acl_hook_recommendation'] = ', '.join(generate_acl_list())
    results['trac_sync_access'] = True
    try:
        have_trac_sync_access()
    except SyncError as e:
        results['trac_sync_access'] = False
        results['trac_sync_access_msg'] = str(e)

    # don't check for existence, submin creates it as needed
    try:
        trac_dir = options.env_path('trac_dir')
    except UnknownKeyError:
        results['trac_dir_set'] = False
    else:
        results['trac_dir_set'] = True
        results['trac_dir'] = trac_dir

        envs = list(missing_config_envs(trac_dir))

        missing_config = [{
            'trac_env': x[0],
            'missing_configs': x[2]
        } for x in envs if x[1]]
        results['trac_envs_missing_config'] = missing_config
        results['trac_envs_complete'] = 0 == len(missing_config)

        # pre-fill label because add_labels cannot deal with this granularity
        for env in missing_config:
            for section in env['missing_configs']:
                for option in env['missing_configs'][section]:
                    if option['fatal']:
                        results['trac_envs_complete_label'] = 'fail'
                        break
                    results['trac_envs_complete_label'] = 'warn'

        orphaned = [x[0] for x in envs if not x[1]]
        results['trac_envs_orphaned'] = orphaned
        results['trac_envs_all_connected'] = 0 == len(orphaned)

    try:
        htpasswd_file = options.env_path("htpasswd_file")
        results['trac_htpasswd_file'] = htpasswd_file
        results['trac_htpasswd_dir_exists'] = os.path.exists(
            htpasswd_file.dirname())
        results['trac_htpasswd_dir'] = htpasswd_file.dirname()
    except UnknownKeyError:
        results['trac_htpasswd_file'] = ""

    results['trac_base_url'] = options.url_path('base_url_trac')

    return add_labels(results, 'trac_all', warnings, fails)
Exemplo n.º 39
0
	def _set_footer():
		git_multimail.FOOTER_TEMPLATE = FOOTER_TEMPLATE.format(
			http_vhost=options.http_vhost(),
			base_url=options.url_path("base_url_submin"),
		)
		git_multimail.REVISION_FOOTER_TEMPLATE = git_multimail.FOOTER_TEMPLATE
Exemplo n.º 40
0
 def _getfilename(self):
     if self.destroyed():
         raise SessionDestroyedError
     suffix = md5(str(options.url_path('base_url_submin'))).hexdigest()
     return '/tmp/sm-sess%s-%s' % (self.sessionid, suffix)
Exemplo n.º 41
0
 def _getfilename(self):
     if self.destroyed():
         raise SessionDestroyedError
     suffix = md5(str(options.url_path("base_url_submin"))).hexdigest()
     return "/tmp/sm-sess%s-%s" % (self.sessionid, suffix)
Exemplo n.º 42
0
def url(reposname):
	try:
		return str(options.url_path('base_url_svn') + reposname)
	except UnknownKeyError as e:
		raise MissingConfig('Please make sure base_url_svn is set in config')
Exemplo n.º 43
0
	def handler(self, request, path):
		if 'user' in request.session:
			request.session['user']['is_authenticated'] = False
		request.session.clear()
		url = options.url_path('base_url_submin')
		return Redirect(url, request)
Exemplo n.º 44
0
def diagnostics():
	results = {}
	results['enabled_trac'] = options.value('enabled_trac', 'no') != 'no'

	if not results['enabled_trac']:
		results['enabled_trac_label'] = 'disabled'
		results['trac_all_label'] = 'disabled'
		return results

	results['installed_trac'] = trac.has_trac_admin()

	results['trac_acl_hook'] = options.value('acl_hook', '') != ''
	results['trac_acl_hook_recommendation'] = ', '.join(generate_acl_list())
	results['trac_sync_access'] = True
	try:
		have_trac_sync_access()
	except SyncError as e:
		results['trac_sync_access'] = False
		results['trac_sync_access_msg' ] = str(e)

	# don't check for existence, submin creates it as needed
	try:
		trac_dir = options.env_path('trac_dir')
	except UnknownKeyError:
		results['trac_dir_set'] = False
	else:
		results['trac_dir_set'] = True
		results['trac_dir'] = trac_dir

		envs = list(missing_config_envs(trac_dir))

		missing_config = [
			{'trac_env': x[0], 'missing_configs': x[2]} for x in envs if x[1]
		]
		results['trac_envs_missing_config'] = missing_config
		results['trac_envs_complete'] = 0 == len(missing_config)

		# pre-fill label because add_labels cannot deal with this granularity
		for env in missing_config:
			for section in env['missing_configs']:
				for option in env['missing_configs'][section]:
					if option['fatal']:
						results['trac_envs_complete_label'] = 'fail'
						break
					results['trac_envs_complete_label'] = 'warn'

		orphaned = [x[0] for x in envs if not x[1]]
		results['trac_envs_orphaned'] = orphaned
		results['trac_envs_all_connected'] = 0 == len(orphaned)

	try:
		htpasswd_file = options.env_path("htpasswd_file")
		results['trac_htpasswd_file'] = htpasswd_file
		results['trac_htpasswd_dir_exists'] = os.path.exists(htpasswd_file.dirname())
		results['trac_htpasswd_dir'] = htpasswd_file.dirname()
	except UnknownKeyError:
		results['trac_htpasswd_file'] = ""

	results['trac_base_url'] = options.url_path('base_url_trac')
	
	return add_labels(results, 'trac_all', warnings, fails)