From 904ded296973c591da04c4d0183ae23c986f1973 Mon Sep 17 00:00:00 2001 From: Mike McGrath Date: Sat, 15 Mar 2008 17:58:30 -0500 Subject: [PATCH 1/2] added initial theme stuff --- fas/build/lib/fas/__init__.py | 30 + fas/build/lib/fas/auth.py | 218 ++++++ fas/build/lib/fas/cla.py | 120 ++++ fas/build/lib/fas/commands.py | 51 ++ fas/build/lib/fas/config/__init__.py | 0 fas/build/lib/fas/config/log.cfg | 29 + fas/build/lib/fas/controllers.py | 145 ++++ fas/build/lib/fas/feeds.py | 17 + fas/build/lib/fas/group.py | 532 ++++++++++++++ fas/build/lib/fas/help.py | 50 ++ fas/build/lib/fas/json_request.py | 73 ++ fas/build/lib/fas/model.py | 470 +++++++++++++ fas/build/lib/fas/openid_fas.py | 112 +++ fas/build/lib/fas/openssl_fas.py | 82 +++ fas/build/lib/fas/release.py | 18 + fas/build/lib/fas/safasprovider.py | 219 ++++++ fas/build/lib/fas/templates/__init__.py | 0 fas/build/lib/fas/templates/about.html | 17 + fas/build/lib/fas/templates/cla/__init__.py | 0 fas/build/lib/fas/templates/cla/cla.html | 82 +++ fas/build/lib/fas/templates/cla/cla.txt | 145 ++++ fas/build/lib/fas/templates/cla/index.html | 26 + fas/build/lib/fas/templates/error.html | 25 + fas/build/lib/fas/templates/group/__init__.py | 0 fas/build/lib/fas/templates/group/dump.txt | 3 + fas/build/lib/fas/templates/group/edit.html | 55 ++ fas/build/lib/fas/templates/group/invite.html | 43 ++ fas/build/lib/fas/templates/group/list.html | 54 ++ fas/build/lib/fas/templates/group/new.html | 57 ++ fas/build/lib/fas/templates/group/view.html | 123 ++++ fas/build/lib/fas/templates/help.html | 12 + fas/build/lib/fas/templates/home.html | 33 + fas/build/lib/fas/templates/login.html | 33 + fas/build/lib/fas/templates/master.html | 104 +++ .../lib/fas/templates/openid/__init__.py | 0 fas/build/lib/fas/templates/openid/about.html | 15 + fas/build/lib/fas/templates/openid/auth.txt | 1 + fas/build/lib/fas/templates/openid/id.html | 21 + .../lib/fas/templates/openid/trusted.html | 20 + fas/build/lib/fas/templates/user/__init__.py | 0 fas/build/lib/fas/templates/user/cert.txt | 2 + .../lib/fas/templates/user/changepass.html | 20 + fas/build/lib/fas/templates/user/edit.html | 88 +++ fas/build/lib/fas/templates/user/list.html | 45 ++ fas/build/lib/fas/templates/user/new.html | 42 ++ .../lib/fas/templates/user/resetpass.html | 20 + .../lib/fas/templates/user/verifyemail.html | 21 + .../lib/fas/templates/user/verifypass.html | 22 + fas/build/lib/fas/templates/user/view.html | 99 +++ fas/build/lib/fas/templates/welcome.html | 26 + fas/build/lib/fas/tests/__init__.py | 0 fas/build/lib/fas/tests/test_controllers.py | 37 + fas/build/lib/fas/tests/test_model.py | 22 + fas/build/lib/fas/user.py | 656 ++++++++++++++++++ fas/build/scripts-2.5/fasClient | 577 +++++++++++++++ fas/build/scripts-2.5/restricted-shell | 67 ++ fas/fas/static/{ => theme/fas}/css/style.css | 0 .../static/{ => theme/fas}/images/account.png | Bin .../{ => theme/fas}/images/approved.png | Bin .../static/{ => theme/fas}/images/arrow.png | Bin .../static/{ => theme/fas}/images/attn.png | Bin .../fas}/images/control-separator.png | Bin .../static/{ => theme/fas}/images/favicon.ico | Bin .../{ => theme/fas}/images/footer-bottom.png | Bin .../{ => theme/fas}/images/footer-top.png | Bin .../static/{ => theme/fas}/images/head.png | Bin .../fas}/images/header-icon_account.png | Bin .../{ => theme/fas}/images/header_inner.png | Bin .../static/{ => theme/fas}/images/help.png | Bin fas/fas/static/{ => theme/fas}/images/hr.png | Bin .../{ => theme/fas}/images/icon_tool-item.png | Bin .../{ => theme/fas}/images/icon_warning.png | Bin .../static/{ => theme/fas}/images/info.png | Bin .../static/{ => theme/fas}/images/infobar.png | Bin .../static/{ => theme/fas}/images/logo.png | Bin fas/fas/static/{ => theme/fas}/images/ok.png | Bin .../static/{ => theme/fas}/images/queue.png | Bin .../static/{ => theme/fas}/images/shadow.png | Bin .../static/{ => theme/fas}/images/sidebar.png | Bin .../fas}/images/status_approved.png | Bin .../fas}/images/status_incomplete.png | Bin .../fas}/images/status_rejected.png | Bin .../static/{ => theme/fas}/images/success.png | Bin .../fas}/images/tg_under_the_hood.png | Bin .../static/{ => theme/fas}/images/tools.png | Bin .../fas}/images/topnav-separator.png | Bin .../static/{ => theme/fas}/images/topnav.png | Bin .../{ => theme/fas}/images/unapproved.png | Bin .../fas}/images/under_the_hood_blue.png | Bin fas/fas/templates/master.html | 5 +- 90 files changed, 4782 insertions(+), 2 deletions(-) create mode 100644 fas/build/lib/fas/__init__.py create mode 100644 fas/build/lib/fas/auth.py create mode 100644 fas/build/lib/fas/cla.py create mode 100644 fas/build/lib/fas/commands.py create mode 100644 fas/build/lib/fas/config/__init__.py create mode 100644 fas/build/lib/fas/config/log.cfg create mode 100644 fas/build/lib/fas/controllers.py create mode 100644 fas/build/lib/fas/feeds.py create mode 100644 fas/build/lib/fas/group.py create mode 100644 fas/build/lib/fas/help.py create mode 100644 fas/build/lib/fas/json_request.py create mode 100644 fas/build/lib/fas/model.py create mode 100644 fas/build/lib/fas/openid_fas.py create mode 100644 fas/build/lib/fas/openssl_fas.py create mode 100644 fas/build/lib/fas/release.py create mode 100644 fas/build/lib/fas/safasprovider.py create mode 100644 fas/build/lib/fas/templates/__init__.py create mode 100644 fas/build/lib/fas/templates/about.html create mode 100644 fas/build/lib/fas/templates/cla/__init__.py create mode 100644 fas/build/lib/fas/templates/cla/cla.html create mode 100644 fas/build/lib/fas/templates/cla/cla.txt create mode 100644 fas/build/lib/fas/templates/cla/index.html create mode 100644 fas/build/lib/fas/templates/error.html create mode 100644 fas/build/lib/fas/templates/group/__init__.py create mode 100644 fas/build/lib/fas/templates/group/dump.txt create mode 100644 fas/build/lib/fas/templates/group/edit.html create mode 100644 fas/build/lib/fas/templates/group/invite.html create mode 100644 fas/build/lib/fas/templates/group/list.html create mode 100644 fas/build/lib/fas/templates/group/new.html create mode 100644 fas/build/lib/fas/templates/group/view.html create mode 100644 fas/build/lib/fas/templates/help.html create mode 100644 fas/build/lib/fas/templates/home.html create mode 100644 fas/build/lib/fas/templates/login.html create mode 100644 fas/build/lib/fas/templates/master.html create mode 100644 fas/build/lib/fas/templates/openid/__init__.py create mode 100644 fas/build/lib/fas/templates/openid/about.html create mode 100644 fas/build/lib/fas/templates/openid/auth.txt create mode 100644 fas/build/lib/fas/templates/openid/id.html create mode 100644 fas/build/lib/fas/templates/openid/trusted.html create mode 100644 fas/build/lib/fas/templates/user/__init__.py create mode 100644 fas/build/lib/fas/templates/user/cert.txt create mode 100644 fas/build/lib/fas/templates/user/changepass.html create mode 100644 fas/build/lib/fas/templates/user/edit.html create mode 100644 fas/build/lib/fas/templates/user/list.html create mode 100644 fas/build/lib/fas/templates/user/new.html create mode 100644 fas/build/lib/fas/templates/user/resetpass.html create mode 100644 fas/build/lib/fas/templates/user/verifyemail.html create mode 100644 fas/build/lib/fas/templates/user/verifypass.html create mode 100644 fas/build/lib/fas/templates/user/view.html create mode 100644 fas/build/lib/fas/templates/welcome.html create mode 100644 fas/build/lib/fas/tests/__init__.py create mode 100644 fas/build/lib/fas/tests/test_controllers.py create mode 100644 fas/build/lib/fas/tests/test_model.py create mode 100644 fas/build/lib/fas/user.py create mode 100755 fas/build/scripts-2.5/fasClient create mode 100755 fas/build/scripts-2.5/restricted-shell rename fas/fas/static/{ => theme/fas}/css/style.css (100%) rename fas/fas/static/{ => theme/fas}/images/account.png (100%) rename fas/fas/static/{ => theme/fas}/images/approved.png (100%) rename fas/fas/static/{ => theme/fas}/images/arrow.png (100%) rename fas/fas/static/{ => theme/fas}/images/attn.png (100%) rename fas/fas/static/{ => theme/fas}/images/control-separator.png (100%) rename fas/fas/static/{ => theme/fas}/images/favicon.ico (100%) rename fas/fas/static/{ => theme/fas}/images/footer-bottom.png (100%) rename fas/fas/static/{ => theme/fas}/images/footer-top.png (100%) rename fas/fas/static/{ => theme/fas}/images/head.png (100%) rename fas/fas/static/{ => theme/fas}/images/header-icon_account.png (100%) rename fas/fas/static/{ => theme/fas}/images/header_inner.png (100%) rename fas/fas/static/{ => theme/fas}/images/help.png (100%) rename fas/fas/static/{ => theme/fas}/images/hr.png (100%) rename fas/fas/static/{ => theme/fas}/images/icon_tool-item.png (100%) rename fas/fas/static/{ => theme/fas}/images/icon_warning.png (100%) rename fas/fas/static/{ => theme/fas}/images/info.png (100%) rename fas/fas/static/{ => theme/fas}/images/infobar.png (100%) rename fas/fas/static/{ => theme/fas}/images/logo.png (100%) rename fas/fas/static/{ => theme/fas}/images/ok.png (100%) rename fas/fas/static/{ => theme/fas}/images/queue.png (100%) rename fas/fas/static/{ => theme/fas}/images/shadow.png (100%) rename fas/fas/static/{ => theme/fas}/images/sidebar.png (100%) rename fas/fas/static/{ => theme/fas}/images/status_approved.png (100%) rename fas/fas/static/{ => theme/fas}/images/status_incomplete.png (100%) rename fas/fas/static/{ => theme/fas}/images/status_rejected.png (100%) rename fas/fas/static/{ => theme/fas}/images/success.png (100%) rename fas/fas/static/{ => theme/fas}/images/tg_under_the_hood.png (100%) rename fas/fas/static/{ => theme/fas}/images/tools.png (100%) rename fas/fas/static/{ => theme/fas}/images/topnav-separator.png (100%) rename fas/fas/static/{ => theme/fas}/images/topnav.png (100%) rename fas/fas/static/{ => theme/fas}/images/unapproved.png (100%) rename fas/fas/static/{ => theme/fas}/images/under_the_hood_blue.png (100%) diff --git a/fas/build/lib/fas/__init__.py b/fas/build/lib/fas/__init__.py new file mode 100644 index 0000000..e333e3c --- /dev/null +++ b/fas/build/lib/fas/__init__.py @@ -0,0 +1,30 @@ +from fas import release +__version__ = release.VERSION + +class FASError(Exception): + '''FAS Error''' + pass + +class ApplyError(FASError): + '''Raised when a user could not apply to a group''' + pass + +class ApproveError(FASError): + '''Raised when a user could not be approved in a group''' + pass + +class SponsorError(FASError): + '''Raised when a user could not be sponsored in a group''' + pass + +class UpgradeError(FASError): + '''Raised when a user could not be upgraded in a group''' + pass + +class DowngradeError(FASError): + '''Raised when a user could not be downgraded in a group''' + pass + +class RemoveError(FASError): + '''Raised when a user could not be removed from a group''' + pass diff --git a/fas/build/lib/fas/auth.py b/fas/build/lib/fas/auth.py new file mode 100644 index 0000000..05b5deb --- /dev/null +++ b/fas/build/lib/fas/auth.py @@ -0,0 +1,218 @@ +from turbogears import config + +from fas.model import Groups +from fas.model import PersonRoles +from fas.model import People + +from sqlalchemy.exceptions import * +import turbogears + +import re + +def isAdmin(person): + ''' + Returns True if the user is a FAS admin (a member of the admingroup) + ''' + admingroup = config.get('admingroup') + try: + if person.group_roles[admingroup].role_status == 'approved': + return True + else: + return False + except KeyError: + return False + return False + +def canAdminGroup(person, group): + ''' + Returns True if the user is allowed to act as an admin for a group + ''' + if isAdmin(person) or (group.owner == person): + return True + else: + try: + role = PersonRoles.query.filter_by(group=group, member=person).one() + except IndexError: + ''' Not in the group ''' + return False + except InvalidRequestError: + return False + if role.role_status == 'approved' and role.role_type == 'administrator': + return True + return False + +def canSponsorGroup(person, group): + ''' + Returns True if the user is allowed to act as a sponsor for a group + ''' + try: + if isAdmin(person) or \ + group.owner == person: + return True + else: + try: + role = PersonRoles.query.filter_by(group=group, member=person).one() + except IndexError: + ''' Not in the group ''' + return False + if role.role_status == 'approved' and role.role_type == 'sponsor': + return True + return False + except: + return False + +def isApproved(person, group): + ''' + Returns True if the user is an approved member of a group + ''' + try: + if person.group_roles[group.name].role_status == 'approved': + return True + else: + return False + except KeyError: + return False + return False + +def CLADone(person): + ''' + Returns True if the user has completed the CLA + ''' + cla_done_group =config.get('cla_done_group') + try: + if person.group_roles[cla_done_group].role_status == 'approved': + return True + else: + return False + except KeyError: + return False + return False + +def canEditUser(person, target): + ''' + Returns True if the user has privileges to edit the target user + ''' + if person == target: + return True + elif isAdmin(person): + return True + else: + return False + +def canCreateGroup(person, group): + ''' + Returns True if the user can create groups + ''' + # Should groupname restrictions go here? + if isAdmin(person): + return True + else: + return False + +def canEditGroup(person, group): + ''' + Returns True if the user can edit the group + ''' + if canAdminGroup(person, group): + return True + else: + return False + +def canViewGroup(person, group): + ''' + Returns True if the user can view the group + ''' + # If the group matched by privileged_view_groups, then + # only people that can admin the group can view it + privilegedViewGroups = config.get('privileged_view_groups') + if re.compile(privilegedViewGroups).match(group.name): + if canAdminGroup(person, group): + return True + else: + return False + else: + return True + +def canApplyGroup(person, group, applicant): + ''' + Returns True if the user can apply applicant to the group + ''' + # User must satisfy all dependencies to join. + # This is bypassed for people already in the group and for the + # owner of the group (when they initially make it). + prerequisite = group.prerequisite + # TODO: Make this return more useful info. + if prerequisite: + if prerequisite in person.approved_memberships: + pass + else: + turbogears.flash(_('%s membership required before application to this group is allowed') % prerequisite.name) + return False + # A user can apply themselves, and FAS admins can apply other people. + + if (person == applicant) or \ + canAdminGroup(person, group): + return True + else: + turbogears.flash(_('%s membership required before application to this group is allowed') % prerequisite.name) + return False + +def canSponsorUser(person, group, target): + ''' + Returns True if the user can sponsor target in the group + ''' + # This is just here in case we want to add more complex checks in the future + if canSponsorGroup(person, group): + return True + else: + return False + +def canRemoveUser(person, group, target): + ''' + Returns True if the user can remove target from the group + ''' + # Only administrators can remove administrators. + if canAdminGroup(target, group) and \ + not canAdminGroup(person, group): + return False + # A user can remove themself from a group if user_can_remove is 1 + # Otherwise, a sponsor can remove sponsors/users. + elif ((person == target) and (group.user_can_remove == True)) or \ + canSponsorGroup(person, group): + return True + else: + return False + +def canUpgradeUser(person, group, target): + ''' + Returns True if the user can upgrade target in the group + ''' + # Group admins can upgrade anybody. + # The controller should handle the case where the target + # is already a group admin. + if canAdminGroup(person, group): + return True + # Sponsors can only upgrade non-sponsors (i.e. normal users) + # TODO: Don't assume that canSponsorGroup means that the user is a sponsor + elif canSponsorGroup(person, group) and \ + not canSponsorGroup(target, group): + return True + else: + return False + +def canDowngradeUser(person, group, target): + ''' + Returns True if the user can downgrade target in the group + ''' + # Group admins can downgrade anybody. + if canAdminGroup(person, group): + return True + # Sponsors can only downgrade sponsors. + # The controller should handle the case where the target + # is already a normal user. + elif canSponsorGroup(person, group) and \ + not canAdminGroup(person, group): + return True + else: + return False + diff --git a/fas/build/lib/fas/cla.py b/fas/build/lib/fas/cla.py new file mode 100644 index 0000000..c6aa636 --- /dev/null +++ b/fas/build/lib/fas/cla.py @@ -0,0 +1,120 @@ +import turbogears +from turbogears import controllers, expose, paginate, identity, redirect, widgets, validate, validators, error_handler +from turbogears.database import session + +import cherrypy + +from datetime import datetime +import re +import turbomail +from genshi.template.plugin import TextTemplateEnginePlugin + +from fas.model import People +from fas.model import Log +from fas.auth import * + +class CLA(controllers.Controller): + + def __init__(self): + '''Create a CLA Controller.''' + + @identity.require(turbogears.identity.not_anonymous()) + @expose(template="fas.templates.cla.index") + def index(self): + '''Display the CLAs (and accept/do not accept buttons)''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + if not person.telephone or not person.postal_address: + turbogears.flash('Postal Address and telephone number are required to complete the cla, please fill them out') + turbogears.redirect('/user/edit/%s' % username) + cla = CLADone(person) + return dict(cla=cla, person=person, date=datetime.utcnow().ctime()) + + def jsonRequest(self): + return 'tg_format' in cherrypy.request.params and \ + cherrypy.request.params['tg_format'] == 'json' + + @expose(template="fas.templates.error") + def error(self, tg_errors=None): + '''Show a friendly error message''' + if not tg_errors: + turbogears.redirect('/') + return dict(tg_errors=tg_errors) + + @identity.require(turbogears.identity.not_anonymous()) + @error_handler(error) + @expose(template="genshi-text:fas.templates.cla.cla", format="text", content_type='text/plain; charset=utf-8') + def text(self, type=None): + '''View CLA as text''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + return dict(person=person, date=datetime.utcnow().ctime()) + + @identity.require(turbogears.identity.not_anonymous()) + @error_handler(error) + @expose(template="genshi-text:fas.templates.cla.cla", format="text", content_type='text/plain; charset=utf-8') + def download(self, type=None): + '''Download CLA''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + return dict(person=person, date=datetime.utcnow().ctime()) + + @identity.require(turbogears.identity.not_anonymous()) + @error_handler(error) + @expose(template="fas.templates.cla.index") + def send(self, agree=False): + '''Send CLA''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + if CLADone(person): + turbogears.flash(_('You have already completed the CLA.')) + turbogears.redirect('/cla/') + return dict() + if not agree: + turbogears.flash(_("You have not completed the CLA.")) + turbogears.redirect('/user/view/%s' % person.username) + if not person.telephone or \ + not person.postal_address: + turbogears.flash(_('To complete the CLA, we must have your telephone number and postal address. Please ensure they have been filled out.')) + turbogears.redirect('/user/edit/%s' % username) + groupname = config.get('cla_fedora_group') + group = Groups.by_name(groupname) + try: + # Everything is correct. + person.apply(group, person) # Apply... + session.flush() + person.sponsor(group, person) # Sponsor! + except: + # TODO: If apply succeeds and sponsor fails, the user has + # to remove themselves from the CLA group before they can + # complete the CLA and go through the above try block again. + turbogears.flash(_("You could not be added to the '%s' group.") % group.name) + turbogears.redirect('/cla/') + return dict() + else: + dt = datetime.utcnow() + Log(author_id=person.id, description='Completed CLA', changetime=dt) + message = turbomail.Message(config.get('accounts_email'), config.get('legal_cla_email'), 'Fedora ICLA completed') + message.plain = ''' +Fedora user %(username)s has completed an ICLA (below). +Username: %(username)s +Email: %(email)s +Date: %(date)s + +=== CLA === + +''' % {'username': person.username, + 'human_name': person.human_name, + 'email': person.email, + 'postal_address': person.postal_address, + 'telephone': person.telephone, + 'facsimile': person.facsimile, + 'date': dt.ctime(),} + # Sigh.. if only there were a nicer way. + plugin = TextTemplateEnginePlugin() + message.plain += plugin.render(template='fas.templates.cla.cla', info=dict(person=person), format='text') + turbomail.enqueue(message) + turbogears.flash(_("You have successfully completed the CLA. You are now in the '%s' group.") % group.name) + turbogears.redirect('/user/view/%s' % person.username) + return dict() + diff --git a/fas/build/lib/fas/commands.py b/fas/build/lib/fas/commands.py new file mode 100644 index 0000000..dbbaf2d --- /dev/null +++ b/fas/build/lib/fas/commands.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +"""This module contains functions called from console script entry points.""" + +import os +import sys + +import pkg_resources +pkg_resources.require("TurboGears") + +import turbogears +import cherrypy + +cherrypy.lowercase_api = True + +class ConfigurationError(Exception): + pass + +def start(): + '''Start the CherryPy application server.''' + setupdir = os.path.dirname(os.path.dirname(__file__)) + curdir = os.getcwd() + + # First look on the command line for a desired config file, + # if it's not on the command line, then look for 'setup.py' + # in the current directory. If there, load configuration + # from a file called 'dev.cfg'. If it's not there, the project + # is probably installed and we'll look first for a file called + # 'prod.cfg' in the current directory and then for a default + # config file called 'default.cfg' packaged in the egg. + if len(sys.argv) > 1: + configfile = sys.argv[1] + elif os.path.exists(os.path.join(setupdir, 'setup.py')) \ + and os.path.exists(os.path.join(setupdir, 'dev.cfg')): + configfile = os.path.join(setupdir, 'dev.cfg') + elif os.path.exists(os.path.join(curdir, 'fas.cfg')): + configfile = os.path.join(curdir, 'fas.cfg') + elif os.path.exists(os.path.join('/etc/fas.cfg')): + configfile = os.path.join('/etc/fas.cfg') + else: + try: + configfile = pkg_resources.resource_filename( + pkg_resources.Requirement.parse("fas"), + "config/default.cfg") + except pkg_resources.DistributionNotFound: + raise ConfigurationError("Could not find default configuration.") + + turbogears.update_config(configfile=configfile, + modulename="fas.config") + + from fas.controllers import Root + turbogears.start_server(Root()) diff --git a/fas/build/lib/fas/config/__init__.py b/fas/build/lib/fas/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fas/build/lib/fas/config/log.cfg b/fas/build/lib/fas/config/log.cfg new file mode 100644 index 0000000..ce776f8 --- /dev/null +++ b/fas/build/lib/fas/config/log.cfg @@ -0,0 +1,29 @@ +# LOGGING +# Logging is often deployment specific, but some handlers and +# formatters can be defined here. + +[logging] +[[formatters]] +[[[message_only]]] +format='*(message)s' + +[[[full_content]]] +format='*(asctime)s *(name)s *(levelname)s *(message)s' + +[[handlers]] +[[[debug_out]]] +class='StreamHandler' +level='DEBUG' +args='(sys.stdout,)' +formatter='full_content' + +[[[access_out]]] +class='StreamHandler' +level='INFO' +args='(sys.stdout,)' +formatter='message_only' + +[[[error_out]]] +class='StreamHandler' +level='ERROR' +args='(sys.stdout,)' diff --git a/fas/build/lib/fas/controllers.py b/fas/build/lib/fas/controllers.py new file mode 100644 index 0000000..b092bf5 --- /dev/null +++ b/fas/build/lib/fas/controllers.py @@ -0,0 +1,145 @@ +from turbogears import controllers, expose, config +from model import * +from turbogears import identity, redirect, widgets, validate, validators, error_handler +from cherrypy import request, response + +from turbogears import exception_handler +import turbogears +import cherrypy +import time + +from fas.user import User +from fas.group import Group +from fas.cla import CLA +from fas.json_request import JsonRequest +from fas.help import Help +from fas.auth import * +#from fas.openid_fas import OpenID + +import os +import sys +reload(sys) +sys.setdefaultencoding('utf-8') + +def add_custom_stdvars(vars): + return vars.update({"gettext": _}) + +turbogears.view.variable_providers.append(add_custom_stdvars) + +def get_locale(locale=None): + if locale: + return locale + try: + return turbogears.identity.current.user.locale + except AttributeError: + return turbogears.i18n.utils._get_locale() + +config.update({'i18n.get_locale': get_locale}) + +# from fas import json +# import logging +# log = logging.getLogger("fas.controllers") + +#TODO: Appropriate flash icons for errors, etc. +# mmcgrath wonders if it will be handy to expose an encrypted mailer with fas over json for our apps + +class Root(controllers.RootController): + + user = User() + group = Group() + cla = CLA() + json = JsonRequest() + help = Help() + #openid = OpenID() + + # TODO: Find a better place for this. + os.environ['GNUPGHOME'] = config.get('gpghome') + + @expose(template="fas.templates.welcome", allow_json=True) + def index(self): + if turbogears.identity.not_anonymous(): + if 'tg_format' in request.params \ + and request.params['tg_format'] == 'json': + # redirects don't work with JSON calls. This is a bit of a + # hack until we can figure out something better. + return dict() + turbogears.redirect('/home') + return dict(now=time.ctime()) + + @expose(template="fas.templates.home", allow_json=True) + @identity.require(identity.not_anonymous()) + def home(self): + user_name = turbogears.identity.current.user_name + person = People.by_username(user_name) + cla = CLADone(person) + return dict(person=person, cla=cla) + + @expose(template="fas.templates.about") + def about(self): + return dict() + + @expose(template="fas.templates.login", allow_json=True) + def login(self, forward_url=None, previous_url=None, *args, **kwargs): + '''Page to become authenticated to the Account System. + + This shows a small login box to type in your username and password + from the Fedora Account System. + + Arguments: + :forward_url: The url to send to once authentication succeeds + :previous_url: The url that sent us to the login page + ''' + if forward_url == '.': + forward_url = turbogears.url('/../home') + if not identity.current.anonymous \ + and identity.was_login_attempted() \ + and not identity.get_identity_errors(): + # User is logged in + turbogears.flash(_('Welcome, %s') % People.by_username(turbogears.identity.current.user_name).human_name) + if 'tg_format' in request.params \ + and request.params['tg_format'] == 'json': + # When called as a json method, doesn't make any sense to + # redirect to a page. Returning the logged in identity + # is better. + return dict(user = identity.current.user) + if not forward_url: + forward_url = turbogears.url('/') + raise redirect(forward_url) + + forward_url=None + previous_url= request.path + + if identity.was_login_attempted(): + msg=_("The credentials you supplied were not correct or " + "did not grant access to this resource.") + elif identity.get_identity_errors(): + msg=_("You must provide your credentials before accessing " + "this resource.") + else: + msg=_("Please log in.") + forward_url= '.' + + cherrypy.response.status=403 + return dict(message=msg, previous_url=previous_url, logging_in=True, + original_parameters=request.params, + forward_url=forward_url) + + @expose(allow_json=True) + def logout(self): + identity.current.logout() + turbogears.flash(_('You have successfully logged out.')) + if 'tg_format' in request.params \ + and request.params['tg_format'] == 'json': + # When called as a json method, doesn't make any sense to + # redirect to a page. Returning the logged in identity + # is better. + return dict(status=True) + raise redirect('/') + + @expose() + def language(self, locale): + locale_key = config.get("i18n.session_key", "locale") + cherrypy.session[locale_key] = locale + raise redirect(request.headers.get("Referer", "/")) + + diff --git a/fas/build/lib/fas/feeds.py b/fas/build/lib/fas/feeds.py new file mode 100644 index 0000000..93a64c8 --- /dev/null +++ b/fas/build/lib/fas/feeds.py @@ -0,0 +1,17 @@ +import urllib +from xml.dom import minidom + + +class Koji: + def __init__(self, userName, url='http://publictest8/koji/recentbuilds?user='): + buildFeed = minidom.parse(urllib.urlopen(url + userName)) + try: + self.userLink = buildFeed.getElementsByTagName('link')[0].childNodes[0].data + self.builds = {} + for build in buildFeed.getElementsByTagName('item'): + link = build.getElementsByTagName('link')[0].childNodes[0].data + self.builds[link] = {} + self.builds[link]['title'] = build.getElementsByTagName('title')[0].childNodes[0].data + self.builds[link]['pubDate'] = build.getElementsByTagName('pubDate')[0].childNodes[0].data + except IndexError: + return diff --git a/fas/build/lib/fas/group.py b/fas/build/lib/fas/group.py new file mode 100644 index 0000000..c96b92c --- /dev/null +++ b/fas/build/lib/fas/group.py @@ -0,0 +1,532 @@ +import turbogears +from turbogears import controllers, expose, paginate, identity, redirect, widgets, validate, validators, error_handler +from turbogears.database import session + +import cherrypy +import sqlalchemy + +import fas +from fas.auth import * +from fas.user import KnownUser + +import re +import turbomail + +class KnownGroup(validators.FancyValidator): + '''Make sure that a group already exists''' + def _to_python(self, value, state): + return value.strip() + def validate_python(self, value, state): + try: + g = Groups.by_name(value) + except InvalidRequestError: + raise validators.Invalid(_("The group '%s' does not exist.") % value, value, state) + +class UnknownGroup(validators.FancyValidator): + '''Make sure that a group doesn't already exist''' + def _to_python(self, value, state): + return value.strip() + def validate_python(self, value, state): + try: + g = Groups.by_name(value) + except InvalidRequestError: + pass + else: + raise validators.Invalid(_("The group '%s' already exists.") % value, value, state) + +class GroupCreate(validators.Schema): + + name = validators.All( + UnknownGroup, + validators.String(max=32, min=3), + validators.Regex(regex='^[a-z0-9\-_]+$'), + ) + display_name = validators.NotEmpty + owner = validators.All( + KnownUser, + validators.NotEmpty, + ) + prerequisite = KnownGroup + #group_type = something + +class GroupSave(validators.Schema): + groupname = validators.All(KnownGroup, validators.String(max=32, min=3)) + display_name = validators.NotEmpty + owner = KnownUser + prerequisite = KnownGroup + #group_type = something + +class GroupApply(validators.Schema): + groupname = KnownGroup + targetname = KnownUser + +class GroupSponsor(validators.Schema): + groupname = KnownGroup + targetname = KnownUser + +class GroupRemove(validators.Schema): + groupname = KnownGroup + targetname = KnownUser + +class GroupUpgrade(validators.Schema): + groupname = KnownGroup + targetname = KnownUser + +class GroupDowngrade(validators.Schema): + groupname = KnownGroup + targetname = KnownUser + +class GroupView(validators.Schema): + groupname = KnownGroup + +class GroupEdit(validators.Schema): + groupname = KnownGroup + +class GroupInvite(validators.Schema): + groupname = KnownGroup + +class GroupSendInvite(validators.Schema): + groupname = KnownGroup + target = validators.Email(not_empty=True, strip=True), + +#class findUser(widgets.WidgetsList): +# username = widgets.AutoCompleteField(label=_('Username'), search_controller='search', search_param='username', result_name='people') +# action = widgets.HiddenField(default='apply', validator=validators.String(not_empty=True)) +# groupname = widgets.HiddenField(validator=validators.String(not_empty=True)) +# +#findUserForm = widgets.ListForm(fields=findUser(), submit_text=_('Invite')) + +class Group(controllers.Controller): + + def __init__(self): + '''Create a Group Controller.''' + + @identity.require(turbogears.identity.not_anonymous()) + def index(self): + '''Perhaps show a nice explanatory message about groups here?''' + return dict() + + def jsonRequest(self): + return 'tg_format' in cherrypy.request.params and \ + cherrypy.request.params['tg_format'] == 'json' + + @expose(template="fas.templates.error") + def error(self, tg_errors=None): + '''Show a friendly error message''' + if not tg_errors: + turbogears.redirect('/') + return dict(tg_errors=tg_errors) + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=GroupView()) + @error_handler(error) + @expose(template="fas.templates.group.view", allow_json=True) + def view(self, groupname): + '''View group''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + group = Groups.by_name(groupname) + + if not canViewGroup(person, group): + turbogears.flash(_("You cannot view '%s'") % group.name) + turbogears.redirect('/group/list') + return dict() + else: + return dict(group=group) + + @identity.require(turbogears.identity.not_anonymous()) + @expose(template="fas.templates.group.new") + def new(self): + '''Display create group form''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + + if not canCreateGroup(person, Groups.by_name(config.get('admingroup'))): + turbogears.flash(_('Only FAS adminstrators can create groups.')) + turbogears.redirect('/') + return dict() + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=GroupCreate()) + @error_handler(error) + @expose(template="fas.templates.group.new") + def create(self, name, display_name, owner, group_type, needs_sponsor=0, user_can_remove=1, prerequisite='', joinmsg=''): + '''Create a group''' + + groupname = name + person = People.by_username(turbogears.identity.current.user_name) + person_owner = People.by_username(owner) + + if not canCreateGroup(person, Groups.by_name(config.get('admingroup'))): + turbogears.flash(_('Only FAS adminstrators can create groups.')) + turbogears.redirect('/') + try: + owner = People.by_username(owner) + group = Groups() + group.name = name + group.display_name = display_name + group.owner_id = person_owner.id + group.group_type = group_type + group.needs_sponsor = bool(needs_sponsor) + group.user_can_remove = bool(user_can_remove) + if prerequisite: + prerequisite = Groups.by_name(prerequisite) + group.prerequisite = prerequisite + group.joinmsg = joinmsg + # Log here + session.flush() + except TypeError: + turbogears.flash(_("The group: '%s' could not be created.") % groupname) + return dict() + else: + try: + owner.apply(group, person) # Apply... + session.flush() + owner.sponsor(group, person) + owner.upgrade(group, person) + owner.upgrade(group, person) + except KeyError: + turbogears.flash(_("The group: '%(group)s' has been created, but '%(user)s' could not be added as a group administrator.") % {'group': group.name, 'user': owner.username}) + else: + turbogears.flash(_("The group: '%s' has been created.") % group.name) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=GroupEdit()) + @error_handler(error) + @expose(template="fas.templates.group.edit") + def edit(self, groupname): + '''Display edit group form''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + group = Groups.by_name(groupname) + + if not canAdminGroup(person, group): + turbogears.flash(_("You cannot edit '%s'.") % group.name) + turbogears.redirect('/group/view/%s' % group.name) + return dict(group=group) + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=GroupSave()) + @error_handler(error) + @expose(template="fas.templates.group.edit") + def save(self, groupname, display_name, owner, group_type, needs_sponsor=0, user_can_remove=1, prerequisite='', joinmsg=''): + '''Edit a group''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + group = Groups.by_name(groupname) + + if not canEditGroup(person, group): + turbogears.flash(_("You cannot edit '%s'.") % group.name) + turbogears.redirect('/group/view/%s' % group.name) + else: + try: + owner = People.by_username(owner) + group.display_name = display_name + group.owner = owner + group.group_type = group_type + group.needs_sponsor = bool(needs_sponsor) + group.user_can_remove = bool(user_can_remove) + if prerequisite: + prerequisite = Groups.by_name(prerequisite) + group.prerequisite = prerequisite + group.joinmsg = joinmsg + # Log here + session.flush() + except: + turbogears.flash(_('The group details could not be saved.')) + else: + turbogears.flash(_('The group details have been saved.')) + turbogears.redirect('/group/view/%s' % group.name) + return dict(group=group) + + @identity.require(turbogears.identity.not_anonymous()) + @expose(template="fas.templates.group.list", allow_json=True) + def list(self, search='*'): + username = turbogears.identity.current.user_name + person = People.by_username(username) + + memberships = {} + groups = [] + re_search = re.sub(r'\*', r'%', search).lower() + results = Groups.query.filter(Groups.name.like(re_search)).order_by('name').all() + if self.jsonRequest(): + membersql = sqlalchemy.select([PersonRoles.c.person_id, PersonRoles.c.group_id, PersonRoles.c.role_type], PersonRoles.c.role_status=='approved').order_by(PersonRoles.c.group_id) + members = membersql.execute() + for member in members: + try: + memberships[member[1]].append({'person_id': member[0], 'role_type': member[2]}) + except KeyError: + memberships[member[1]]=[{'person_id': member[0], 'role_type': member[2]}] + for group in results: + if canViewGroup(person, group): + groups.append(group) + if not len(groups): + turbogears.flash(_("No Groups found matching '%s'") % search) + return dict(groups=groups, search=search, memberships=memberships) + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=GroupApply()) + @error_handler(error) + @expose(template='fas.templates.group.view') + def apply(self, groupname, targetname=None): + '''Apply to a group''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + if not targetname: + target = person + else: + target = People.by_username(targetname) + group = Groups.by_name(groupname) + + if not canApplyGroup(person, group, target): + turbogears.flash(_('%(user)s can not apply to %(group)s.') % \ + {'user': target.username, 'group': group.name }) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + else: + try: + target.apply(group, person) + except fas.ApplyError, e: + turbogears.flash(_('%(user)s could not apply to %(group)s: %(error)s') % \ + {'user': target.username, 'group': group.name, 'error': e}) + turbogears.redirect('/group/view/%s' % group.name) + else: + # TODO: How do we handle gettext calls for these kinds of emails? + # TODO: CC to right place, put a bit more thought into how to most elegantly do this + # TODO: Maybe that @fedoraproject.org (and even -sponsors) should be configurable somewhere? + message = turbomail.Message(config.get('accounts_email'), '%(group)s-sponsors@%(host)s' % {'group': group.name, 'host': config.get('email_host')}, \ + "Fedora '%(group)s' sponsor needed for %(user)s" % {'user': target.username, 'group': group.name}) + url = config.get('base_url_filter.base_url') + '/group/edit/%s' % groupname + + message.plain = _(''' +Fedora user %(user)s, aka %(name)s <%(email)s> has requested +membership for %(applicant)s (%(applicant_name)s) in the %(group)s group and needs a sponsor. + +Please go to %(url)s to take action. +''') % {'user': person.username, 'name': person.human_name, 'applicant': target.username, 'applicant_name': target.human_name, 'email': person.email, 'url': url, 'group': group.name} + turbomail.enqueue(message) + turbogears.flash(_('%(user)s has applied to %(group)s!') % \ + {'user': target.username, 'group': group.name}) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=GroupSponsor()) + @error_handler(error) + @expose(template='fas.templates.group.view') + def sponsor(self, groupname, targetname): + '''Sponsor user''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + target = People.by_username(targetname) + group = Groups.by_name(groupname) + + if not canSponsorUser(person, group, target): + turbogears.flash(_("You cannot sponsor '%s'") % target.username) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + else: + try: + target.sponsor(group, person) + except fas.SponsorError, e: + turbogears.flash(_("%(user)s could not be sponsored in %(group)s: %(error)s") % \ + {'user': target.username, 'group': group.name, 'error': e}) + turbogears.redirect('/group/view/%s' % group.name) + else: + import turbomail + message = turbomail.Message(config.get('accounts_email'), target.email, "Your Fedora '%s' membership has been sponsored" % group.name) + message.plain = _(''' +%(name)s <%(email)s> has sponsored you for membership in the %(group)s +group of the Fedora account system. If applicable, this change should +propagate into the e-mail aliases and CVS repository within an hour. + +%(joinmsg)s +''') % {'group': group.name, 'name': person.human_name, 'email': person.email, 'joinmsg': group.joinmsg} + turbomail.enqueue(message) + turbogears.flash(_("'%s' has been sponsored!") % target.human_name) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=GroupRemove()) + @error_handler(error) + @expose(template='fas.templates.group.view') + def remove(self, groupname, targetname): + '''Remove user from group''' + # TODO: Add confirmation? + username = turbogears.identity.current.user_name + person = People.by_username(username) + target = People.by_username(targetname) + group = Groups.by_name(groupname) + + if not canRemoveUser(person, group, target): + turbogears.flash(_("You cannot remove '%(user)s' from '%(group)s'.") % {'user': target.username, 'group': group.name}) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + else: + try: + target.remove(group, target) + except fas.RemoveError, e: + turbogears.flash(_("%(user)s could not be removed from %(group)s: %(error)s") % \ + {'user': target.username, 'group': group.name, 'error': e}) + turbogears.redirect('/group/view/%s' % group.name) + else: + message = turbomail.Message(config.get('accounts_email'), target.email, "Your Fedora '%s' membership has been removed" % group.name) + message.plain = _(''' +%(name)s <%(email)s> has removed you from the '%(group)s' +group of the Fedora Accounts System This change is effective +immediately for new operations, and should propagate into the e-mail +aliases within an hour. +''') % {'group': group.name, 'name': person.human_name, 'email': person.email} + turbomail.enqueue(message) + turbogears.flash(_('%(name)s has been removed from %(group)s') % \ + {'name': target.username, 'group': group.name}) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=GroupUpgrade()) + @error_handler(error) + @expose(template='fas.templates.group.view') + def upgrade(self, groupname, targetname): + '''Upgrade user in group''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + target = People.by_username(targetname) + group = Groups.by_name(groupname) + + if not canUpgradeUser(person, group, target): + turbogears.flash(_("You cannot upgrade '%s'") % target.username) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + else: + try: + target.upgrade(group, person) + except fas.UpgradeError, e: + turbogears.flash(_('%(name)s could not be upgraded in %(group)s: %(error)s') % \ + {'name': target.username, 'group': group.name, 'error': e}) + turbogears.redirect('/group/view/%s' % group.name) + else: + import turbomail + message = turbomail.Message(config.get('accounts_email'), target.email, "Your Fedora '%s' membership has been upgraded" % group.name) + # Should we make person.upgrade return this? + role = PersonRoles.query.filter_by(group=group, member=target).one() + status = role.role_type + message.plain = _(''' +%(name)s <%(email)s> has upgraded you to %(status)s status in the +'%(group)s' group of the Fedora Accounts System This change is +effective immediately for new operations, and should propagate +into the e-mail aliases within an hour. +''') % {'group': group.name, 'name': person.human_name, 'email': person.email, 'status': status} + turbomail.enqueue(message) + turbogears.flash(_('%s has been upgraded!') % target.username) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=GroupDowngrade()) + @error_handler(error) + @expose(template='fas.templates.group.view') + def downgrade(self, groupname, targetname): + '''Upgrade user in group''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + target = People.by_username(targetname) + group = Groups.by_name(groupname) + + if not canDowngradeUser(person, group, target): + turbogears.flash(_("You cannot downgrade '%s'") % target.username) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + else: + try: + target.downgrade(group, person) + except fas.DowngradeError, e: + turbogears.flash(_('%(name)s could not be downgraded in %(group)s: %(error)s') % \ + {'name': target.username, 'group': group.name, 'error': e}) + turbogears.redirect('/group/view/%s' % group.name) + else: + import turbomail + message = turbomail.Message(config.get('accounts_email'), target.email, "Your Fedora '%s' membership has been downgraded" % group.name) + role = PersonRoles.query.filter_by(group=group, member=target).one() + status = role.role_type + message.plain = _(''' +%(name)s <%(email)s> has downgraded you to %(status)s status in the +'%(group)s' group of the Fedora Accounts System This change is +effective immediately for new operations, and should propagate +into the e-mail aliases within an hour. +''') % {'group': group.name, 'name': person.human_name, 'email': person.email, 'status': status} + turbomail.enqueue(message) + turbogears.flash(_('%s has been downgraded!') % target.username) + turbogears.redirect('/group/view/%s' % group.name) + return dict() + + @identity.require(turbogears.identity.not_anonymous()) + @error_handler(error) + @expose(template="genshi-text:fas.templates.group.dump", format="text", content_type='text/plain; charset=utf-8') + def dump(self, groupname=None): + username = turbogears.identity.current.user_name + person = People.by_username(username) + if not groupname: +# groupname = config.get('cla_done_group') + people = People.query.order_by('username').all() + else: + people = [] + groups = Groups.by_name(groupname) + for role in groups.approved_roles: + people.append(role.member) + if not canViewGroup(person, groups): + turbogears.flash(_("You cannot view '%s'") % group.name) + turbogears.redirect('/group/list') + return dict() + + return dict(people=people) + + @identity.require(identity.not_anonymous()) + @validate(validators=GroupInvite()) + @error_handler(error) + @expose(template='fas.templates.group.invite') + def invite(self, groupname): + username = turbogears.identity.current.user_name + person = People.by_username(username) + group = Groups.by_name(groupname) + + return dict(person=person, group=group) + + @identity.require(identity.not_anonymous()) + @validate(validators=GroupSendInvite()) + @error_handler(error) + @expose(template='fas.templates.group.invite') + def sendinvite(self, groupname, target): + import turbomail + username = turbogears.identity.current.user_name + person = People.by_username(username) + group = Groups.by_name(groupname) + + if isApproved(person, group): + message = turbomail.Message(person.email, target, _('Come join The Fedora Project!')) + message.plain = _(''' +%(name)s <%(email)s> has invited you to join the Fedora +Project! We are a community of users and developers who produce a +complete operating system from entirely free and open source software +(FOSS). %(name)s thinks that you have knowledge and skills +that make you a great fit for the Fedora community, and that you might +be interested in contributing. + +How could you team up with the Fedora community to use and develop your +skills? Check out http://fedoraproject.org/join-fedora for some ideas. +Our community is more than just software developers -- we also have a +place for you whether you're an artist, a web site builder, a writer, or +a people person. You'll grow and learn as you work on a team with other +very smart and talented people. + +Fedora and FOSS are changing the world -- come be a part of it!''') % {'name': person.human_name, 'email': person.email} + turbomail.enqueue(message) + turbogears.flash(_('Message sent to: %s') % target) + turbogears.redirect('/group/view/%s' % group.name) + else: + turbogears.flash(_("You are not in the '%s' group.") % group.name) + return dict(target=target, person=person, group=group) + diff --git a/fas/build/lib/fas/help.py b/fas/build/lib/fas/help.py new file mode 100644 index 0000000..b00aedd --- /dev/null +++ b/fas/build/lib/fas/help.py @@ -0,0 +1,50 @@ +import turbogears +from turbogears import controllers, expose, paginate, identity, redirect, widgets, validate, validators, error_handler +from turbogears.database import session + +from fas.auth import * + +# TODO: gettext like crazy. +class Help(controllers.Controller): + help = { 'none' : ['Error', '

We could not find that help item

'], + 'user_ircnick' : ['IRC Nick (Optional)', '

IRC Nick is used to identify yourself on irc.freenode.net. Please register your nick on irc.freenode.net first, then fill this in so people can find you online when they need to

'], + 'user_email' : ['Email (Required)', '

This email address should be your prefered email contact and will be used to send various official emails to. This is also where your @fedoraproject.org email will get forwarded

'], + 'user_human_name' : ['Full Name (Required)', '

Your Human Name or "real life" name

'], + 'user_gpg_keyid' : ['GPG Key', '

A GPG key is generally used to prove that a message or email came from you or to encrypt information so that only the recipients can read it. This can be used when a password reset is sent to your email.

'], + 'user_telephone' : ['Telephone', '

Required in order to complete the CLA. Sometimes during a time of emergency someone from the Fedora Project may need to contact you. For more information see our Privacy Policy

'], + 'user_postal_address': ['Postal Address', '

Required in order to complete the CLA. This should be a mailing address where you can be contacted. See our Privacy Policy about any concerns.

'], + 'user_timezone': ['Timezone (Optional)', '

Please specify the time zone you are in.

'], + 'user_comments': ['Comments (Optional)', '

Misc comments about yourself.

'], + 'user_account_status': ['Account Status', '

Shows account status, possible values include

'], + 'user_cla' : ['CLA', '

In order to become a full Fedora contributor you must complete the Contributor License Agreement. This license is a legal agreement between you and Red Hat. Full status allows people to contribute content and code and is recommended for anyone interested in getting involved in the Fedora Project.

'], + 'user_ssh_key' : ['Public SSH Key', '

Many resources require public key authentiaction to work. By uploading your public key to us, you can then log in to our servers. Type "man ssh-keygen" for more information on creating your key. Once created you will want to upload ~/.ssh/id_dsa.pub or ~/.ssh/id_rsa.pub

'], + 'user_locale': ['Locale', '

For non-english speaking peoples this allows individuals to select which locale they are in.

'], + + 'group_apply': ['Apply', '

Applying for a group is like applying for a job and it can certainly take a while to get in. Many groups have their own rules about how to actually get approved or sponsored. For more information on how the account system works see the about page.

'], + 'group_remove': ['Remove', '''

Removing a person from a group will cause that user to no longer be in the group. They will need to re-apply to get in. Admins can remove anyone, Sponsors can remove users, users can't remove anyone.

'''], + 'group_upgrade': ['Upgrade', '''

Upgrade a persons status in this group.

'''], + 'group_downgrade': ['Downgrade', '''

Downgrade a persons status in the group.

'''], + 'group_approve': ['Approve', '''

A sponsor or administrator can approve users to be in a group. Once the user has applied for the group, go to the group's page and click approve to approve the user.

'''], + 'group_sponsor': ['Sponsor', '''

A sponsor or administrator can sponsor users to be in a gruop. Once the user has applied for the group, go to the group's page and click approve to sponsor the user. Sponsorship of a user implies that you are approving a user and may mentor and answer their questions as they come up.

'''], + 'group_user_add': ['Add User', '''

Manually add a user to a group. Place their username in this field and click 'Add'

'''], + 'group_name': ['Group Name', '''

The name of the group you'd like to create. It should be alphanumeric though '-'s are allowed

'''], + 'group_display_name': ['Display Name', '''

More human readable name of the group

'''], + 'group_owner': ['Group Owner', '''

The name of the owner who will run this group

'''], + 'group_type': ['Group Type', '''

Normally it is safe to leave this blank. Though some values include 'tracking', 'shell', 'cvs', 'git', 'hg', 'svn', and 'mtn'. This value only really matters if the group is to end up getting shell access or commit access somewhere like fedorahosted.

'''], + 'group_needs_sponsor': ['Needs Sponsor', '''

If your group requires sponsorship (recommended), this means that when a user is approved by a sponsor. That relationship is recorded in the account system. If user A sponsors user N, then in viewing the members of this group, people will know to contact user A about user N if something goes wrong. If this box is unchecked, this means that only approval is needed and no relationship is recorded about who did the approving

'''], + 'group_self_removal': ['Self Removal', '''

Should users be able to remove themselves from this group without sponsor / admin intervention? (recommended yes)

'''], + 'group_prerequisite': ['Must Belong To', '''

Before a user can join this group, they must belong to the group listed in this box. This value cannot be removed without administrative intervention, only changed. Recommended values are for the 'cla_done' group.

'''], + 'group_join_message': ['Join Message', '''

This message will go out to users when they join the group. It should be informative and offer tips about what to do next. A description of the group would also be valuable here

'''], + 'gencert': ['Client Side Cert', '''

The client side cert is generally used to grant access to upload packages to Fedora or for other authentication purposes like with koji. If you are not a package maintainer there is no need to worry about the client side cert

'''], + } + + def __init__(self): + '''Create a JsonRequest Controller.''' + + @expose(template="fas.templates.help") + def get_help(self, id='none'): + try: + helpItem = self.help[id] + except KeyError: + return dict(title='Error', helpItem=['Error', '

We could not find that help item

']) + return dict(help=helpItem) diff --git a/fas/build/lib/fas/json_request.py b/fas/build/lib/fas/json_request.py new file mode 100644 index 0000000..8e75438 --- /dev/null +++ b/fas/build/lib/fas/json_request.py @@ -0,0 +1,73 @@ +import turbogears +from turbogears import controllers, expose, identity + +import sqlalchemy + +from fas.model import People +from fas.model import Groups +from fas.model import Log + +from fas.auth import * + +class JsonRequest(controllers.Controller): + def __init__(self): + """Create a JsonRequest Controller.""" + + @identity.require(turbogears.identity.not_anonymous()) + @expose("json", allow_json=True) + def index(self): + """Return a help message""" + return dict(help='This is a JSON interface.') + + @identity.require(turbogears.identity.not_anonymous()) + @expose("json", allow_json=True) + def person_by_id(self, id): + try: + person = People.by_id(id) + person.jsonProps = { + 'People': ('approved_memberships', 'unapproved_memberships') + } + return dict(success=True, person=person) + except InvalidRequestError: + return dict(success=False) + + @identity.require(turbogears.identity.not_anonymous()) + @expose("json", allow_json=True) + def person_by_username(self, username): + try: + person = People.by_username(username) + person.jsonProps = { + 'People': ('approved_memberships', 'unapproved_memberships') + } + return dict(success=True, person=person) + except InvalidRequestError: + return dict(success=False) + + @identity.require(turbogears.identity.not_anonymous()) + @expose("json", allow_json=True) + def group_by_id(self, id): + try: + group = Groups.by_id(id) + return dict(success=True, group=group) + except InvalidRequestError: + return dict(success=False) + + @identity.require(turbogears.identity.not_anonymous()) + @expose("json", allow_json=True) + def group_by_name(self, groupname): + try: + group = Groups.by_name(groupname) + return dict(success=True, group=group) + except InvalidRequestError: + return dict(success=False) + + @identity.require(turbogears.identity.not_anonymous()) + @expose("json", allow_json=True) + def user_id(self): + people = {} + peoplesql = sqlalchemy.select([People.c.id, People.c.username]) + persons = peoplesql.execute() + for person in persons: + people[person[0]] = person[1] + return dict(people=people) + diff --git a/fas/build/lib/fas/model.py b/fas/build/lib/fas/model.py new file mode 100644 index 0000000..57786f5 --- /dev/null +++ b/fas/build/lib/fas/model.py @@ -0,0 +1,470 @@ +# -*- coding: utf-8 -*- +# +# Copyright © 2008 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, modify, +# copy, or redistribute it subject to the terms and conditions of the GNU +# General Public License v.2. This program is distributed in the hope that it +# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the +# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the GNU General Public License for more details. You should have +# received a copy of the GNU General Public License along with this program; +# if not, write to the Free Software Foundation, Inc., 51 Franklin Street, +# Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat trademarks that are +# incorporated in the source code or documentation are not subject to the GNU +# General Public License and may only be used or replicated with the express +# permission of Red Hat, Inc. +# +# Author(s): Toshio Kuratomi +# Ricky Zhou +# + +''' +Model for the Fedora Account System +''' +from datetime import datetime +import pytz +from turbogears.database import metadata, mapper, get_engine +# import some basic SQLAlchemy classes for declaring the data model +# (see http://www.sqlalchemy.org/docs/04/ormtutorial.html) +from sqlalchemy import Table, Column, ForeignKey +from sqlalchemy.orm import relation +# import some datatypes for table columns from SQLAlchemy +# (see http://www.sqlalchemy.org/docs/04/types.html for more) +from sqlalchemy import String, Unicode, Integer, DateTime +# A few sqlalchemy tricks: +# Allow viewing foreign key relations as a dictionary +from sqlalchemy.orm.collections import column_mapped_collection, attribute_mapped_collection +# Allow us to reference the remote table of a many:many as a simple list +from sqlalchemy.ext.associationproxy import association_proxy +from sqlalchemy import select, and_ + +from sqlalchemy.exceptions import InvalidRequestError + +from turbogears.database import session + +from turbogears import identity, config + +import turbogears + +from fedora.tg.json import SABase +import fas + +# Bind us to the database defined in the config file. +get_engine() + +# +# Tables Mapped from the DB +# + +PeopleTable = Table('people', metadata, autoload=True) +PersonRolesTable = Table('person_roles', metadata, autoload=True) + +ConfigsTable = Table('configs', metadata, autoload=True) +GroupsTable = Table('groups', metadata, autoload=True) +GroupRolesTable = Table('group_roles', metadata, autoload=True) +BugzillaQueueTable = Table('bugzilla_queue', metadata, autoload=True) +LogTable = Table('log', metadata, autoload=True) +RequestsTable = Table('requests', metadata, autoload=True) + +# +# Selects for filtering roles +# +ApprovedRolesSelect = PersonRolesTable.select(and_( + PeopleTable.c.id==PersonRolesTable.c.person_id, + PersonRolesTable.c.role_status=='approved')).alias('approved') +UnApprovedRolesSelect = PersonRolesTable.select(and_( + PeopleTable.c.id==PersonRolesTable.c.person_id, + PersonRolesTable.c.role_status!='approved')).alias('unapproved') + +# The identity schema -- These must follow some conventions that TG +# understands and are shared with other Fedora services via the python-fedora +# module. + +visits_table = Table('visit', metadata, + Column('visit_key', String(40), primary_key=True), + Column('created', DateTime, nullable=False, default=datetime.now(pytz.utc)), + Column('expiry', DateTime) +) + +visit_identity_table = Table('visit_identity', metadata, + Column('visit_key', String(40), ForeignKey('visit.visit_key'), + primary_key=True), + Column('user_id', Integer, ForeignKey('people.id'), index=True) +) + +# +# Mapped Classes +# + +class People(SABase): + '''Records for all the contributors to Fedora.''' + + @classmethod + def by_id(cls, id): + ''' + A class method that can be used to search users + based on their unique id + ''' + return cls.query.filter_by(id=id).one() + + @classmethod + def by_email_address(cls, email): + ''' + A class method that can be used to search users + based on their email addresses since it is unique. + ''' + return cls.query.filter_by(email=email).one() + + @classmethod + def by_username(cls, username): + ''' + A class method that permits to search users + based on their username attribute. + ''' + return cls.query.filter_by(username=username).one() + + # If we're going to do logging here, we'll have to pass the person that did the applying. + def apply(cls, group, requester): + ''' + Apply a person to a group + ''' + if group in cls.memberships: + raise fas.ApplyError, _('user is already in this group') + else: + role = PersonRoles() + role.role_status = 'unapproved' + role.role_type = 'user' + role.member = cls + role.group = group + + def upgrade(cls, group, requester): + ''' + Upgrade a user in a group - requester for logging purposes + ''' + if not group in cls.memberships: + raise fas.UpgradeError, _('user is not a member') + else: + role = PersonRoles.query.filter_by(member=cls, group=group).one() + if role.role_type == 'administrator': + raise fas.UpgradeError, _('administrators cannot be upgraded any further') + elif role.role_type == 'sponsor': + role.role_type = 'administrator' + elif role.role_type == 'user': + role.role_type = 'sponsor' + + def downgrade(cls, group, requester): + ''' + Downgrade a user in a group - requester for logging purposes + ''' + if not group in cls.memberships: + raise fas.DowngradeError, _('user is not a member') + else: + role = PersonRoles.query.filter_by(member=cls, group=group).one() + if role.role_type == 'user': + raise fas.DowngradeError, _('users cannot be downgraded any further') + elif role.role_type == 'sponsor': + role.role_type = 'user' + elif role.role_type == 'administrator': + role.role_type = 'sponsor' + + def sponsor(cls, group, requester): + # If we want to do logging, this might be the place. + if not group in cls.unapproved_memberships: + raise fas.SponsorError, _('user is not an unapproved member') + role = PersonRoles.query.filter_by(member=cls, group=group).one() + role.role_status = 'approved' + role.sponsor = requester + role.approval = datetime.now(pytz.utc) + cls._handle_auto_add(group, requester) + + def _handle_auto_add(cls, group, requester): + """ + Handle automatic group approvals + """ + auto_approve_groups = config.get('auto_approve_groups') + associations = auto_approve_groups.split('|') + approve_group_queue = [] + for association in associations: + (groupname, approve_groups) = association.split(':', 1) + if groupname == group.name: + approve_group_queue.extend(approve_groups.split(',')) + for groupname in approve_group_queue: + approve_group = Groups.by_name(groupname) + cls._auto_add(approve_group, requester) + + def _auto_add(cls, group, requester): + """ + Ensure that a person is approved in a group + """ + try: + role = PersonRoles.query.filter_by(member=cls, group=group).one() + if role.role_status != 'approved': + role.role_status = 'approved' + role.sponsor = requester + role.approval = datetime.now(pytz.utc) + except InvalidRequestError: + role = PersonRoles() + role.role_status = 'approved' + role.role_type = 'user' + role.member = cls + role.group = group + + def remove(cls, group, requester): + if not group in cls.memberships: + raise fas.RemoveError, _('user is not a member') + else: + role = PersonRoles.query.filter_by(member=cls, group=group).one() + session.delete(role) + + def __repr__(cls): + return "User(%s,%s)" % (cls.username, cls.human_name) + + def __json__(self): + '''We want to make sure we keep a tight reign on sensistive information. + Thus we strip out certain information unless a user is an admin or the + current user. + + Current access restrictions + =========================== + + Anonymous users can see: + :id: The id in the account system and on the shell servers + :username: Username in FAS + :human_name: Human name of the person + :comments: Comments that the user leaves about themselves + :creation: Date this account was created + :ircnick: User's nickname on IRC + :last_seen: timestamp the user last logged into anything tied to + the account system + :status: Whether the user is active, inactive, on vacation, etc + :status_change: timestamp that the status was last updated + :locale: User's default locale for Fedora Services + :timezone: User's timezone + :latitude: Used for constructing maps of contributors + :longitude: Used for contructing maps of contributors + + Authenticated Users add: + :ssh_key: Public key for connecting to over ssh + :gpg_keyid: gpg key of the user + :affiliation: company or group the user wishes to identify with + :certificate_serial: serial number of the user's Fedora SSL + Certificate + + User Themselves add: + :password: hashed password to identify the user + :passwordtoken: used when the user needs to reset a password + :password_changed: last time the user changed the password + :postal_address: user's postal address + :telephone: user's telephone number + :facsimile: user's FAX number + + Admins gets access to this final field as well: + :internal_comments: Comments an admin wants to write about a user + + Note: There are a few other resources that are not located directly in + the People structure that you are likely to want to pass to consuming + code like email address and groups. Please see the documentation on + SABase.__json__() to find out how to set jsonProps to handle those. + ''' + props = super(People, self).__json__() + if not identity.in_group('admin'): + # Only admins can see internal_comments + del props['internal_comments'] + del props['emailtoken'] + del props['passwordtoken'] + if identity.current.anonymous: + # Anonymous users can't see any of these + del props['email'] + del props['unverified_email'] + del props['ssh_key'] + del props['gpg_keyid'] + del props['affiliation'] + del props['certificate_serial'] + del props['password'] + del props['password_changed'] + del props['postal_address'] + del props['telephone'] + del props['facsimile'] + # TODO: Are we still doing the fas-system thing? I think I saw a systems users somewhere... + elif not identity.current.user.username == self.username and 'fas-system' not in identity.current.groups: + # Only an admin or the user themselves can see these fields + del props['unverified_email'] + del props['password'] + del props['postal_address'] + del props['password_changed'] + del props['telephone'] + del props['facsimile'] + + return props + + memberships = association_proxy('roles', 'group') + approved_memberships = association_proxy('approved_roles', 'group') + unapproved_memberships = association_proxy('unapproved_roles', 'group') + +class PersonRoles(SABase): + '''Record people that are members of groups.''' + def __repr__(cls): + return "PersonRole(%s,%s,%s,%s)" % (cls.member.username, cls.group.name, cls.role_type, cls.role_status) + groupname = association_proxy('group', 'name') + +class Configs(SABase): + '''Configs for applications that a Fedora Contributor uses.''' + pass + +class Groups(SABase): + '''Group that people can belong to.''' + + @classmethod + def by_id(cls, id): + ''' + A class method that can be used to search groups + based on their unique id + ''' + return cls.query.filter_by(id=id).one() + + @classmethod + def by_email_address(cls, email): + ''' + A class method that can be used to search groups + based on their email addresses since it is unique. + ''' + return cls.query.filter_by(email=email).one() + + + @classmethod + def by_name(cls, name): + ''' + A class method that permits to search groups + based on their name attribute. + ''' + return cls.query.filter_by(name=name).one() + + def __repr__(cls): + return "Groups(%s,%s)" % (cls.name, cls.display_name) + + # People in the group + people = association_proxy('roles', 'member') + # Groups in the group + groups = association_proxy('group_members', 'member') + # Groups that this group belongs to + memberships = association_proxy('group_roles', 'group') + +class GroupRoles(SABase): + '''Record groups that are members of other groups.''' + pass + +class BugzillaQueue(SABase): + '''Queued up changes that need to be applied to bugzilla.''' + pass + +class Log(SABase): + '''Write simple logs of changes to the database.''' + pass + +class Requests(SABase): + ''' + Requests for certain resources may be restricted based on the user or host. + ''' + pass + +# +# Classes for mapping arbitrary selectables (This is similar to a view in +# python rather than in the db +# + +class ApprovedRoles(PersonRoles): + '''Only display roles that are approved.''' + pass + +class UnApprovedRoles(PersonRoles): + '''Only show Roles that are not approved.''' + pass + +# +# Classes for the SQLAlchemy Visit Manager +# + +class Visit(SABase): + '''Track how many people are visiting the website. + + It doesn't currently make sense for us to track this here so we clear this + table of stale records every hour. + ''' + @classmethod + def lookup_visit(cls, visit_key): + return cls.query.get(visit_key) + +class VisitIdentity(SABase): + '''Associate a user with a visit cookie. + + This allows users to log in to app. + ''' + pass + +# +# set up mappers between tables and classes +# + +# +# mappers for filtering roles +# +mapper(ApprovedRoles, ApprovedRolesSelect, properties = { + 'group': relation(Groups, backref='approved_roles', lazy = False) + }) +mapper(UnApprovedRoles, UnApprovedRolesSelect, properties = { + 'group': relation(Groups, backref='unapproved_roles', lazy = False) + }) + +mapper(People, PeopleTable, properties = { + # This name is kind of confusing. It's to allow person.group_roles['groupname'] in order to make auth.py (hopefully) slightly faster. + 'group_roles': relation(PersonRoles, + collection_class = attribute_mapped_collection('groupname'), + primaryjoin = PeopleTable.c.id==PersonRolesTable.c.person_id), + 'approved_roles': relation(ApprovedRoles, backref='member', + primaryjoin = PeopleTable.c.id==ApprovedRoles.c.person_id), + 'unapproved_roles': relation(UnApprovedRoles, backref='member', + primaryjoin = PeopleTable.c.id==UnApprovedRoles.c.person_id) + }) +mapper(PersonRoles, PersonRolesTable, properties = { + 'member': relation(People, backref = 'roles', lazy = False, + primaryjoin=PersonRolesTable.c.person_id==PeopleTable.c.id), + 'group': relation(Groups, backref='roles', lazy = False, + primaryjoin=PersonRolesTable.c.group_id==GroupsTable.c.id), + 'sponsor': relation(People, uselist=False, + primaryjoin = PersonRolesTable.c.sponsor_id==PeopleTable.c.id) + }) +mapper(Configs, ConfigsTable, properties = { + 'person': relation(People, backref = 'configs') + }) +mapper(Groups, GroupsTable, properties = { + 'owner': relation(People, uselist=False, + primaryjoin = GroupsTable.c.owner_id==PeopleTable.c.id), + 'prerequisite': relation(Groups, uselist=False, + primaryjoin = GroupsTable.c.prerequisite_id==GroupsTable.c.id) + }) +# GroupRoles are complex because the group is a member of a group and thus +# is referencing the same table. +mapper(GroupRoles, GroupRolesTable, properties = { + 'member': relation(Groups, backref = 'group_roles', + primaryjoin = GroupsTable.c.id==GroupRolesTable.c.member_id), + 'group': relation(Groups, backref = 'group_members', + primaryjoin = GroupsTable.c.id==GroupRolesTable.c.group_id), + 'sponsor': relation(People, uselist=False, + primaryjoin = GroupRolesTable.c.sponsor_id==PeopleTable.c.id) + }) +mapper(BugzillaQueue, BugzillaQueueTable, properties = { + 'group': relation(Groups, backref = 'pending'), + 'person': relation(People, backref = 'pending'), + ### TODO: test to be sure SQLAlchemy only loads the backref on demand + 'author': relation(People, backref='changes') + }) +mapper(Requests, RequestsTable, properties = { + 'person': relation(People, backref='requests') + }) +mapper(Log, LogTable) + +# TurboGears Identity +mapper(Visit, visits_table) +mapper(VisitIdentity, visit_identity_table, + properties=dict(users=relation(People, backref='visit_identity'))) diff --git a/fas/build/lib/fas/openid_fas.py b/fas/build/lib/fas/openid_fas.py new file mode 100644 index 0000000..f9ca8c7 --- /dev/null +++ b/fas/build/lib/fas/openid_fas.py @@ -0,0 +1,112 @@ +import turbogears +from turbogears import controllers, expose, paginate, identity, redirect, widgets, validate, validators, error_handler, config +from cherrypy import session + +import cherrypy + +from openid.server.server import Server as OpenIDServer +from openid.server.server import BROWSER_REQUEST_MODES +from openid.server.server import OPENID_PREFIX +from openid.store.filestore import FileOpenIDStore + +from fas.auth import * + +from fas.user import KnownUser + +class UserID(validators.Schema): + targetname = KnownUser + +class OpenID(controllers.Controller): + + def __init__(self): + '''Create a OpenID Controller.''' + store = FileOpenIDStore(config.get('openidstore')) + self.openid_server = OpenIDServer(store)#, turbogears.url('/openid/server')) + + @expose() + def index(self): + turbogears.redirect('/openid/about') + return dict() + + @expose(template="fas.templates.openid.about") + def about(self): + '''Display an explanatory message about the OpenID service''' + username = turbogears.identity.current.user_name + return dict(username=username) + + @expose(template="genshi-text:fas.templates.openid.auth", format="text", content_type='text/plain; charset=utf-8') + def server(self, **query): + '''Perform OpenID auth''' + openid_server = self.openid_server + openid_query = {} + openid_request = None + if not session.has_key('openid_trusted'): + session['openid_trusted'] = [] + if query.has_key('url') and query.has_key('trusted') and query['trusted'] == 'allow': + session['openid_trusted'].append(query['url']) + if query.has_key('openid'): + try: + for key in query['openid'].keys(): + openid_key = OPENID_PREFIX + key + openid_query[openid_key] = query['openid'][key] + openid_request = openid_server.decodeRequest(openid_query) + session['openid_request'] = openid_request + except KeyError: + turbogears.flash(_('The OpenID request could not be decoded.')) + elif session.has_key('openid_request'): + openid_request = session['openid_request'] + if openid_request is None: + turbogears.redirect('/openid/about') + return dict() + else: + openid_response = None + if openid_request.mode in BROWSER_REQUEST_MODES: + username = turbogears.identity.current.user_name; + url = None + if username is not None: + url = config.get('base_url') + turbogears.url('/openid/id/%s' % username) + if openid_request.identity == url: + if openid_request.trust_root in session['openid_trusted']: + openid_response = openid_request.answer(True) + elif openid_request.immediate: + openid_response = openid_request.answer(False, server_url=config.get('base_url') + turbogears.url('/openid/server')) + else: + if query.has_key('url') and not query.has_key('allow'): + openid_response = openid_request.answer(False, server_url=config.get('base_url') + turbogears.url('/openid/server')) + else: + turbogears.redirect('/openid/trusted', url=openid_request.trust_root) + elif openid_request.immediate: + openid_response = openid_request.answer(False, server_url=config.get('base_url') + turbogears.url('/openid/server')) + else: + turbogears.redirect('/openid/login') + return dict() + else: + openid_response = openid_server.handleRequest(openid_request) + web_response = openid_server.encodeResponse(openid_response) + for name, value in web_response.headers.items(): + cherrypy.response.headers[name] = value; + cherrypy.response.status = web_response.code + return dict(body=web_response.body) + + @identity.require(turbogears.identity.not_anonymous()) + @expose(template="fas.templates.openid.trusted") + def trusted(self, url): + '''Ask the user if they trust a site for OpenID authentication''' + return dict(url=url) + + @identity.require(turbogears.identity.not_anonymous()) + @expose() + def login(self): + '''This exists only to make the user login and then redirect to /openid/server''' + turbogears.redirect('/openid/server') + return dict() + + + @expose(template="fas.templates.openid.id") + @validate(validators=UserID()) + def id(self, username): + '''The "real" OpenID URL''' + person = People.by_username(username) + server = config.get('base_url') + turbogears.url('/openid/server') + return dict(person=person, server=server) + diff --git a/fas/build/lib/fas/openssl_fas.py b/fas/build/lib/fas/openssl_fas.py new file mode 100644 index 0000000..1681d22 --- /dev/null +++ b/fas/build/lib/fas/openssl_fas.py @@ -0,0 +1,82 @@ +# Pretty much all copied from pyOpenSSL's certgen.py example and func's certs.py + +from OpenSSL import crypto +TYPE_RSA = crypto.TYPE_RSA +TYPE_DSA = crypto.TYPE_DSA + +def retrieve_key_from_file(keyfile): + fo = open(keyfile, 'r') + buf = fo.read() + keypair = crypto.load_privatekey(crypto.FILETYPE_PEM, buf) + return keypair + +def retrieve_cert_from_file(certfile): + fo = open(certfile, 'r') + buf = fo.read() + cert = crypto.load_certificate(crypto.FILETYPE_PEM, buf) + return cert + +def createKeyPair(type, bits): + """ + Create a public/private key pair. + + Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA + bits - Number of bits to use in the key + Returns: The public/private key pair in a PKey object + """ + pkey = crypto.PKey() + pkey.generate_key(type, bits) + return pkey + +def createCertRequest(pkey, digest="md5", **name): + """ + Create a certificate request. + + Arguments: pkey - The key to associate with the request + digest - Digestion method to use for signing, default is md5 + **name - The name of the subject of the request, possible + arguments are: + C - Country name + ST - State or province name + L - Locality name + O - Organization name + OU - Organizational unit name + CN - Common name + emailAddress - E-mail address + Returns: The certificate request in an X509Req object + """ + req = crypto.X509Req() + subj = req.get_subject() + + for (key,value) in name.items(): + setattr(subj, key, value) + + req.set_pubkey(pkey) + req.sign(pkey, digest) + return req + +def createCertificate(req, (issuerCert, issuerKey), serial, (notBefore, notAfter), digest="md5"): + """ + Generate a certificate given a certificate request. + + Arguments: req - Certificate reqeust to use + issuerCert - The certificate of the issuer + issuerKey - The private key of the issuer + serial - Serial number for the certificate + notBefore - Timestamp (relative to now) when the certificate + starts being valid + notAfter - Timestamp (relative to now) when the certificate + stops being valid + digest - Digest method to use for signing, default is md5 + Returns: The signed certificate in an X509 object + """ + cert = crypto.X509() + cert.set_serial_number(serial) + cert.gmtime_adj_notBefore(notBefore) + cert.gmtime_adj_notAfter(notAfter) + cert.set_issuer(issuerCert.get_subject()) + cert.set_subject(req.get_subject()) + cert.set_pubkey(req.get_pubkey()) + cert.sign(issuerKey, digest) + return cert + diff --git a/fas/build/lib/fas/release.py b/fas/build/lib/fas/release.py new file mode 100644 index 0000000..35e271d --- /dev/null +++ b/fas/build/lib/fas/release.py @@ -0,0 +1,18 @@ +''' +Release information about the Fedora Accounts System +''' + +VERSION = '0.8.1' +NAME = 'fas' +DESCRIPTION = 'The Fedora Account System' +LONG_DESCRIPTION = ''' +Manage the accounts of contributors to the Fedora Project. +''' +AUTHOR = 'Ricky Zhou, Mike McGrath, and Toshio Kuratomi' +EMAIL = 'fedora-infrastructure-list@fedoraproject.org' +COPYRIGHT = '2007-2008 Red Hat, Inc.' + +# if it's open source, you might want to specify these +URL = 'https://admin.fedoraproject.org/accounts/' +DOWNLOAD_URL = 'https://fas2.fedorahosted.org/' +LICENSE = 'GPLv2' diff --git a/fas/build/lib/fas/safasprovider.py b/fas/build/lib/fas/safasprovider.py new file mode 100644 index 0000000..ac0220e --- /dev/null +++ b/fas/build/lib/fas/safasprovider.py @@ -0,0 +1,219 @@ +# -*- coding: utf-8 -*- +# +# Copyright © 2007-2008 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, modify, +# copy, or redistribute it subject to the terms and conditions of the GNU +# General Public License v.2. This program is distributed in the hope that it +# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the +# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the GNU General Public License for more details. You should have +# received a copy of the GNU General Public License along with this program; +# if not, write to the Free Software Foundation, Inc., 51 Franklin Street, +# Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat trademarks that are +# incorporated in the source code or documentation are not subject to the GNU +# General Public License and may only be used or replicated with the express +# permission of Red Hat, Inc. +# +# Red Hat Author(s): Toshio Kuratomi +# + +''' +This plugin provides authentication of passwords against the Fedora Account +System. +''' + + + +from sqlalchemy.orm import class_mapper +from turbogears import config, identity +from turbogears.identity.saprovider import SqlAlchemyIdentity, \ + SqlAlchemyIdentityProvider +from turbogears.database import session +from turbogears.util import load_class + +import gettext +t = gettext.translation('python-fedora', '/usr/share/locale', fallback=True) +_ = t.ugettext + +import crypt + +import logging +log = logging.getLogger('turbogears.identity.safasprovider') + +try: + set, frozenset +except NameError: + from sets import Set as set, ImmutableSet as frozenset + +# Global class references -- +# these will be set when the provider is initialised. +user_class = None +visit_identity_class = None + +class SaFasIdentity(SqlAlchemyIdentity): + def __init__(self, visit_key, user=None): + super(SaFasIdentity, self).__init__(visit_key, user) + + def _get_user(self): + try: + return self._user + except AttributeError: + # User hasn't already been set + pass + # Attempt to load the user. After this code executes, there *WILL* be + # a _user attribute, even if the value is None. + ### TG: Difference: Can't use the inherited method b/c of global var + visit = visit_identity_class.query.filter_by(visit_key = self.visit_key).first() + if not visit: + self._user = None + return None + self._user = user_class.query.get(visit.user_id) + return self._user + user = property(_get_user) + + def _get_user_name(self): + if not self.user: + return None + ### TG: Difference: Different name for the field + return self.user.username + user_name = property(_get_user_name) + + def _get_groups(self): + try: + return self._groups + except AttributeError: + # Groups haven't been computed yet + pass + if not self.user: + self._groups = frozenset() + else: + ### TG: Difference. Our model has a many::many for people:groups + # And an association proxy that links them together + self._groups = frozenset([g.name for g in self.user.approved_memberships]) + return self._groups + groups = property(_get_groups) + + def logout(self): + ''' + Remove the link between this identity and the visit. + ''' + if not self.visit_key: + return + try: + ### TG: Difference: Can't inherit b/c this uses a global var + visit = visit_identity_class.query.filter_by(visit_key=self.visit_key).first() + session.delete(visit) + # Clear the current identity + anon = SqlAlchemyIdentity(None,None) + identity.set_current_identity(anon) + except: + pass + else: + session.flush() + +class SaFasIdentityProvider(SqlAlchemyIdentityProvider): + ''' + IdentityProvider that authenticates users against the fedora account system + ''' + def __init__(self): + global visit_identity_class + global user_class + + user_class_path = config.get("identity.saprovider.model.user", None) + user_class = load_class(user_class_path) + visit_identity_class_path = config.get("identity.saprovider.model.visit", None) + log.info(_("Loading: %(visitmod)s") % \ + {'visitmod': visit_identity_class_path}) + visit_identity_class = load_class(visit_identity_class_path) + + def create_provider_model(self): + ''' + Create the database tables if they don't already exist. + ''' + class_mapper(user_class).local_table.create(checkfirst=True) + class_mapper(visit_identity_class).local_table.create(checkfirst=True) + + def validate_identity(self, user_name, password, visit_key): + ''' + Look up the identity represented by user_name and determine whether the + password is correct. + + Must return either None if the credentials weren't valid or an object + with the following properties: + user_name: original user name + user: a provider dependant object (TG_User or similar) + groups: a set of group IDs + permissions: a set of permission IDs + ''' + user = user_class.query.filter_by(username=user_name).first() + if not user: + log.warning("No such user: %s", user_name) + return None + if not self.validate_password(user, user_name, password): + log.info("Passwords don't match for user: %s", user_name) + return None + + log.info("associating user (%s) with visit (%s)", user.username, + visit_key) + # Link the user to the visit + link = visit_identity_class.query.filter_by(visit_key=visit_key).first() + if not link: + link = visit_identity_class() + link.visit_key = visit_key + link.user_id = user.id + else: + link.user_id = user.id + session.flush() + return SaFasIdentity(visit_key, user) + + def validate_password(self, user, user_name, password): + ''' + Check the supplied user_name and password against existing credentials. + Note: user_name is not used here, but is required by external + password validation schemes that might override this method. + If you use SqlAlchemyIdentityProvider, but want to check the passwords + against an external source (i.e. PAM, LDAP, Windows domain, etc), + subclass SqlAlchemyIdentityProvider, and override this method. + + Arguments: + :user: User information. Not used. + :user_name: Given username. + :password: Given, plaintext password. + + Returns: True if the password matches the username. Otherwise False. + Can return False for problems within the Account System as well. + ''' + + return user.password == crypt.crypt(password, user.password) + + def load_identity(self, visit_key): + '''Lookup the principal represented by visit_key. + + Arguments: + :visit_key: The session key for whom we're looking up an identity. + + Must return an object with the following properties: + user_name: original user name + user: a provider dependant object (TG_User or similar) + groups: a set of group IDs + permissions: a set of permission IDs + ''' + return SaFasIdentity(visit_key) + + def anonymous_identity(self): + ''' + Must return an object with the following properties: + user_name: original user name + user: a provider dependant object (TG_User or similar) + groups: a set of group IDs + permissions: a set of permission IDs + ''' + + return SaFasIdentity(None) + + def authenticated_identity(self, user): + ''' + Constructs Identity object for user that has no associated visit_key. + ''' + return SaFasIdentity(None, user) diff --git a/fas/build/lib/fas/templates/__init__.py b/fas/build/lib/fas/templates/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fas/build/lib/fas/templates/about.html b/fas/build/lib/fas/templates/about.html new file mode 100644 index 0000000..d6dbd9f --- /dev/null +++ b/fas/build/lib/fas/templates/about.html @@ -0,0 +1,17 @@ + + + + + ${_('About FAS')} + + +

${_('FAS - The Open Account System')}

+

${_('''FAS is designed around an open architecture. Unlike the traditional account systems where a single admin or group of admins decide who gets to be in what group, FAS is completely designed to be self operating per team. Every group is given at least one administrator who can then approve other people in the group. Also, unlike traditional account systems. FAS allows people to apply for the groups they want to be in. This paridigm is interesting as it allows anyone to find out who is in what groups and contact them. This openness is brought over from the same philosophies that make Open Source popular.''')}

+

${_('Etiquette')}

+

${_("People shouldn't assume that by applying for a group that they're then in that group. Consider it like applying for another job. It often takes time. For best odds of success, learn about the group you're applying for and get to know someone in the group. Find someone with sponsor or admin access and ask them if they'd have time to mentor you. Plan on spending at least a few days learning about the group, doing a mundain task, participating on the mailing list. Sometimes this process can take weeks depending on the group. It's best to know you will get sponsored before you apply.")}

+

${_('Users, Sponsors, Administrators')}

+

${_('''Once you're in the group, you're in the group. Sponsorship and Administrators typically have special access in the group in questions. Some groups consider sponsorship level to be of a higher involvement, partial ownership of the group for example. But as far as the account system goes the disctinction is easy. Sponsors can approve new users and make people into sponsors. They cannot, however, downgrade or remove other sponsors. They also cannot change administrators in any way. Administrators can do anything to anyone in the group.''')}

+ + diff --git a/fas/build/lib/fas/templates/cla/__init__.py b/fas/build/lib/fas/templates/cla/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fas/build/lib/fas/templates/cla/cla.html b/fas/build/lib/fas/templates/cla/cla.html new file mode 100644 index 0000000..34643a3 --- /dev/null +++ b/fas/build/lib/fas/templates/cla/cla.html @@ -0,0 +1,82 @@ +
+

The Fedora Project + Individual Contributor License Agreement (CLA) +

+ http://fedoraproject.org/wiki/Legal/Licenses/CLA +

+ Thank you for your interest in The Fedora Project (the "Project"). In order to clarify the intellectual property license granted with Contributions from any person or entity, Red hat, Inc. ("Red Hat"), as maintainer of the Project, must have a Contributor License Agreement (CLA) on file that has been signed by each Contributor, indicating agreement to the license terms below. This license is for Your protection as a Contributor as well as the protection of the Project and its users; it does not change your rights to use your own Contributions for any other purpose. +

+

+ If you have not already done so, please complete an original signed Agreement. Use black ink, and hand-print or type the items other than the signature. Send the completed Agreement to +

+
+ Fedora Project, c/o Red Hat, Inc.,
+ Attn: Legal Affairs
+ 1801 Varsity Drive
+ Raleigh, North Carolina, 27606 U.S.A. +
+

+ If necessary, you may send it by facsimile to the Project at +1-919-754-3704 or e-mail a signed pdf copy of the document to fedora-legal@redhat.com. Please read this document carefully before signing and keep a copy for your records. +

+

+ Full name: ${person.human_name}
+ E-Mail: ${person.email}
+ Address: ${person.postal_address}
+ Telephone: ${person.telephone} + +

+

+ You and the Project hereby accept and agree to the following terms and conditions: +

+
    +
  1. + Contributors and Contributions. +
      +
    1. + The Project and any individual or legal entity that voluntarily submits to the Project a Contribution are collectively addressed herein as "Contributors". For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. +
    2. +
    3. + A "Contribution" is any original work, including any modification or addition to an existing work, that has been submitted for inclusion in, or documentation of, any of the products owned or managed by the Project, where such work originates from that particular Contributor or from some entity acting on behalf of that Contributor. +
    4. +
    5. + A Contribution is "submitted" when any form of electronic, verbal, or written communication is sent to the Project, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of discussing or improving software or documentation of the Project, but excluding communication that is conspicuously marked or otherwise designated in writing by you as "Not a Contribution." +
    6. +
    7. + Any Contribution submitted by you to the Project shall be under the terms and conditions of this License, without any additional terms or conditions, unless you explicitly state otherwise in the submission. +
    8. +
    +
  2. +
  3. + Contributor Grant of License. You hereby grant to Red Hat, Inc., on behalf of the Project, and to recipients of software distributed by the Project: +
      +
    1. + a perpetual, non-exclusive, worldwide, fully paid-up, royalty free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute your Contribution and such derivative works; and, +
    2. +
    3. + a perpetual, non-exclusive, worldwide, fully paid-up, royalty free, irrevocable (subject to Section 3) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer your Contribution and derivative works thereof, where such license applies only to those patent claims licensable by you that are necessarily infringed by your Contribution alone or by combination of your Contribution with the work to which you submitted the Contribution. Except for the license granted in this section, you reserve all right, title and interest in and to your Contributions. +
    4. +
    +
  4. +
  5. + Reciprocity. As of the date any such litigation is filed, your patent grant shall immediately terminate with respect to any party that institutes patent litigation against you (including a cross-claim or counterclaim in a lawsuit) alleging that your Contribution, or the work to which you have contributed, constitutes direct or contributory patent infringement. +
  6. +
  7. + You represent that you are legally entitled to grant the above license. If your employer(s) has rights to intellectual property that you create that includes your Contributions, you represent that you have received permission to make Contributions on behalf of that employer, that your employer has waived such rights for your Contributions to the Project, or that your employer has executed a separate Corporate CLA with the Project. +
  8. +
  9. + You represent that each of your Contributions is your original creation (see section 7 for submissions on behalf of others). You represent that your Contribution submission(s) include complete details of any third-party license or other restriction (including, but not limited to, related copyright, atents and trademarks) of which you are personally aware and which are associated with any part of your Contribution. +
  10. +
  11. + You are not expected to provide support for your Contributions, except to the extent you desire to provide support. You may provide support for free, for a fee, or not at all. Your Contributions are provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. +
  12. +
  13. + Should you wish to submit work that is not your original creation, you may submit it to the Project separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which you are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [named here]". +
  14. +
  15. + You agree to notify the Project of any facts or circumstances of which you become aware that would make these representations inaccurate in any respect. +
  16. +
  17. + The Project is under no obligations to accept and include every contribution. +
  18. +
+
diff --git a/fas/build/lib/fas/templates/cla/cla.txt b/fas/build/lib/fas/templates/cla/cla.txt new file mode 100644 index 0000000..7d6d482 --- /dev/null +++ b/fas/build/lib/fas/templates/cla/cla.txt @@ -0,0 +1,145 @@ + The Fedora Project + Individual Contributor License Agreement (CLA) + http://fedoraproject.org/wiki/Legal/Licenses/CLA + + Thank you for your interest in The Fedora Project (the + "Project"). In order to clarify the intellectual property license + granted with Contributions from any person or entity, Red hat, + Inc. ("Red Hat"), as maintainer of the Project, must have a + Contributor License Agreement (CLA) on file that has been signed + by each Contributor, indicating agreement to the license terms + below. This license is for Your protection as a Contributor as + well as the protection of the Project and its users; it does not + change your rights to use your own Contributions for any other + purpose. + + If you have not already done so, please complete an original signed + Agreement. Use black ink, and hand-print or type the items other than + the signature. Send the completed Agreement to + + Fedora Project, c/o Red Hat, Inc., + Attn: Legal Affairs + 1801 Varsity Drive + Raleigh, North Carolina, 27606 U.S.A. + + If necessary, you may send it by facsimile to the Project at + +1-919-754-3704 or e-mail a signed pdf copy of the document to + fedora-legal@redhat.com. Please read this document carefully before + signing and keep a copy for your records. + + Full name: ${person.human_name} E-Mail: ${person.email} + + Address: +${person.postal_address} + + Telephone: ${person.telephone} + + Facsimile: ${person.facsimile} + + You and the Project hereby accept and agree to the following terms and conditions: + + 1. Contributors and Contributions. + + A. The Project and any individual or legal entity that + voluntarily submits to the Project a Contribution are + collectively addressed herein as "Contributors". For legal + entities, the entity making a Contribution and all other + entities that control, are controlled by, or are under common + control with that entity are considered to be a single + Contributor. For the purposes of this definition, "control" + means (i) the power, direct or indirect, to cause the direction + or management of such entity, whether by contract or otherwise, + or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such + entity. + + B. A "Contribution" is any original work, including any + modification or addition to an existing work, that has been + submitted for inclusion in, or documentation of, any of the + products owned or managed by the Project, where such work + originates from that particular Contributor or from some entity + acting on behalf of that Contributor. + + C. A Contribution is "submitted" when any form of electronic, + verbal, or written communication is sent to the Project, + including but not limited to communication on electronic + mailing lists, source code control systems, and issue tracking + systems that are managed by, or on behalf of, the Project for + the purpose of discussing or improving software or + documentation of the Project, but excluding communication that + is conspicuously marked or otherwise designated in writing by + you as "Not a Contribution." + + D. Any Contribution submitted by you to the Project shall be + under the terms and conditions of this License, without any + additional terms or conditions, unless you explicitly state + otherwise in the submission. + + 2. Contributor Grant of License. You hereby grant to Red Hat, + Inc., on behalf of the Project, and to recipients of software + distributed by the Project: + + (a) a perpetual, non-exclusive, worldwide, fully paid-up, + royalty free, irrevocable copyright license to reproduce, + prepare derivative works of, publicly display, publicly + perform, sublicense, and distribute your Contribution and such + derivative works; and, + + (b) a perpetual, non-exclusive, worldwide, fully paid-up, + royalty free, irrevocable (subject to Section 3) patent license + to make, have made, use, offer to sell, sell, import, and + otherwise transfer your Contribution and derivative works + thereof, where such license applies only to those patent claims + licensable by you that are necessarily infringed by your + Contribution alone or by combination of your Contribution with + the work to which you submitted the Contribution. Except for + the license granted in this section, you reserve all right, + title and interest in and to your Contributions. + + 3. Reciprocity. As of the date any such litigation is filed, your + patent grant shall immediately terminate with respect to any + party that institutes patent litigation against you (including + a cross-claim or counterclaim in a lawsuit) alleging that your + Contribution, or the work to which you have contributed, + constitutes direct or contributory patent infringement. + + 4. You represent that you are legally entitled to grant the above + license. If your employer(s) has rights to intellectual + property that you create that includes your Contributions, you + represent that you have received permission to make + Contributions on behalf of that employer, that your employer + has waived such rights for your Contributions to the Project, + or that your employer has executed a separate Corporate CLA + with the Project. + + 5. You represent that each of your Contributions is your original + creation (see section 7 for submissions on behalf of others). + You represent that your Contribution submission(s) include + complete details of any third-party license or other + restriction (including, but not limited to, related copyright, + atents and trademarks) of which you are personally aware and + which are associated with any part of your Contribution. + + 6. You are not expected to provide support for your Contributions, + except to the extent you desire to provide support. You may + provide support for free, for a fee, or not at all. Your + Contributions are provided on an "AS IS" BASIS, WITHOUT + WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or + conditions of NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR + A PARTICULAR PURPOSE. + + 7. Should you wish to submit work that is not your original + creation, you may submit it to the Project separately from any + Contribution, identifying the complete details of its source + and of any license or other restriction (including, but not + limited to, related patents, trademarks, and license + agreements) of which you are personally aware, and + conspicuously marking the work as "Submitted on behalf of a + third-party: [named here]". + + 8. You agree to notify the Project of any facts or circumstances + of which you become aware that would make these representations + inaccurate in any respect. + + 9. The Project is under no obligations to accept and include every contribution. diff --git a/fas/build/lib/fas/templates/cla/index.html b/fas/build/lib/fas/templates/cla/index.html new file mode 100644 index 0000000..ff8f9e6 --- /dev/null +++ b/fas/build/lib/fas/templates/cla/index.html @@ -0,0 +1,26 @@ + + + + + ${_('Fedora Accounts System')} + + +

${_('Fedora Contributor License Agreement')}

+ ${Markup(_('<a href="%(url)s">Text Version</a>') % {'url': tg.url('/cla/text')})} + + ${Markup(_('<a href="%(url)s">Text Version</a>') % {'url': tg.url('/cla/text')})} +

+ ${Markup(_('You have already sucessfully complete the CLA.') % {'url': tg.url('/cla/text')})} +

+ +
+
+ + +
+
+
+ + diff --git a/fas/build/lib/fas/templates/error.html b/fas/build/lib/fas/templates/error.html new file mode 100644 index 0000000..c72b965 --- /dev/null +++ b/fas/build/lib/fas/templates/error.html @@ -0,0 +1,25 @@ + + + + + ${_('Fedora Accounts System')} + + + +

${_('Error!')}

+

${_('The following error(s) have occured with your request:')}

+
    +
  • + ${field}: ${str(error)} +
  • +
+ + diff --git a/fas/build/lib/fas/templates/group/__init__.py b/fas/build/lib/fas/templates/group/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fas/build/lib/fas/templates/group/dump.txt b/fas/build/lib/fas/templates/group/dump.txt new file mode 100644 index 0000000..7219bd4 --- /dev/null +++ b/fas/build/lib/fas/templates/group/dump.txt @@ -0,0 +1,3 @@ +#for person in sorted(people) +${person.username},${person.email},${person.human_name},user,0 +#end diff --git a/fas/build/lib/fas/templates/group/edit.html b/fas/build/lib/fas/templates/group/edit.html new file mode 100644 index 0000000..8df9316 --- /dev/null +++ b/fas/build/lib/fas/templates/group/edit.html @@ -0,0 +1,55 @@ + + + + + ${_('Edit Group')} + + +

${_('Edit Group: %s') % group.name}

+
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + + +
+
+ + + +   +
+
+ + + +   +
+
+ + + +
+
+ +
+
+ + diff --git a/fas/build/lib/fas/templates/group/invite.html b/fas/build/lib/fas/templates/group/invite.html new file mode 100644 index 0000000..0c537a8 --- /dev/null +++ b/fas/build/lib/fas/templates/group/invite.html @@ -0,0 +1,43 @@ + + + + + ${_('Invite a new community member!')} + + +

${_('Invite a new community member!')}

+
+
+ + ${_('To email:')}
+ ${_('From:')} ${person.email}
+ ${_('Subject:')} Invitation to join the Fedora Team!
+ ${_('Message:')} +
+

+ ${person.human_name} <${person.email}> has invited you to join the Fedora + Project! We are a community of users and developers who produce a + complete operating system from entirely free and open source software + (FOSS). ${person.human_name} thinks that you have knowledge and skills + that make you a great fit for the Fedora community, and that you might + be interested in contributing. +

+

+ How could you team up with the Fedora community to use and develop your + skills? Check out http://fedoraproject.org/join-fedora for some ideas. + Our community is more than just software developers -- we also have a + place for you whether you're an artist, a web site builder, a writer, or + a people person. You'll grow and learn as you work on a team with other + very smart and talented people. +

+

+ Fedora and FOSS are changing the world -- come be a part of it! +

+
+ +
+
+ + diff --git a/fas/build/lib/fas/templates/group/list.html b/fas/build/lib/fas/templates/group/list.html new file mode 100644 index 0000000..59c147e --- /dev/null +++ b/fas/build/lib/fas/templates/group/list.html @@ -0,0 +1,54 @@ + + + + + ${_('Groups List')} + + + + +

Create New Group

+ Create Group +
+ +

${_('List (%s)') % search}

+

${_('Search Groups')}

+
+

${_('"*" is a wildcard (Ex: "cvs*")')}

+
+ + +
+
+

${_('Results')}

+ + + + + + + + + + + + + +
${_('Group')}${_('Description')}${_('Status')}
${group.name}${ group.display_name } + + ${_('Approved')} + ${_('Unapproved')} + + ${_('Apply')} + +
+ + diff --git a/fas/build/lib/fas/templates/group/new.html b/fas/build/lib/fas/templates/group/new.html new file mode 100644 index 0000000..f74862c --- /dev/null +++ b/fas/build/lib/fas/templates/group/new.html @@ -0,0 +1,57 @@ + + + + + ${_('Create a new FAS Group')} + + +

${_('Create a new FAS Group')}

+
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + +
+
+ +   + +
+
+ +   + +
+
+ + + +
+
+ + + +
+
+ +
+
+ + diff --git a/fas/build/lib/fas/templates/group/view.html b/fas/build/lib/fas/templates/group/view.html new file mode 100644 index 0000000..44d4cc8 --- /dev/null +++ b/fas/build/lib/fas/templates/group/view.html @@ -0,0 +1,123 @@ + + + + + ${_('View Group')} + + + +

${group.display_name} (${group.name})

+

+ ${_('My Status:')} + ${_('Approved')} + ${_('Unapproved')} + ${_('Not a Member')} +

+
+
+ + +
+
+ ${_('Remove me')} + +

Group Details ${_('(edit)')}

+
+
+
${_('Name:')}
${group.name} 
+
${_('Description:')}
${group.display_name} 
+
${_('Owner:')}
${group.owner.username} 
+
${_('Type:')}
${group.group_type} 
+
${_('Needs Sponsor:')}
+ ${_('Yes')} + ${_('No')} +  
+
${_('Self Removal:')}
+ ${_('Yes')} + ${_('No')} +  
+
${_('Join Message:')}
${group.joinmsg} 
+
${_('Prerequisite:')}
+
${group.prerequisite.name} 
+
 
+
${_('Created:')}
${group.creation} 
+ +
${_('Add User:')}
+
+
+ + + +
+
+
+
+
+ +

${_('Members')}

+ + + + + + + + + + + + + + + + + + + + + + + + +
${_('Username')}${_('Sponsor')}${_('Date Added')}${_('Date Approved')}${_('Approval')}${_('Role Type')}${_('Action')}
${role[1].member.username}${role[1].sponsor.username}${_('None')}${role[1].creation.astimezone(timezone).strftime('%Y-%m-%d %H:%M:%S %Z')}${role[1].approval.astimezone(timezone).strftime('%Y-%m-%d %H:%M:%S %Z')}${_('None')}${role[1].role_status}${role[1].role_type} +
    +
  • + + ${_('Sponsor')} + + + + ${_('Approve')} + + +
  • +
  • + ${_('Remove')} + +
  • +
  • + ${_('Upgrade')} + +
  • +
  • + ${_('Downgrade')} + +
  • +
+
+ + diff --git a/fas/build/lib/fas/templates/help.html b/fas/build/lib/fas/templates/help.html new file mode 100644 index 0000000..b3dd861 --- /dev/null +++ b/fas/build/lib/fas/templates/help.html @@ -0,0 +1,12 @@ + + + + + ${help[0]} + + + ${XML(help[1])} + + diff --git a/fas/build/lib/fas/templates/home.html b/fas/build/lib/fas/templates/home.html new file mode 100644 index 0000000..a12d0b9 --- /dev/null +++ b/fas/build/lib/fas/templates/home.html @@ -0,0 +1,33 @@ + + + + + ${_('Fedora Accounts System')} + + + +

${_('Todo queue:')}

+ + +
+
    +
  • + ${Markup(_('<strong>%(user)s</strong> requests approval to join <a href="group/view/%(group)s">%(group)s</a>.') % {'user': role.member.username, 'group': group.name, 'group': group.name})} +
  • +
+
+
+
+
    +
  • ${Markup(_('CLA not completed. To become a full Fedora Contributor please <a href="%s">complete the CLA</a>.') % tg.url('/cla/'))}
  • +
  • ${Markup(_('You have not submitted an SSH key, some Fedora resources require an SSH key. Please submit yours by editing <a href="%s">My Account</a>') % tg.url('/user/edit'))}
  • +
+
+ + ${_('Download a client-side certificate')}  + +
+ + diff --git a/fas/build/lib/fas/templates/login.html b/fas/build/lib/fas/templates/login.html new file mode 100644 index 0000000..24bf545 --- /dev/null +++ b/fas/build/lib/fas/templates/login.html @@ -0,0 +1,33 @@ + + + + + ${_('Login to the Fedora Accounts System')} + + + +

${_('Login')}

+

${message}

+
+
+
+
+ + + +
+
+ + + diff --git a/fas/build/lib/fas/templates/master.html b/fas/build/lib/fas/templates/master.html new file mode 100644 index 0000000..4838960 --- /dev/null +++ b/fas/build/lib/fas/templates/master.html @@ -0,0 +1,104 @@ + + + + + + + + + + + + + +
+ + +
+
+ + ${_('Logged in:')} ${tg.identity.user.username} + +
+ +
+
+ +
+
+ ${tg_flash} +
+
+
+ +
+
+ + diff --git a/fas/build/lib/fas/templates/openid/__init__.py b/fas/build/lib/fas/templates/openid/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fas/build/lib/fas/templates/openid/about.html b/fas/build/lib/fas/templates/openid/about.html new file mode 100644 index 0000000..2cbe67f --- /dev/null +++ b/fas/build/lib/fas/templates/openid/about.html @@ -0,0 +1,15 @@ + + + + + ${_('Fedora Accounts System')} + + +

${_('Fedora Project OpenID Provider')}

+

+ ${Markup_('Description goes here, <a href="http://username.fedorapeople.org/">username.fedorapeople.org</a>')} +

+ + diff --git a/fas/build/lib/fas/templates/openid/auth.txt b/fas/build/lib/fas/templates/openid/auth.txt new file mode 100644 index 0000000..34accd5 --- /dev/null +++ b/fas/build/lib/fas/templates/openid/auth.txt @@ -0,0 +1 @@ +${body} diff --git a/fas/build/lib/fas/templates/openid/id.html b/fas/build/lib/fas/templates/openid/id.html new file mode 100644 index 0000000..01a5220 --- /dev/null +++ b/fas/build/lib/fas/templates/openid/id.html @@ -0,0 +1,21 @@ + + + + + ${_('Fedora Accounts System')} + + + +

${_('User %s') % person.username}

+
+
+
${_('Username:')}
+
${person.username}
+
${_('Name:')}
+
${person.human_name}
+
+
+ + diff --git a/fas/build/lib/fas/templates/openid/trusted.html b/fas/build/lib/fas/templates/openid/trusted.html new file mode 100644 index 0000000..0affc19 --- /dev/null +++ b/fas/build/lib/fas/templates/openid/trusted.html @@ -0,0 +1,20 @@ + + + + + ${_('Fedora Accounts System')} + + +

${_('Fedora Project OpenID Provider')}

+
+
+ + +
+ +
+
+ + diff --git a/fas/build/lib/fas/templates/user/__init__.py b/fas/build/lib/fas/templates/user/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fas/build/lib/fas/templates/user/cert.txt b/fas/build/lib/fas/templates/user/cert.txt new file mode 100644 index 0000000..692f231 --- /dev/null +++ b/fas/build/lib/fas/templates/user/cert.txt @@ -0,0 +1,2 @@ +${cert} +${key} diff --git a/fas/build/lib/fas/templates/user/changepass.html b/fas/build/lib/fas/templates/user/changepass.html new file mode 100644 index 0000000..189c024 --- /dev/null +++ b/fas/build/lib/fas/templates/user/changepass.html @@ -0,0 +1,20 @@ + + + + + ${_('Change Password')} + + +

${_('Change Password')}

+
+
    +
    +
    +
    +
    +
+
+ + diff --git a/fas/build/lib/fas/templates/user/edit.html b/fas/build/lib/fas/templates/user/edit.html new file mode 100644 index 0000000..0b25090 --- /dev/null +++ b/fas/build/lib/fas/templates/user/edit.html @@ -0,0 +1,88 @@ + + + + + ${_('Edit Account')} + + +

${_('Edit Account (%s)') % target.username}

+
+
+ + + +
+ +
+ + + + ${Markup(_('(pending change to %(email)s - <a href="%(url)s">cancel</a>)') % {'email': target.unverified_email, 'url': tg.url('/user/verifyemail/1/cancel')})} + + +
+ +
+ + + +
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + + +
+
+ + + +
+
+ + + + + +
+
+ + + +
+ +
+ + diff --git a/fas/build/lib/fas/templates/user/list.html b/fas/build/lib/fas/templates/user/list.html new file mode 100644 index 0000000..d2679b7 --- /dev/null +++ b/fas/build/lib/fas/templates/user/list.html @@ -0,0 +1,45 @@ + + + + + ${_('Users List')} + + + +

${_('List (%s)') % search}

+
+

${_('"*" is a wildcard (Ex: "ric*")')}

+
+ + +
+
+

${_('Results')}

+ + + + + + + + + + + + + + +
${_('Username')}${_('Account Status')}
${person.username} + + ${_('CLA Done')} + ${_('Not Done')} +
+ + diff --git a/fas/build/lib/fas/templates/user/new.html b/fas/build/lib/fas/templates/user/new.html new file mode 100644 index 0000000..786cd5b --- /dev/null +++ b/fas/build/lib/fas/templates/user/new.html @@ -0,0 +1,42 @@ + + + + + ${_('Sign up for a Fedora account')} + + +

${_('Sign up for a Fedora account')}

+
+
+ + +
+
+ + +
+
+ + +
+ +
+ +
+
+ + diff --git a/fas/build/lib/fas/templates/user/resetpass.html b/fas/build/lib/fas/templates/user/resetpass.html new file mode 100644 index 0000000..d110add --- /dev/null +++ b/fas/build/lib/fas/templates/user/resetpass.html @@ -0,0 +1,20 @@ + + + + + ${_('Reset Password')} + + +

${_('Reset Password')}

+
+
    +
    +
    +
    +
    +
+
+ + diff --git a/fas/build/lib/fas/templates/user/verifyemail.html b/fas/build/lib/fas/templates/user/verifyemail.html new file mode 100644 index 0000000..9c5dab7 --- /dev/null +++ b/fas/build/lib/fas/templates/user/verifyemail.html @@ -0,0 +1,21 @@ + + + + + ${_('Confirm Email Change Request')} + + +

${_('Confirm Email Change Request')}

+
+
+

+ ${_('Do you really want to change your email to: %s?') % person.unverified_email} +

+ + ${_('Cancel')} +
+
+ + diff --git a/fas/build/lib/fas/templates/user/verifypass.html b/fas/build/lib/fas/templates/user/verifypass.html new file mode 100644 index 0000000..763dd54 --- /dev/null +++ b/fas/build/lib/fas/templates/user/verifypass.html @@ -0,0 +1,22 @@ + + + + + ${_('Reset Password')} + + +

${_('Reset Password')}

+
+
    +
    +
    + +
+
+ + diff --git a/fas/build/lib/fas/templates/user/view.html b/fas/build/lib/fas/templates/user/view.html new file mode 100644 index 0000000..9f2bf6c --- /dev/null +++ b/fas/build/lib/fas/templates/user/view.html @@ -0,0 +1,99 @@ + + + + + ${_('View Account')} + + + + + +

${_('Account Details')} ${_('(edit)')}

+
+
+
${_('Account Name:')}
${person.username}
+
${_('Real Name:')}
${person.human_name}
+
${_('Email:')}
${person.email} + + ${Markup(_('(pending change to %(email)s - <a href="%(url)s">cancel</a>)') % {'email': person.unverified_email, 'url': tg.url('/user/verifyemail/1/cancel')})} + +
+
${_('Telephone Number:')}
${person.telephone} 
+
${_('Postal Address:')}
${person.postal_address} 
+ +
${_('IRC Nick:')}
${person.ircnick} 
+
${_('PGP Key:')}
${person.gpg_keyid} 
+
${_('Public SSH Key:')}
+
${person.ssh_key[:20]}.... 
+
No ssh key provided 
+
+
${_('Comments:')}
${person.comments} 
+
${_('Password:')}
${_('Valid')} (change)
+
${_('Account Status:')}
+ ${_('Active')} + ${_('Vacation')} + ${_('Inactive')} + ${_('Pinged')} +
+
${_('CLA:')}
+ ${_('CLA Done')} + ${_('Not Done')} (${_('Complete it!')}) +
+
+
+

${_('Your Roles')}

+

${_('%s\'s Roles') % person.human_name}

+ + + + + diff --git a/fas/build/lib/fas/templates/welcome.html b/fas/build/lib/fas/templates/welcome.html new file mode 100644 index 0000000..9d58e38 --- /dev/null +++ b/fas/build/lib/fas/templates/welcome.html @@ -0,0 +1,26 @@ + + + + + ${_('Welcome to FAS2')} + + + +

+ ${Markup(_('Welcome to the Fedora Accounts System 2. Please submit bugs to <a href="https://fedorahosted.org/fas2">https://fedorahosted.org/fas2/</a> or stop by #fedora-admin on irc.freenode.net.'))} +

+ + + diff --git a/fas/build/lib/fas/tests/__init__.py b/fas/build/lib/fas/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fas/build/lib/fas/tests/test_controllers.py b/fas/build/lib/fas/tests/test_controllers.py new file mode 100644 index 0000000..b3acfac --- /dev/null +++ b/fas/build/lib/fas/tests/test_controllers.py @@ -0,0 +1,37 @@ +import unittest +import turbogears +from turbogears import testutil +from fas.controllers import Root +import cherrypy + +cherrypy.root = Root() + +class TestPages(unittest.TestCase): + + def setUp(self): + turbogears.startup.startTurboGears() + + def tearDown(self): + """Tests for apps using identity need to stop CP/TG after each test to + stop the VisitManager thread. + See http://trac.turbogears.org/turbogears/ticket/1217 for details. + """ + turbogears.startup.stopTurboGears() + + def test_method(self): + "the index method should return a string called now" + import types + result = testutil.call(cherrypy.root.index) + assert type(result["now"]) == types.StringType + + def test_indextitle(self): + "The indexpage should have the right title" + testutil.createRequest("/") + response = cherrypy.response.body[0].lower() + assert "welcome to turbogears" in response + + def test_logintitle(self): + "login page should have the right title" + testutil.createRequest("/login") + response = cherrypy.response.body[0].lower() + assert "login" in response diff --git a/fas/build/lib/fas/tests/test_model.py b/fas/build/lib/fas/tests/test_model.py new file mode 100644 index 0000000..8d0187f --- /dev/null +++ b/fas/build/lib/fas/tests/test_model.py @@ -0,0 +1,22 @@ +# If your project uses a database, you can set up database tests +# similar to what you see below. Be sure to set the db_uri to +# an appropriate uri for your testing database. sqlite is a good +# choice for testing, because you can use an in-memory database +# which is very fast. + +from turbogears import testutil, database +# from fas.model import YourDataClass, User + +# database.set_db_uri("sqlite:///:memory:") + +# class TestUser(testutil.DBTest): +# def get_model(self): +# return User +# def test_creation(self): +# "Object creation should set the name" +# obj = User(user_name = "creosote", +# email_address = "spam@python.not", +# display_name = "Mr Creosote", +# password = "Wafer-thin Mint") +# assert obj.display_name == "Mr Creosote" + diff --git a/fas/build/lib/fas/user.py b/fas/build/lib/fas/user.py new file mode 100644 index 0000000..f3ab6ad --- /dev/null +++ b/fas/build/lib/fas/user.py @@ -0,0 +1,656 @@ +import turbogears +from turbogears import controllers, expose, paginate, identity, redirect, widgets, validate, validators, error_handler, config +from turbogears.database import session +import cherrypy + +import turbomail + +import sqlalchemy + +import os +import re +import gpgme +import StringIO +import crypt +import random +import subprocess +from OpenSSL import crypto + +from fas.model import People +from fas.model import Log + +from fas import openssl_fas +from fas.auth import * + +from random import Random +import sha +from base64 import b64encode + +class KnownUser(validators.FancyValidator): + '''Make sure that a user already exists''' + def _to_python(self, value, state): + return value.strip() + def validate_python(self, value, state): + try: + p = People.by_username(value) + except InvalidRequestError: + raise validators.Invalid(_("'%s' does not exist.") % value, value, state) + +class UnknownUser(validators.FancyValidator): + '''Make sure that a user doesn't already exist''' + def _to_python(self, value, state): + return value.strip() + def validate_python(self, value, state): + try: + p = People.by_username(value) + except InvalidRequestError: + return + except: + raise validators.Invalid(_("Error: Could not create - '%s'") % value, value, state) + + raise validators.Invalid(_("'%s' already exists.") % value, value, state) + +class NonFedoraEmail(validators.FancyValidator): + '''Make sure that an email address is not @fedoraproject.org''' + def _to_python(self, value, state): + return value.strip() + def validate_python(self, value, state): + if value.endswith('@fedoraproject.org'): + raise validators.Invalid(_("To prevent email loops, your email address cannot be @fedoraproject.org."), value, state) + +class ValidSSHKey(validators.FancyValidator): + ''' Make sure the ssh key uploaded is valid ''' + def _to_python(self, value, state): + + return value.file.read() + def validate_python(self, value, state): +# value = value.file.read() + print dir(value) + keylines = value.split('\n') + print "KEYLINES: %s" % keylines + for keyline in keylines: + if not keyline: + continue + keyline = keyline.strip() + m = re.match('^(rsa|dsa|ssh-rsa|ssh-dss) [ \t]*[^ \t]+.*$', keyline) + if not m: + raise validators.Invalid(_('Error - Not a valid ssh key: %s') % keyline, value, state) + +class ValidUsername(validators.FancyValidator): + '''Make sure that a username isn't blacklisted''' + def _to_python(self, value, state): + return value.strip() + def validate_python(self, value, state): + username_blacklist = config.get('username_blacklist') + if re.compile(username_blacklist).match(value): + raise validators.Invalid(_("'%s' is an illegal username.") % value, value, state) + +class UserSave(validators.Schema): + targetname = KnownUser + human_name = validators.All( + validators.String(not_empty=True, max=42), + validators.Regex(regex='^[^\n:<>]+$'), + ) + ssh_key = ValidSSHKey(max=5000) + email = validators.All( + validators.Email(not_empty=True, strip=True, max=128), + NonFedoraEmail(not_empty=True, strip=True, max=128), + ) + #fedoraPersonBugzillaMail = validators.Email(strip=True, max=128) + #fedoraPersonKeyId- Save this one for later :) + postal_address = validators.String(max=512) + +class UserCreate(validators.Schema): + username = validators.All( + UnknownUser, + ValidUsername(not_empty=True), + validators.String(max=32, min=3), + validators.Regex(regex='^[a-z][a-z0-9]+$'), + ) + human_name = validators.All( + validators.String(not_empty=True, max=42), + validators.Regex(regex='^[^\n:<>]+$'), + ) + email = validators.All( + validators.Email(not_empty=True, strip=True), + NonFedoraEmail(not_empty=True, strip=True), + ) + #fedoraPersonBugzillaMail = validators.Email(strip=True) + postal_address = validators.String(max=512) + +class UserSetPassword(validators.Schema): + currentpassword = validators.String + # TODO (after we're done with most testing): Add complexity requirements? + password = validators.String(min=8) + passwordcheck = validators.String + chained_validators = [validators.FieldsMatch('password', 'passwordcheck')] + +class UserResetPassword(validators.Schema): + # TODO (after we're done with most testing): Add complexity requirements? + password = validators.String(min=8) + passwordcheck = validators.String + chained_validators = [validators.FieldsMatch('password', 'passwordcheck')] + +class UserView(validators.Schema): + username = KnownUser + +class UserEdit(validators.Schema): + targetname = KnownUser + +def generate_password(password=None, length=16): + ''' Generate Password ''' + secret = {} # contains both hash and password + + if not password: + # Exclude 1,l and 0,O + chars = '23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ' + password = '' + for i in xrange(length): + password += random.choice(chars) + + secret['hash'] = crypt.crypt(password, "$1$%s" % generate_salt(8)) + secret['pass'] = password + + return secret + +def generate_salt(length=8): + chars = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + salt = '' + for i in xrange(length): + salt += random.choice(chars) + return salt + +def generate_token(length=32): + chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + token = '' + for i in xrange(length): + token += random.choice(chars) + return token + +class User(controllers.Controller): + + def __init__(self): + '''Create a User Controller. + ''' + + @identity.require(turbogears.identity.not_anonymous()) + def index(self): + '''Redirect to view + ''' + turbogears.redirect('/user/view/%s' % turbogears.identity.current.user_name) + + def jsonRequest(self): + return 'tg_format' in cherrypy.request.params and \ + cherrypy.request.params['tg_format'] == 'json' + + + @expose(template="fas.templates.error") + def error(self, tg_errors=None): + '''Show a friendly error message''' + if not tg_errors: + turbogears.redirect('/') + return dict(tg_errors=tg_errors) + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=UserView()) + @error_handler(error) + @expose(template="fas.templates.user.view", allow_json=True) + def view(self, username=None): + '''View a User. + ''' + if not username: + username = turbogears.identity.current.user_name + person = People.by_username(username) + if turbogears.identity.current.user_name == username: + personal = True + else: + personal = False + if isAdmin(person): + admin = True + # TODO: Should admins be able to see personal info? If so, enable this. + # Either way, let's enable this after the testing period. + #personal = True + else: + admin = False + cla = CLADone(person) + person.jsonProps = { + 'People': ('approved_memberships', 'unapproved_memberships') + } + return dict(person=person, cla=cla, personal=personal, admin=admin) + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=UserEdit()) + @error_handler(error) + @expose(template="fas.templates.user.edit") + def edit(self, targetname=None): + '''Edit a user + ''' + username = turbogears.identity.current.user_name + person = People.by_username(username) + + if targetname: + target = People.by_username(targetname) + else: + target = person + if not canEditUser(person, target): + turbogears.flash(_('You cannot edit %s') % target.username ) + turbogears.redirect('/user/view/%s', target.username) + return dict() + return dict(target=target) + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=UserSave()) + @error_handler(error) + @expose(template='fas.templates.user.edit') + def save(self, targetname, human_name, telephone, postal_address, email, ssh_key=None, ircnick=None, gpg_keyid=None, comments='', locale='en', timezone='UTC'): + username = turbogears.identity.current.user_name + target = targetname + person = People.by_username(username) + target = People.by_username(target) + emailflash = '' + + if not canEditUser(person, target): + turbogears.flash(_("You do not have permission to edit '%s'") % target.username) + turbogears.redirect('/user/view/%s', target.username) + return dict() + try: + target.human_name = human_name + if target.email != email: + token = generate_token() + target.unverified_email = email + target.emailtoken = token + message = turbomail.Message(config.get('accounts_email'), email, _('Email Change Requested for %s') % person.username) + # TODO: Make this email friendlier. + message.plain = _(''' +You have recently requested to change your Fedora Account System email +to this address. To complete the email change, you must confirm your +ownership of this email by visiting the following URL (you will need to +login with your Fedora account first): + +https://admin.fedoraproject.org/accounts/user/verifyemail/%s +''') % token + emailflash = _(' Before your new email takes effect, you must confirm it. You should receive an email with instructions shortly.') + turbomail.enqueue(message) + target.ircnick = ircnick + target.gpg_keyid = gpg_keyid + target.telephone = telephone + if ssh_key: + target.ssh_key = ssh_key + target.postal_address = postal_address + target.comments = comments + target.locale = locale + target.timezone = timezone + except TypeError: + turbogears.flash(_('Your account details could not be saved: %s') % e) + else: + turbogears.flash(_('Your account details have been saved.') + ' ' + emailflash) + turbogears.redirect("/user/view/%s" % target.username) + return dict(target=target) + + # TODO: This took about 55 seconds for me to load - might want to limit it to the right accounts (systems user, accounts group) + @identity.require(turbogears.identity.not_anonymous()) + @error_handler(error) + @expose(template="fas.templates.user.list", allow_json=True) + def list(self, search="a*"): + '''List users + ''' + re_search = re.sub(r'\*', r'%', search).lower() + if self.jsonRequest(): + people = [] + peoplesql = sqlalchemy.select([People.c.id, People.c.username, People.c.human_name, People.c.ssh_key, People.c.password]) + persons = peoplesql.execute() + for person in persons: + people.append({ + 'id' : person[0], + 'username' : person[1], + 'human_name' : person[2], + 'ssh_key' : person[3], + 'password' : person[4]}) + else: + people = People.query.filter(People.username.like(re_search)).order_by('username') + if people.count() < 0: + turbogears.flash(_("No users found matching '%s'") % search) + return dict(people=people, search=search) + + @identity.require(turbogears.identity.not_anonymous()) + @error_handler(error) + @expose(format='json') + def email_list(self, search='*'): + re_search = re.sub(r'\*', r'%', search).lower() + people = People.query.filter(People.username.like(re_search)).order_by('username') + emails = {} + for person in people: + emails[person.username] = person.email + return dict(emails=emails) + + @identity.require(turbogears.identity.not_anonymous()) + @error_handler(error) + @expose(template='fas.templates.user.verifyemail') + def verifyemail(self, token, cancel=False): + username = turbogears.identity.current.user_name + person = People.by_username(username) + if cancel: + person.emailtoken = '' + turbogears.flash(_('Your pending email change has been canceled. The email change token has been invalidated.')) + turbogears.redirect('/user/view/%s' % username) + return dict() + if not person.unverified_email: + turbogears.flash(_('You do not have any pending email changes.')) + turbogears.redirect('/user/view/%s' % username) + return dict() + if person.emailtoken and (person.emailtoken != token): + turbogears.flash(_('Invalid email change token.')) + turbogears.redirect('/user/view/%s' % username) + return dict() + return dict(person=person, token=token) + + @identity.require(turbogears.identity.not_anonymous()) + @error_handler(error) + @expose() + def setemail(self, token): + username = turbogears.identity.current.user_name + person = People.by_username(username) + if not (person.unverified_email and person.emailtoken): + turbogears.flash(_('You do not have any pending email changes.')) + turbogears.redirect('/user/view/%s' % username) + return dict() + if person.emailtoken != token: + turbogears.flash(_('Invalid email change token.')) + turbogears.redirect('/user/view/%s' % username) + return dict() + ''' Log this ''' + oldEmail = person.email + person.email = person.unverified_email + Log(author_id=person.id, description='Email changed from %s to %s' % (oldEmail, person.email)) + person.unverified_email = '' + session.flush() + turbogears.flash(_('You have successfully changed your email to \'%s\'') % person.email) + turbogears.redirect('/user/view/%s' % username) + return dict() + + @error_handler(error) + @expose(template='fas.templates.user.new') + def new(self): + if turbogears.identity.not_anonymous(): + turbogears.flash(_('No need to sign up, you have an account!')) + turbogears.redirect('/user/view/%s' % turbogears.identity.current.user_name) + return dict() + + @validate(validators=UserCreate()) + @error_handler(error) + @expose(template='fas.templates.new') + def create(self, username, human_name, email, telephone=None, postal_address=None): + # TODO: Ensure that e-mails are unique? + # Also, perhaps implement a timeout- delete account + # if the e-mail is not verified (i.e. the person changes + # their password) withing X days. + try: + person = People() + person.username = username + person.human_name = human_name + person.telephone = telephone + person.email = email + person.password = '*' + person.status = 'active' + session.flush() + newpass = generate_password() + message = turbomail.Message(config.get('accounts_email'), person.email, _('Welcome to the Fedora Project!')) + message.plain = _(''' +You have created a new Fedora account! +Your new password is: %s + +Please go to https://admin.fedoraproject.org/accounts/ to change it. + +Welcome to the Fedora Project. Now that you've signed up for an +account you're probably desperate to start contributing, and with that +in mind we hope this e-mail might guide you in the right direction to +make this process as easy as possible. + +Fedora is an exciting project with lots going on, and you can +contribute in a huge number of ways, using all sorts of different +skill sets. To find out about the different ways you can contribute to +Fedora, you can visit our join page which provides more information +about all the different roles we have available. + +http://fedoraproject.org/en/join-fedora + +If you already know how you want to contribute to Fedora, and have +found the group already working in the area you're interested in, then +there are a few more steps for you to get going. + +Foremost amongst these is to sign up for the team or project's mailing +list that you're interested in - and if you're interested in more than +one group's work, feel free to sign up for as many mailing lists as +you like! This is because mailing lists are where the majority of work +gets organised and tasks assigned, so to stay in the loop be sure to +keep up with the messages. + +Once this is done, it's probably wise to send a short introduction to +the list letting them know what experience you have and how you'd like +to help. From here, existing members of the team will help you to find +your feet as a Fedora contributor. + +And finally, from all of us here at the Fedora Project, we're looking +forward to working with you! +''') % newpass['pass'] + turbomail.enqueue(message) + person.password = newpass['hash'] + except IntegrityError: + turbogears.flash(_("An account has already been registered with that email address.")) + turbogears.redirect('/user/new') + return dict() + else: + turbogears.flash(_('Your password has been emailed to you. Please log in with it and change your password')) + turbogears.redirect('/user/changepass') + return dict() + + @identity.require(turbogears.identity.not_anonymous()) + @error_handler(error) + @expose(template="fas.templates.user.changepass") + def changepass(self): + return dict() + + @identity.require(turbogears.identity.not_anonymous()) + @validate(validators=UserSetPassword()) + @error_handler(error) + @expose(template="fas.templates.user.changepass") + def setpass(self, currentpassword, password, passwordcheck): + username = turbogears.identity.current.user_name + person = People.by_username(username) + +# current_encrypted = generate_password(currentpassword) +# print "PASS: %s %s" % (current_encrypted, person.password) + if not person.password == crypt.crypt(currentpassword, person.password): + turbogears.flash('Your current password did not match') + return dict() + # TODO: Enable this when we need to. + #if currentpassword == password: + # turbogears.flash('Your new password cannot be the same as your old one.') + # return dict() + newpass = generate_password(password) + try: + person.password = newpass['hash'] + Log(author_id=person.id, description='Password changed') + # TODO: Make this catch something specific. + except: + Log(author_id=person.id, description='Password change failed!') + turbogears.flash(_("Your password could not be changed.")) + return dict() + else: + turbogears.flash(_("Your password has been changed.")) + turbogears.redirect('/user/view/%s' % turbogears.identity.current.user_name) + return dict() + + @error_handler(error) + @expose(template="fas.templates.user.resetpass") + def resetpass(self): + if turbogears.identity.not_anonymous(): + turbogears.flash(_('You are already logged in!')) + turbogears.redirect('/user/view/%s' % turbogears.identity.current.user_name) + return dict() + + #TODO: Validate + @error_handler(error) + @expose(template="fas.templates.user.resetpass") + def sendtoken(self, username, email, encrypted=False): + import turbomail + # Logged in + if turbogears.identity.current.user_name: + turbogears.flash(_("You are already logged in.")) + turbogears.redirect('/user/view/%s', turbogears.identity.current.user_name) + return dict() + try: + person = People.by_username(username) + except InvalidRequestError: + turbogears.flash(_('Username email combo does not exist!')) + turbogears.redirect('/user/resetpass') + if email != person.email: + turbogears.flash(_("username + email combo unknown.")) + return dict() + token = generate_token() + message = turbomail.Message(config.get('accounts_email'), email, _('Fedora Project Password Reset')) + mail = _(''' +Somebody (hopefully you) has requested a password reset for your account! +To change your password (or to cancel the request), please visit +https://admin.fedoraproject.org/accounts/user/verifypass/%(user)s/%(token)s +''') % {'user': username, 'token': token} + if encrypted: + # TODO: Move this out to a single function (same as + # CLA one), think of how to make sure this doesn't get + # full of random keys (keep a clean Fedora keyring) + # TODO: MIME stuff? + keyid = re.sub('\s', '', person.gpg_keyid) + if not keyid: + turbogears.flash(_("This user does not have a GPG Key ID set, so an encrypted email cannot be sent.")) + return dict() + ret = subprocess.call([config.get('gpgexec'), '--keyserver', config.get('gpg_keyserver'), '--recv-keys', keyid]) + if ret != 0: + turbogears.flash(_("Your key could not be retrieved from subkeys.pgp.net")) + turbogears.redirect('/user/resetpass') + return dict() + else: + try: + # This may not be the neatest fix, but gpgme gave an error when mail was unicode. + plaintext = StringIO.StringIO(mail.encode('utf-8')) + ciphertext = StringIO.StringIO() + ctx = gpgme.Context() + ctx.armor = True + signer = ctx.get_key(re.sub('\s', '', config.get('gpg_fingerprint'))) + ctx.signers = [signer] + recipient = ctx.get_key(keyid) + def passphrase_cb(uid_hint, passphrase_info, prev_was_bad, fd): + os.write(fd, '%s\n' % config.get('gpg_passphrase')) + ctx.passphrase_cb = passphrase_cb + ctx.encrypt_sign([recipient], + gpgme.ENCRYPT_ALWAYS_TRUST, + plaintext, + ciphertext) + message.plain = ciphertext.getvalue() + except: + turbogears.flash(_('Your password reset email could not be encrypted.')) + return dict() + else: + message.plain = mail; + turbomail.enqueue(message) + person.passwordtoken = token + turbogears.flash(_('A password reset URL has been emailed to you.')) + turbogears.redirect('/login') + return dict() + + @error_handler(error) + @expose(template="fas.templates.user.newpass") + # TODO: Validator + def newpass(self, username, token, password=None, passwordcheck=None): + person = People.by_username(username) + if not person.passwordtoken: + turbogears.flash(_('You do not have any pending password changes.')) + turbogears.redirect('/login') + return dict() + if person.passwordtoken != token: + person.emailtoken = '' + turbogears.flash(_('Invalid password change token.')) + turbogears.redirect('/login') + return dict() + return dict(person=person, token=token) + + @error_handler(error) + @expose(template="fas.templates.user.verifypass") + # TODO: Validator + def verifypass(self, username, token, cancel=False): + person = People.by_username(username) + if not person.passwordtoken: + turbogears.flash(_('You do not have any pending password changes.')) + turbogears.redirect('/login') + return dict() + if person.passwordtoken != token: + turbogears.flash(_('Invalid password change token.')) + turbogears.redirect('/login') + return dict() + if cancel: + person.passwordtoken = '' + turbogears.flash(_('Your password reset has been canceled. The password change token has been invalidated.')) + turbogears.redirect('/login') + return dict() + return dict(person=person, token=token) + + @error_handler(error) + @expose() + @validate(validators=UserResetPassword()) + def setnewpass(self, username, token, password, passwordcheck): + person = People.by_username(username) + if not person.passwordtoken: + turbogears.flash(_('You do not have any pending password changes.')) + turbogears.redirect('/login') + return dict() + if person.passwordtoken != token: + person.emailtoken = '' + turbogears.flash(_('Invalid password change token.')) + turbogears.redirect('/login') + return dict() + ''' Log this ''' + newpass = generate_password(password) + person.password = newpass['hash'] + person.passwordtoken = '' + Log(author_id=person.id, description='Password changed') + session.flush() + turbogears.flash(_('You have successfully reset your password. You should now be able to login below.')) + turbogears.redirect('/login') + return dict() + + @identity.require(turbogears.identity.not_anonymous()) + @error_handler(error) + @expose(template="genshi-text:fas.templates.user.cert", format="text", content_type='text/plain; charset=utf-8') + def gencert(self): + username = turbogears.identity.current.user_name + person = People.by_username(username) + if CLADone(person): + person.certificate_serial = person.certificate_serial + 1 + + pkey = openssl_fas.createKeyPair(openssl_fas.TYPE_RSA, 1024); + + digest = config.get('openssl_digest') + expire = config.get('openssl_expire') + cafile = config.get('openssl_ca_file') + + cakey = openssl_fas.retrieve_key_from_file(cafile) + cacert = openssl_fas.retrieve_cert_from_file(cafile) + + req = openssl_fas.createCertRequest(pkey, digest=digest, + C=config.get('openssl_c'), + ST=config.get('openssl_st'), + L=config.get('openssl_l'), + O=config.get('openssl_o'), + OU=config.get('openssl_ou'), + CN=person.username, + emailAddress=person.email, + ) + + cert = openssl_fas.createCertificate(req, (cacert, cakey), person.certificate_serial, (0, expire), digest='md5') + certdump = crypto.dump_certificate(crypto.FILETYPE_PEM, cert) + keydump = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey) + return dict(cert=certdump, key=keydump) + else: + turbogears.flash(_('Before generating a certificate, you must first complete the CLA.')) + turbogears.redirect('/cla/') + + diff --git a/fas/build/scripts-2.5/fasClient b/fas/build/scripts-2.5/fasClient new file mode 100755 index 0000000..4d36a95 --- /dev/null +++ b/fas/build/scripts-2.5/fasClient @@ -0,0 +1,577 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright © 2007-2008 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, modify, +# copy, or redistribute it subject to the terms and conditions of the GNU +# General Public License v.2. This program is distributed in the hope that it +# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the +# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the GNU General Public License for more details. You should have +# received a copy of the GNU General Public License along with this program; +# if not, write to the Free Software Foundation, Inc., 51 Franklin Street, +# Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat trademarks that are +# incorporated in the source code or documentation are not subject to the GNU +# General Public License and may only be used or replicated with the express +# permission of Red Hat, Inc. +# +# Red Hat Author(s): Mike McGrath +# +# TODO: put tmp files in a 700 tmp dir + +import sys +import logging +import syslog +import os +import tempfile +import codecs +import datetime +import time + +from urllib2 import URLError +from fedora.tg.client import BaseClient, AuthError, ServerError +from optparse import OptionParser +from shutil import move, rmtree, copytree +from rhpl.translate import _ + +import ConfigParser + +parser = OptionParser() + +parser.add_option('-i', '--install', + dest = 'install', + default = False, + action = 'store_true', + help = _('Download and sync most recent content')) +parser.add_option('-c', '--config', + dest = 'CONFIG_FILE', + default = '/etc/fas.conf', + metavar = 'CONFIG_FILE', + help = _('Specify config file (default "%default")')) +parser.add_option('--nogroup', + dest = 'no_group', + default = False, + action = 'store_true', + help = _('Do not sync group information')) +parser.add_option('--nopasswd', + dest = 'no_passwd', + default = False, + action = 'store_true', + help = _('Do not sync passwd information')) +parser.add_option('--noshadow', + dest = 'no_shadow', + default = False, + action = 'store_true', + help = _('Do not sync shadow information')) +parser.add_option('--nohome', + dest = 'no_home_dirs', + default = False, + action = 'store_true', + help = _('Do not create home dirs')) +parser.add_option('--nossh', + dest = 'no_ssh_keys', + default = False, + action = 'store_true', + help = _('Do not create ssh keys')) +parser.add_option('-s', '--server', + dest = 'FAS_URL', + default = None, + metavar = 'FAS_URL', + help = _('Specify URL of fas server.')) +parser.add_option('-p', '--prefix', + dest = 'prefix', + default = None, + metavar = 'prefix', + help = _('Specify install prefix. Useful for testing')) +parser.add_option('-e', '--enable', + dest = 'enable', + default = False, + action = 'store_true', + help = _('Enable FAS synced shell accounts')) +parser.add_option('-d', '--disable', + dest = 'disable', + default = False, + action = 'store_true', + help = _('Disable FAS synced shell accounts')) +parser.add_option('-a', '--aliases', + dest = 'aliases', + default = False, + action = 'store_true', + help = _('Sync mail aliases')) + + +(opts, args) = parser.parse_args() + +log = logging.getLogger('fas') + +try: + config = ConfigParser.ConfigParser() + if os.path.exists(opts.CONFIG_FILE): + config.read(opts.CONFIG_FILE) + elif os.path.exists('fas.conf'): + config.read('fas.conf') + print >> sys.stderr, "Could not open %s, defaulting to ./fas.conf" % opts.CONFIG_FILE + else: + print >> sys.stderr, "Could not open %s." % opts.CONFIG_FILE + sys.exit(5) +except ConfigParser.MissingSectionHeaderError, e: + print >> sys.stderr, "Config file does not have proper formatting - %s" % e + sys.exit(6) + +FAS_URL = config.get('global', 'url').strip('"') +if opts.prefix: + prefix = opts.prefix +else: + prefix = config.get('global', 'prefix').strip('"') + +def _chown(arg, dir_name, files): + os.chown(dir_name, arg[0], arg[1]) + for file in files: + os.chown(os.path.join(dir_name, file), arg[0], arg[1]) + +class MakeShellAccounts(BaseClient): + temp = None + groups = None + people = None + memberships = None + emails = None + group_mapping = {} + valid_groups = {} + usernames = {} + + def mk_tempdir(self): + self.temp = tempfile.mkdtemp('-tmp', 'fas-', os.path.join(prefix + config.get('global', 'temp').strip('"'))) + + def rm_tempdir(self): + rmtree(self.temp) + + + def valid_groups(self): + ''' Create a dict of valid groups, including that of group_type ''' + if not self.groups: + self.group_list() + valid_groups = {'groups':[], 'restricted_groups':[], 'ssh_restricted_groups': []} + for restriction in valid_groups: + for group in config.get('host', restriction).strip('"').split(','): + if group == '': + continue + if group == '@all': + for grp in self.groups: + if not grp['name'].startswith('cla'): + valid_groups[restriction].append(grp['name']) + elif group.startswith('@'): + for grp in self.groups: + if grp['group_type'] == group[1:]: + valid_groups[restriction].append(grp['name']) + else: + valid_groups[restriction].append(group) + self.valid_groups = valid_groups + + def valid_group(self, name, restriction=None): + ''' Determine if group is valid on the system ''' + if restriction: + return name in self.valid_groups[restriction] + else: + for restrict_key in self.valid_groups: + if name in self.valid_groups[restrict_key]: + return True + return False + + def valid_user(self, username): + ''' Is the user valid on this system ''' + if not self.valid_groups: + self.valid_groups() + if not self.group_mapping: + self.get_group_mapping() + try: + for restriction in self.valid_groups: + for group in self.valid_groups[restriction]: + if username in self.group_mapping[group]: + return True + except KeyError: + return False + return False + + def ssh_key(self, person): + ''' determine what ssh key a user should have ''' + for group in self.valid_groups['groups']: + try: + if person['username'] in self.group_mapping[group]: + return person['ssh_key'] + except KeyError: + print >> sys.stderr, '%s could not be found in fas but was in your config under "groups"!' % group + continue + for group in self.valid_groups['restricted_groups']: + try: + if person['username'] in self.group_mapping[group]: + return person['ssh_key'] + except KeyError: + print >> sys.stderr, '%s could not be found in fas but was in your config under "restricted_groups"!' % group + continue + for group in self.valid_groups['ssh_restricted_groups']: + try: + if person['username'] in self.group_mapping[group]: + command = config.get('users', 'ssh_restricted_app').strip('"') + options = config.get('users', 'ssh_key_options').strip('"') + key = 'command="%s",%s %s' % (command, options, person['ssh_key']) + return key + except TypeError: + print >> sys.stderr, '%s could not be found in fas but was in your config under "ssh_restricted_groups"!' % group + continue + return 'INVALID\n' + + def shell(self, username): + ''' Determine what shell username should have ''' + for group in self.valid_groups['groups']: + try: + if username in self.group_mapping[group]: + return config.get('users', 'shell').strip('"') + except KeyError: + print >> sys.stderr, '%s could not be found in fas but was in your config under "groups"!' % group + continue + for group in self.valid_groups['restricted_groups']: + try: + if username in self.group_mapping[group]: + return config.get('users', 'restricted_shell').strip('"') + except KeyError: + print >> sys.stderr, '%s could not be found in fas but was in your config under "restricted_groups"!' % group + continue + for group in self.valid_groups['ssh_restricted_groups']: + try: + if username in self.group_mapping[group]: + return config.get('users', 'ssh_restricted_shell').strip('"') + except KeyError: + print >> sys.stderr, '%s could not be found in fas but was in your config under "ssh_restricted_groups"!' % group + continue + + print >> sys.stderr, 'Could not determine shell for %s. Defaulting to /sbin/nologin' % username + return '/sbin/nologin' + + def install_aliases_txt(self): + move(self.temp + '/aliases', prefix + '/etc/aliases') + + def passwd_text(self, people=None): + i = 0 + passwd_file = codecs.open(self.temp + '/passwd.txt', mode='w', encoding='utf-8') + shadow_file = codecs.open(self.temp + '/shadow.txt', mode='w', encoding='utf-8') + os.chmod(self.temp + '/shadow.txt', 00400) + if not self.people: + self.people_list() + for person in self.people: + username = person['username'] + if self.valid_user(username): + uid = person['id'] + human_name = person['human_name'] + password = person['password'] + home_dir = "%s/%s" % (config.get('users', 'home').strip('"'), username) + shell = self.shell(username) + passwd_file.write("=%s %s:x:%i:%i:%s:%s:%s\n" % (uid, username, uid, uid, human_name, home_dir, shell)) + passwd_file.write("0%i %s:x:%i:%i:%s:%s:%s\n" % (i, username, uid, uid, human_name, home_dir, shell)) + passwd_file.write(".%s %s:x:%i:%i:%s:%s:%s\n" % (username, username, uid, uid, human_name, home_dir, shell)) + shadow_file.write("=%i %s:%s:99999:0:99999:7:::\n" % (uid, username, password)) + shadow_file.write("0%i %s:%s:99999:0:99999:7:::\n" % (i, username, password)) + shadow_file.write(".%s %s:%s:99999:0:99999:7:::\n" % (username, username, password)) + i = i + 1 + passwd_file.close() + shadow_file.close() + + def valid_user_group(self, person_id): + ''' Determine if person is valid on this machine as defined in the + config file. I worry that this is going to be horribly inefficient + with large numbers of users and groups.''' + for member in self.memberships: + for group in self.memberships[member]: + if group['person_id'] == person_id: + return True + return False + + def get_usernames(self): + usernames = {} + if not self.people: + self.people_list() + for person in self.people: + uid = person['id'] + if self.valid_user_group(uid): + username = person['username'] + usernames[uid] = username + self.usernames = usernames + + def get_group_mapping(self): + if not self.usernames: + self.get_usernames() + for group in self.groups: + gid = group['id'] + name = group['name'] + try: + ''' Shoot me now I know this isn't right ''' + members = [] + for member in self.memberships[name]: + members.append(self.usernames[member['person_id']]) + memberships = ','.join(members) + self.group_mapping[name] = members + except KeyError: + ''' No users exist in the group ''' + pass + + + def groups_text(self, groups=None, people=None): + i = 0 + file = open(self.temp + '/group.txt', 'w') + if not self.groups: + self.group_list() + if not self.people: + self.people_list() + if not self.usernames: + self.get_usernames() + if not self.group_mapping: + self.get_group_mapping() + ''' First create all of our users/groups combo ''' + for person in self.people: + uid = person['id'] + try: + if self.valid_user(self.usernames[uid]): + username = person['username'] + file.write("=%i %s:x:%i:\n" % (uid, username, uid)) + file.write("0%i %s:x:%i:\n" % (i, username, uid)) + file.write(".%s %s:x:%i:\n" % (username, username, uid)) + i = i + 1 + except KeyError: + continue + + for group in self.groups: + gid = group['id'] + name = group['name'] + try: + ''' Shoot me now I know this isn't right ''' + members = [] + for member in self.memberships[name]: + members.append(self.usernames[member['person_id']]) + memberships = ','.join(members) + self.group_mapping[name] = members + except KeyError: + ''' No users exist in the group ''' + pass + file.write("=%i %s:x:%i:%s\n" % (gid, name, gid, memberships)) + file.write("0%i %s:x:%i:%s\n" % (i, name, gid, memberships)) + file.write(".%s %s:x:%i:%s\n" % (name, name, gid, memberships)) + i = i + 1 + file.close() + + def group_list(self, search='*'): + params = {'search' : search} + request = self.send_request('group/list', auth=True, input=params) + self.groups = request['groups'] + memberships = {} + for group in self.groups: + memberships[group['name']] = [] + try: + for member in request['memberships'][u'%s' % group['id']]: + memberships[group['name']].append(member) + except KeyError: + pass + self.memberships = memberships + self.valid_groups() + return self.groups + + def people_list(self, search='*'): + params = {'search' : search} + self.people = self.send_request('user/list', auth=True, input=params)['people'] + + def email_list(self, search='*'): + params = {'search' : search} + self.emails = self.send_request('user/email_list', auth=True, input=params)['emails'] + return self.emails + + def make_group_db(self): + self.groups_text() + os.system('makedb -o %s/group.db %s/group.txt' % (self.temp, self.temp)) + + def make_passwd_db(self): + self.passwd_text() + os.system('makedb -o %s/passwd.db %s/passwd.txt' % (self.temp, self.temp)) + os.system('makedb -o %s/shadow.db %s/shadow.txt' % (self.temp, self.temp)) + os.chmod(self.temp + '/shadow.db', 00400) + + def install_passwd_db(self): + try: + move(self.temp + '/passwd.db', os.path.join(prefix + '/var/db/passwd.db')) + except IOError, e: + print "ERROR: Could not write passwd db - %s" % e + + def install_shadow_db(self): + try: + move(self.temp + '/shadow.db', os.path.join(prefix + '/var/db/shadow.db')) + except IOError, e: + print "ERROR: Could not write shadow db - %s" % e + + def install_group_db(self): + try: + move(self.temp + '/group.db', os.path.join(prefix + '/var/db/group.db')) + except IOError, e: + print "ERROR: Could not write group db - %s" % e + + def create_homedirs(self): + ''' Create homedirs and home base dir if they do not exist ''' + home_base = os.path.join(prefix + config.get('users', 'home').strip('"')) + if not os.path.exists(home_base): + os.makedirs(home_base, mode=0755) + for person in self.people: + home_dir = os.path.join(home_base, person['username']) + if not os.path.exists(home_dir) and self.valid_user(person['username']): + syslog.syslog('Creating homedir for %s' % person['username']) + copytree('/etc/skel/', home_dir) + os.path.walk(home_dir, _chown, [person['id'], person['id']]) + + def remove_stale_homedirs(self): + ''' Remove homedirs of users that no longer have access ''' + home_base = os.path.join(prefix + config.get('users', 'home').strip('"')) + try: + home_backup_dir = config.get('users', 'home_backup_dir').strip('"') + except ConfigParser.NoOptionError: + home_backup_dir = '/var/tmp/' + users = os.listdir(home_base) + for user in users: + if not self.valid_user(user): + if not os.path.exists(home_backup_dir): + os.makedirs(home_backup_dir) + syslog.syslog('Backed up %s to %s' % (user, home_backup_dir)) + target = '%s-%s' % (user, time.mktime(datetime.datetime.now().timetuple())) + move(os.path.join(home_base, user), os.path.join(prefix + home_backup_dir, target)) + + def create_ssh_keys(self): + ''' Create ssh keys ''' + home_base = prefix + config.get('users', 'home').strip('"') + for person in self.people: + username = person['username'] + if self.valid_user(username): + ssh_dir = os.path.join(home_base, username, '.ssh') + if person['ssh_key']: + key = self.ssh_key(person) + if not os.path.exists(ssh_dir): + os.makedirs(ssh_dir, mode=0700) + f = codecs.open(os.path.join(ssh_dir, 'authorized_keys'), mode='w', encoding='utf-8') + f.write(key + '\n') + f.close() + os.chmod(os.path.join(ssh_dir, 'authorized_keys'), 0600) + os.path.walk(ssh_dir, _chown, [person['id'], person['id']]) + + def make_aliases_txt(self): + ''' update your mail aliases file ''' + if not self.groups: + groups = self.group_list() + if not self.usernames: + self.get_usernames() + + self.emails = self.email_list() + email_file = codecs.open(self.temp + '/aliases', mode='w', encoding='utf-8') + email_template = codecs.open(config.get('host', 'aliases_template').strip('"')) + email_file.write("# Generated by fasClient\n") + for line in email_template.readlines(): + email_file.write(line) + sorted = self.emails.keys() + sorted.sort() + for person in sorted: + email_file.write("%s: %s\n" % (person, self.emails[person])) + for group in self.groups: + name = group['name'] + members = {} + members['member'] = [] + for membership in self.memberships[name]: + role_type = membership['role_type'] + person = self.usernames[membership['person_id']] + if role_type == 'user': + ''' Legacy support ''' + members['member'].append(person) + continue + members['member'].append(person) + try: + members[role_type].append(person) + except KeyError: + members[role_type] = [person] + for role in members: + email_file.write("%s-%ss: %s\n" % (name, role, ','.join(members[role]))) + email_file.close() + +def enable(): + temp = tempfile.mkdtemp('-tmp', 'fas-', config.get('global', 'temp').strip('"')) + + old = open('/etc/sysconfig/authconfig', 'r') + new = open(temp + '/authconfig', 'w') + for line in old: + if line.startswith("USEDB"): + new.write("USEDB=yes\n") + else: + new.write(line) + new.close() + old.close() + try: + move(temp + '/authconfig', '/etc/sysconfig/authconfig') + except IOError, e: + print "ERROR: Could not write /etc/sysconfig/authconfig - %s" % e + sys.exit(5) + os.system('/usr/sbin/authconfig --updateall') + rmtree(temp) + +def disable(): + temp = tempfile.mkdtemp('-tmp', 'fas-', config.get('global', 'temp').strip('"')) + old = open('/etc/sysconfig/authconfig', 'r') + new = open(temp + '/authconfig', 'w') + for line in old: + if line.startswith("USEDB"): + new.write("USEDB=no\n") + else: + new.write(line) + old.close() + new.close() + try: + move(temp + '/authconfig', '/etc/sysconfig/authconfig') + except IOError, e: + print "ERROR: Could not write /etc/sysconfig/authconfig - %s" % e + sys.exit(5) + os.system('/usr/sbin/authconfig --updateall') + rmtree(temp) + + +if __name__ == '__main__': + if opts.enable: + enable() + if opts.disable: + disable() + + if opts.install: + try: + fas = MakeShellAccounts(FAS_URL, config.get('global', 'login').strip('"'), config.get('global', 'password').strip('"'), False) + except AuthError, e: + print >> sys.stderr, e + sys.exit(1) + except URLError, e: + print >> sys.stderr, 'Could not connect to %s - %s' % (FAS_URL, e.reason[1]) + sys.exit(9) + fas.mk_tempdir() + fas.make_group_db() + fas.make_passwd_db() + if not opts.no_group: + fas.install_group_db() + if not opts.no_passwd: + fas.install_passwd_db() + if not opts.no_shadow: + fas.install_shadow_db() + if not opts.no_home_dirs: + fas.create_homedirs() + fas.remove_stale_homedirs() + if not opts.no_ssh_keys: + fas.create_ssh_keys() + fas.rm_tempdir() + if opts.aliases: + try: + fas = MakeShellAccounts(FAS_URL, config.get('global', 'login').strip('"'), config.get('global', 'password').strip('"'), False) + except AuthError, e: + print >> sys.stderr, e + sys.exit(1) + fas.mk_tempdir() + fas.make_aliases_txt() + fas.install_aliases_txt() + + if not (opts.install or opts.enable or opts.disable or opts.aliases): + parser.print_help() diff --git a/fas/build/scripts-2.5/restricted-shell b/fas/build/scripts-2.5/restricted-shell new file mode 100755 index 0000000..6f4fd1c --- /dev/null +++ b/fas/build/scripts-2.5/restricted-shell @@ -0,0 +1,67 @@ +#!/usr/bin/python -tt +# This script allows people to run the commands listed in 'commands' and +# 'commands' only. Be careful though, by adding /bin/bash you've effectively +# disabled this script. Also, via some voodoo you can restrict what flags +# get passed or even completely alter what would normally happen if a command +# were envoked (see scp section below) + +# TODO: better documentation needed for how this file works + + +import sys, os + +commands = { + "git-receive-pack": "/usr/bin/git-receive-pack", + "git-upload-pack": "/usr/bin/git-upload-pack", + "bzr": "/usr/bin/run-bzr", + "hg": "/usr/bin/run-hg", + "mtn": "/usr/bin/run-mtn", + "svnserve": "/usr/bin/run-svnserve", + "scp": "/usr/bin/scp", +} + +if __name__ == '__main__': + orig_cmd = os.environ.get('SSH_ORIGINAL_COMMAND') + if not orig_cmd: + print "Need a command" + sys.exit(1) + allargs = orig_cmd.split() + try: + basecmd = os.path.basename(allargs[0]) + cmd = commands[basecmd] + except: + sys.stderr.write("Invalid command %s\n" % orig_cmd) + sys.exit(2) + + if basecmd in ('git-receive-pack', 'git-upload-pack'): + # git repositories need to be parsed specially + thearg = ' '.join(allargs[1:]) + if thearg[0] == "'" and thearg[-1] == "'": + thearg = thearg.replace("'","") + thearg = thearg.replace("\\'", "") + if thearg[:len('/git/')] != '/git/' or not os.path.isdir(thearg): + print "Invalid repository %s" % thearg + sys.exit(3) + allargs = [thearg] + elif basecmd in ('scp'): + thearg = ' '.join(allargs[1:]) + firstLetter = allargs[2][0] + secondLetter = allargs[2][1] + uploadTarget = "/srv/web/releases/%s/%s/%s/" % (firstLetter, secondLetter, allargs[2]) + if thearg.find('/') != -1: + print "scp yourfile-1.2.tar.gz scm.fedorahosted.org:$YOURPROJECT # No trailing /" + sys.exit(4) + elif not os.path.isdir(uploadTarget): + print "http://fedorahosted.org/releases/%s/%s/%s does not exist!" % (firstLetter, secondLetter, allargs[2]) + sys.exit(5) + else: + newargs = [] + newargs.append(allargs[0]) + newargs.append(allargs[1]) + newargs.append(uploadTarget) + os.execv(cmd, [cmd] + newargs[1:]) + sys.exit(1) + else: + allargs = allargs[1:] + os.execv(cmd, [cmd] + allargs) + sys.exit(1) diff --git a/fas/fas/static/css/style.css b/fas/fas/static/theme/fas/css/style.css similarity index 100% rename from fas/fas/static/css/style.css rename to fas/fas/static/theme/fas/css/style.css diff --git a/fas/fas/static/images/account.png b/fas/fas/static/theme/fas/images/account.png similarity index 100% rename from fas/fas/static/images/account.png rename to fas/fas/static/theme/fas/images/account.png diff --git a/fas/fas/static/images/approved.png b/fas/fas/static/theme/fas/images/approved.png similarity index 100% rename from fas/fas/static/images/approved.png rename to fas/fas/static/theme/fas/images/approved.png diff --git a/fas/fas/static/images/arrow.png b/fas/fas/static/theme/fas/images/arrow.png similarity index 100% rename from fas/fas/static/images/arrow.png rename to fas/fas/static/theme/fas/images/arrow.png diff --git a/fas/fas/static/images/attn.png b/fas/fas/static/theme/fas/images/attn.png similarity index 100% rename from fas/fas/static/images/attn.png rename to fas/fas/static/theme/fas/images/attn.png diff --git a/fas/fas/static/images/control-separator.png b/fas/fas/static/theme/fas/images/control-separator.png similarity index 100% rename from fas/fas/static/images/control-separator.png rename to fas/fas/static/theme/fas/images/control-separator.png diff --git a/fas/fas/static/images/favicon.ico b/fas/fas/static/theme/fas/images/favicon.ico similarity index 100% rename from fas/fas/static/images/favicon.ico rename to fas/fas/static/theme/fas/images/favicon.ico diff --git a/fas/fas/static/images/footer-bottom.png b/fas/fas/static/theme/fas/images/footer-bottom.png similarity index 100% rename from fas/fas/static/images/footer-bottom.png rename to fas/fas/static/theme/fas/images/footer-bottom.png diff --git a/fas/fas/static/images/footer-top.png b/fas/fas/static/theme/fas/images/footer-top.png similarity index 100% rename from fas/fas/static/images/footer-top.png rename to fas/fas/static/theme/fas/images/footer-top.png diff --git a/fas/fas/static/images/head.png b/fas/fas/static/theme/fas/images/head.png similarity index 100% rename from fas/fas/static/images/head.png rename to fas/fas/static/theme/fas/images/head.png diff --git a/fas/fas/static/images/header-icon_account.png b/fas/fas/static/theme/fas/images/header-icon_account.png similarity index 100% rename from fas/fas/static/images/header-icon_account.png rename to fas/fas/static/theme/fas/images/header-icon_account.png diff --git a/fas/fas/static/images/header_inner.png b/fas/fas/static/theme/fas/images/header_inner.png similarity index 100% rename from fas/fas/static/images/header_inner.png rename to fas/fas/static/theme/fas/images/header_inner.png diff --git a/fas/fas/static/images/help.png b/fas/fas/static/theme/fas/images/help.png similarity index 100% rename from fas/fas/static/images/help.png rename to fas/fas/static/theme/fas/images/help.png diff --git a/fas/fas/static/images/hr.png b/fas/fas/static/theme/fas/images/hr.png similarity index 100% rename from fas/fas/static/images/hr.png rename to fas/fas/static/theme/fas/images/hr.png diff --git a/fas/fas/static/images/icon_tool-item.png b/fas/fas/static/theme/fas/images/icon_tool-item.png similarity index 100% rename from fas/fas/static/images/icon_tool-item.png rename to fas/fas/static/theme/fas/images/icon_tool-item.png diff --git a/fas/fas/static/images/icon_warning.png b/fas/fas/static/theme/fas/images/icon_warning.png similarity index 100% rename from fas/fas/static/images/icon_warning.png rename to fas/fas/static/theme/fas/images/icon_warning.png diff --git a/fas/fas/static/images/info.png b/fas/fas/static/theme/fas/images/info.png similarity index 100% rename from fas/fas/static/images/info.png rename to fas/fas/static/theme/fas/images/info.png diff --git a/fas/fas/static/images/infobar.png b/fas/fas/static/theme/fas/images/infobar.png similarity index 100% rename from fas/fas/static/images/infobar.png rename to fas/fas/static/theme/fas/images/infobar.png diff --git a/fas/fas/static/images/logo.png b/fas/fas/static/theme/fas/images/logo.png similarity index 100% rename from fas/fas/static/images/logo.png rename to fas/fas/static/theme/fas/images/logo.png diff --git a/fas/fas/static/images/ok.png b/fas/fas/static/theme/fas/images/ok.png similarity index 100% rename from fas/fas/static/images/ok.png rename to fas/fas/static/theme/fas/images/ok.png diff --git a/fas/fas/static/images/queue.png b/fas/fas/static/theme/fas/images/queue.png similarity index 100% rename from fas/fas/static/images/queue.png rename to fas/fas/static/theme/fas/images/queue.png diff --git a/fas/fas/static/images/shadow.png b/fas/fas/static/theme/fas/images/shadow.png similarity index 100% rename from fas/fas/static/images/shadow.png rename to fas/fas/static/theme/fas/images/shadow.png diff --git a/fas/fas/static/images/sidebar.png b/fas/fas/static/theme/fas/images/sidebar.png similarity index 100% rename from fas/fas/static/images/sidebar.png rename to fas/fas/static/theme/fas/images/sidebar.png diff --git a/fas/fas/static/images/status_approved.png b/fas/fas/static/theme/fas/images/status_approved.png similarity index 100% rename from fas/fas/static/images/status_approved.png rename to fas/fas/static/theme/fas/images/status_approved.png diff --git a/fas/fas/static/images/status_incomplete.png b/fas/fas/static/theme/fas/images/status_incomplete.png similarity index 100% rename from fas/fas/static/images/status_incomplete.png rename to fas/fas/static/theme/fas/images/status_incomplete.png diff --git a/fas/fas/static/images/status_rejected.png b/fas/fas/static/theme/fas/images/status_rejected.png similarity index 100% rename from fas/fas/static/images/status_rejected.png rename to fas/fas/static/theme/fas/images/status_rejected.png diff --git a/fas/fas/static/images/success.png b/fas/fas/static/theme/fas/images/success.png similarity index 100% rename from fas/fas/static/images/success.png rename to fas/fas/static/theme/fas/images/success.png diff --git a/fas/fas/static/images/tg_under_the_hood.png b/fas/fas/static/theme/fas/images/tg_under_the_hood.png similarity index 100% rename from fas/fas/static/images/tg_under_the_hood.png rename to fas/fas/static/theme/fas/images/tg_under_the_hood.png diff --git a/fas/fas/static/images/tools.png b/fas/fas/static/theme/fas/images/tools.png similarity index 100% rename from fas/fas/static/images/tools.png rename to fas/fas/static/theme/fas/images/tools.png diff --git a/fas/fas/static/images/topnav-separator.png b/fas/fas/static/theme/fas/images/topnav-separator.png similarity index 100% rename from fas/fas/static/images/topnav-separator.png rename to fas/fas/static/theme/fas/images/topnav-separator.png diff --git a/fas/fas/static/images/topnav.png b/fas/fas/static/theme/fas/images/topnav.png similarity index 100% rename from fas/fas/static/images/topnav.png rename to fas/fas/static/theme/fas/images/topnav.png diff --git a/fas/fas/static/images/unapproved.png b/fas/fas/static/theme/fas/images/unapproved.png similarity index 100% rename from fas/fas/static/images/unapproved.png rename to fas/fas/static/theme/fas/images/unapproved.png diff --git a/fas/fas/static/images/under_the_hood_blue.png b/fas/fas/static/theme/fas/images/under_the_hood_blue.png similarity index 100% rename from fas/fas/static/images/under_the_hood_blue.png rename to fas/fas/static/theme/fas/images/under_the_hood_blue.png diff --git a/fas/fas/templates/master.html b/fas/fas/templates/master.html index 4838960..b18fadd 100644 --- a/fas/fas/templates/master.html +++ b/fas/fas/templates/master.html @@ -6,9 +6,10 @@ + - - + + From c395bc1aaa81fcaa04cb4ca00648d85760dcd09f Mon Sep 17 00:00:00 2001 From: Mike McGrath Date: Sat, 15 Mar 2008 18:01:58 -0500 Subject: [PATCH 2/2] these shouldn't be version managed --- fas/build/lib/fas/__init__.py | 30 - fas/build/lib/fas/auth.py | 218 ------ fas/build/lib/fas/cla.py | 120 ---- fas/build/lib/fas/commands.py | 51 -- fas/build/lib/fas/config/__init__.py | 0 fas/build/lib/fas/config/log.cfg | 29 - fas/build/lib/fas/controllers.py | 145 ---- fas/build/lib/fas/feeds.py | 17 - fas/build/lib/fas/group.py | 532 -------------- fas/build/lib/fas/help.py | 50 -- fas/build/lib/fas/json_request.py | 73 -- fas/build/lib/fas/model.py | 470 ------------- fas/build/lib/fas/openid_fas.py | 112 --- fas/build/lib/fas/openssl_fas.py | 82 --- fas/build/lib/fas/release.py | 18 - fas/build/lib/fas/safasprovider.py | 219 ------ fas/build/lib/fas/templates/__init__.py | 0 fas/build/lib/fas/templates/about.html | 17 - fas/build/lib/fas/templates/cla/__init__.py | 0 fas/build/lib/fas/templates/cla/cla.html | 82 --- fas/build/lib/fas/templates/cla/cla.txt | 145 ---- fas/build/lib/fas/templates/cla/index.html | 26 - fas/build/lib/fas/templates/error.html | 25 - fas/build/lib/fas/templates/group/__init__.py | 0 fas/build/lib/fas/templates/group/dump.txt | 3 - fas/build/lib/fas/templates/group/edit.html | 55 -- fas/build/lib/fas/templates/group/invite.html | 43 -- fas/build/lib/fas/templates/group/list.html | 54 -- fas/build/lib/fas/templates/group/new.html | 57 -- fas/build/lib/fas/templates/group/view.html | 123 ---- fas/build/lib/fas/templates/help.html | 12 - fas/build/lib/fas/templates/home.html | 33 - fas/build/lib/fas/templates/login.html | 33 - fas/build/lib/fas/templates/master.html | 104 --- .../lib/fas/templates/openid/__init__.py | 0 fas/build/lib/fas/templates/openid/about.html | 15 - fas/build/lib/fas/templates/openid/auth.txt | 1 - fas/build/lib/fas/templates/openid/id.html | 21 - .../lib/fas/templates/openid/trusted.html | 20 - fas/build/lib/fas/templates/user/__init__.py | 0 fas/build/lib/fas/templates/user/cert.txt | 2 - .../lib/fas/templates/user/changepass.html | 20 - fas/build/lib/fas/templates/user/edit.html | 88 --- fas/build/lib/fas/templates/user/list.html | 45 -- fas/build/lib/fas/templates/user/new.html | 42 -- .../lib/fas/templates/user/resetpass.html | 20 - .../lib/fas/templates/user/verifyemail.html | 21 - .../lib/fas/templates/user/verifypass.html | 22 - fas/build/lib/fas/templates/user/view.html | 99 --- fas/build/lib/fas/templates/welcome.html | 26 - fas/build/lib/fas/tests/__init__.py | 0 fas/build/lib/fas/tests/test_controllers.py | 37 - fas/build/lib/fas/tests/test_model.py | 22 - fas/build/lib/fas/user.py | 656 ------------------ fas/build/scripts-2.5/fasClient | 577 --------------- fas/build/scripts-2.5/restricted-shell | 67 -- 56 files changed, 4779 deletions(-) delete mode 100644 fas/build/lib/fas/__init__.py delete mode 100644 fas/build/lib/fas/auth.py delete mode 100644 fas/build/lib/fas/cla.py delete mode 100644 fas/build/lib/fas/commands.py delete mode 100644 fas/build/lib/fas/config/__init__.py delete mode 100644 fas/build/lib/fas/config/log.cfg delete mode 100644 fas/build/lib/fas/controllers.py delete mode 100644 fas/build/lib/fas/feeds.py delete mode 100644 fas/build/lib/fas/group.py delete mode 100644 fas/build/lib/fas/help.py delete mode 100644 fas/build/lib/fas/json_request.py delete mode 100644 fas/build/lib/fas/model.py delete mode 100644 fas/build/lib/fas/openid_fas.py delete mode 100644 fas/build/lib/fas/openssl_fas.py delete mode 100644 fas/build/lib/fas/release.py delete mode 100644 fas/build/lib/fas/safasprovider.py delete mode 100644 fas/build/lib/fas/templates/__init__.py delete mode 100644 fas/build/lib/fas/templates/about.html delete mode 100644 fas/build/lib/fas/templates/cla/__init__.py delete mode 100644 fas/build/lib/fas/templates/cla/cla.html delete mode 100644 fas/build/lib/fas/templates/cla/cla.txt delete mode 100644 fas/build/lib/fas/templates/cla/index.html delete mode 100644 fas/build/lib/fas/templates/error.html delete mode 100644 fas/build/lib/fas/templates/group/__init__.py delete mode 100644 fas/build/lib/fas/templates/group/dump.txt delete mode 100644 fas/build/lib/fas/templates/group/edit.html delete mode 100644 fas/build/lib/fas/templates/group/invite.html delete mode 100644 fas/build/lib/fas/templates/group/list.html delete mode 100644 fas/build/lib/fas/templates/group/new.html delete mode 100644 fas/build/lib/fas/templates/group/view.html delete mode 100644 fas/build/lib/fas/templates/help.html delete mode 100644 fas/build/lib/fas/templates/home.html delete mode 100644 fas/build/lib/fas/templates/login.html delete mode 100644 fas/build/lib/fas/templates/master.html delete mode 100644 fas/build/lib/fas/templates/openid/__init__.py delete mode 100644 fas/build/lib/fas/templates/openid/about.html delete mode 100644 fas/build/lib/fas/templates/openid/auth.txt delete mode 100644 fas/build/lib/fas/templates/openid/id.html delete mode 100644 fas/build/lib/fas/templates/openid/trusted.html delete mode 100644 fas/build/lib/fas/templates/user/__init__.py delete mode 100644 fas/build/lib/fas/templates/user/cert.txt delete mode 100644 fas/build/lib/fas/templates/user/changepass.html delete mode 100644 fas/build/lib/fas/templates/user/edit.html delete mode 100644 fas/build/lib/fas/templates/user/list.html delete mode 100644 fas/build/lib/fas/templates/user/new.html delete mode 100644 fas/build/lib/fas/templates/user/resetpass.html delete mode 100644 fas/build/lib/fas/templates/user/verifyemail.html delete mode 100644 fas/build/lib/fas/templates/user/verifypass.html delete mode 100644 fas/build/lib/fas/templates/user/view.html delete mode 100644 fas/build/lib/fas/templates/welcome.html delete mode 100644 fas/build/lib/fas/tests/__init__.py delete mode 100644 fas/build/lib/fas/tests/test_controllers.py delete mode 100644 fas/build/lib/fas/tests/test_model.py delete mode 100644 fas/build/lib/fas/user.py delete mode 100755 fas/build/scripts-2.5/fasClient delete mode 100755 fas/build/scripts-2.5/restricted-shell diff --git a/fas/build/lib/fas/__init__.py b/fas/build/lib/fas/__init__.py deleted file mode 100644 index e333e3c..0000000 --- a/fas/build/lib/fas/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -from fas import release -__version__ = release.VERSION - -class FASError(Exception): - '''FAS Error''' - pass - -class ApplyError(FASError): - '''Raised when a user could not apply to a group''' - pass - -class ApproveError(FASError): - '''Raised when a user could not be approved in a group''' - pass - -class SponsorError(FASError): - '''Raised when a user could not be sponsored in a group''' - pass - -class UpgradeError(FASError): - '''Raised when a user could not be upgraded in a group''' - pass - -class DowngradeError(FASError): - '''Raised when a user could not be downgraded in a group''' - pass - -class RemoveError(FASError): - '''Raised when a user could not be removed from a group''' - pass diff --git a/fas/build/lib/fas/auth.py b/fas/build/lib/fas/auth.py deleted file mode 100644 index 05b5deb..0000000 --- a/fas/build/lib/fas/auth.py +++ /dev/null @@ -1,218 +0,0 @@ -from turbogears import config - -from fas.model import Groups -from fas.model import PersonRoles -from fas.model import People - -from sqlalchemy.exceptions import * -import turbogears - -import re - -def isAdmin(person): - ''' - Returns True if the user is a FAS admin (a member of the admingroup) - ''' - admingroup = config.get('admingroup') - try: - if person.group_roles[admingroup].role_status == 'approved': - return True - else: - return False - except KeyError: - return False - return False - -def canAdminGroup(person, group): - ''' - Returns True if the user is allowed to act as an admin for a group - ''' - if isAdmin(person) or (group.owner == person): - return True - else: - try: - role = PersonRoles.query.filter_by(group=group, member=person).one() - except IndexError: - ''' Not in the group ''' - return False - except InvalidRequestError: - return False - if role.role_status == 'approved' and role.role_type == 'administrator': - return True - return False - -def canSponsorGroup(person, group): - ''' - Returns True if the user is allowed to act as a sponsor for a group - ''' - try: - if isAdmin(person) or \ - group.owner == person: - return True - else: - try: - role = PersonRoles.query.filter_by(group=group, member=person).one() - except IndexError: - ''' Not in the group ''' - return False - if role.role_status == 'approved' and role.role_type == 'sponsor': - return True - return False - except: - return False - -def isApproved(person, group): - ''' - Returns True if the user is an approved member of a group - ''' - try: - if person.group_roles[group.name].role_status == 'approved': - return True - else: - return False - except KeyError: - return False - return False - -def CLADone(person): - ''' - Returns True if the user has completed the CLA - ''' - cla_done_group =config.get('cla_done_group') - try: - if person.group_roles[cla_done_group].role_status == 'approved': - return True - else: - return False - except KeyError: - return False - return False - -def canEditUser(person, target): - ''' - Returns True if the user has privileges to edit the target user - ''' - if person == target: - return True - elif isAdmin(person): - return True - else: - return False - -def canCreateGroup(person, group): - ''' - Returns True if the user can create groups - ''' - # Should groupname restrictions go here? - if isAdmin(person): - return True - else: - return False - -def canEditGroup(person, group): - ''' - Returns True if the user can edit the group - ''' - if canAdminGroup(person, group): - return True - else: - return False - -def canViewGroup(person, group): - ''' - Returns True if the user can view the group - ''' - # If the group matched by privileged_view_groups, then - # only people that can admin the group can view it - privilegedViewGroups = config.get('privileged_view_groups') - if re.compile(privilegedViewGroups).match(group.name): - if canAdminGroup(person, group): - return True - else: - return False - else: - return True - -def canApplyGroup(person, group, applicant): - ''' - Returns True if the user can apply applicant to the group - ''' - # User must satisfy all dependencies to join. - # This is bypassed for people already in the group and for the - # owner of the group (when they initially make it). - prerequisite = group.prerequisite - # TODO: Make this return more useful info. - if prerequisite: - if prerequisite in person.approved_memberships: - pass - else: - turbogears.flash(_('%s membership required before application to this group is allowed') % prerequisite.name) - return False - # A user can apply themselves, and FAS admins can apply other people. - - if (person == applicant) or \ - canAdminGroup(person, group): - return True - else: - turbogears.flash(_('%s membership required before application to this group is allowed') % prerequisite.name) - return False - -def canSponsorUser(person, group, target): - ''' - Returns True if the user can sponsor target in the group - ''' - # This is just here in case we want to add more complex checks in the future - if canSponsorGroup(person, group): - return True - else: - return False - -def canRemoveUser(person, group, target): - ''' - Returns True if the user can remove target from the group - ''' - # Only administrators can remove administrators. - if canAdminGroup(target, group) and \ - not canAdminGroup(person, group): - return False - # A user can remove themself from a group if user_can_remove is 1 - # Otherwise, a sponsor can remove sponsors/users. - elif ((person == target) and (group.user_can_remove == True)) or \ - canSponsorGroup(person, group): - return True - else: - return False - -def canUpgradeUser(person, group, target): - ''' - Returns True if the user can upgrade target in the group - ''' - # Group admins can upgrade anybody. - # The controller should handle the case where the target - # is already a group admin. - if canAdminGroup(person, group): - return True - # Sponsors can only upgrade non-sponsors (i.e. normal users) - # TODO: Don't assume that canSponsorGroup means that the user is a sponsor - elif canSponsorGroup(person, group) and \ - not canSponsorGroup(target, group): - return True - else: - return False - -def canDowngradeUser(person, group, target): - ''' - Returns True if the user can downgrade target in the group - ''' - # Group admins can downgrade anybody. - if canAdminGroup(person, group): - return True - # Sponsors can only downgrade sponsors. - # The controller should handle the case where the target - # is already a normal user. - elif canSponsorGroup(person, group) and \ - not canAdminGroup(person, group): - return True - else: - return False - diff --git a/fas/build/lib/fas/cla.py b/fas/build/lib/fas/cla.py deleted file mode 100644 index c6aa636..0000000 --- a/fas/build/lib/fas/cla.py +++ /dev/null @@ -1,120 +0,0 @@ -import turbogears -from turbogears import controllers, expose, paginate, identity, redirect, widgets, validate, validators, error_handler -from turbogears.database import session - -import cherrypy - -from datetime import datetime -import re -import turbomail -from genshi.template.plugin import TextTemplateEnginePlugin - -from fas.model import People -from fas.model import Log -from fas.auth import * - -class CLA(controllers.Controller): - - def __init__(self): - '''Create a CLA Controller.''' - - @identity.require(turbogears.identity.not_anonymous()) - @expose(template="fas.templates.cla.index") - def index(self): - '''Display the CLAs (and accept/do not accept buttons)''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - if not person.telephone or not person.postal_address: - turbogears.flash('Postal Address and telephone number are required to complete the cla, please fill them out') - turbogears.redirect('/user/edit/%s' % username) - cla = CLADone(person) - return dict(cla=cla, person=person, date=datetime.utcnow().ctime()) - - def jsonRequest(self): - return 'tg_format' in cherrypy.request.params and \ - cherrypy.request.params['tg_format'] == 'json' - - @expose(template="fas.templates.error") - def error(self, tg_errors=None): - '''Show a friendly error message''' - if not tg_errors: - turbogears.redirect('/') - return dict(tg_errors=tg_errors) - - @identity.require(turbogears.identity.not_anonymous()) - @error_handler(error) - @expose(template="genshi-text:fas.templates.cla.cla", format="text", content_type='text/plain; charset=utf-8') - def text(self, type=None): - '''View CLA as text''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - return dict(person=person, date=datetime.utcnow().ctime()) - - @identity.require(turbogears.identity.not_anonymous()) - @error_handler(error) - @expose(template="genshi-text:fas.templates.cla.cla", format="text", content_type='text/plain; charset=utf-8') - def download(self, type=None): - '''Download CLA''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - return dict(person=person, date=datetime.utcnow().ctime()) - - @identity.require(turbogears.identity.not_anonymous()) - @error_handler(error) - @expose(template="fas.templates.cla.index") - def send(self, agree=False): - '''Send CLA''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - if CLADone(person): - turbogears.flash(_('You have already completed the CLA.')) - turbogears.redirect('/cla/') - return dict() - if not agree: - turbogears.flash(_("You have not completed the CLA.")) - turbogears.redirect('/user/view/%s' % person.username) - if not person.telephone or \ - not person.postal_address: - turbogears.flash(_('To complete the CLA, we must have your telephone number and postal address. Please ensure they have been filled out.')) - turbogears.redirect('/user/edit/%s' % username) - groupname = config.get('cla_fedora_group') - group = Groups.by_name(groupname) - try: - # Everything is correct. - person.apply(group, person) # Apply... - session.flush() - person.sponsor(group, person) # Sponsor! - except: - # TODO: If apply succeeds and sponsor fails, the user has - # to remove themselves from the CLA group before they can - # complete the CLA and go through the above try block again. - turbogears.flash(_("You could not be added to the '%s' group.") % group.name) - turbogears.redirect('/cla/') - return dict() - else: - dt = datetime.utcnow() - Log(author_id=person.id, description='Completed CLA', changetime=dt) - message = turbomail.Message(config.get('accounts_email'), config.get('legal_cla_email'), 'Fedora ICLA completed') - message.plain = ''' -Fedora user %(username)s has completed an ICLA (below). -Username: %(username)s -Email: %(email)s -Date: %(date)s - -=== CLA === - -''' % {'username': person.username, - 'human_name': person.human_name, - 'email': person.email, - 'postal_address': person.postal_address, - 'telephone': person.telephone, - 'facsimile': person.facsimile, - 'date': dt.ctime(),} - # Sigh.. if only there were a nicer way. - plugin = TextTemplateEnginePlugin() - message.plain += plugin.render(template='fas.templates.cla.cla', info=dict(person=person), format='text') - turbomail.enqueue(message) - turbogears.flash(_("You have successfully completed the CLA. You are now in the '%s' group.") % group.name) - turbogears.redirect('/user/view/%s' % person.username) - return dict() - diff --git a/fas/build/lib/fas/commands.py b/fas/build/lib/fas/commands.py deleted file mode 100644 index dbbaf2d..0000000 --- a/fas/build/lib/fas/commands.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -"""This module contains functions called from console script entry points.""" - -import os -import sys - -import pkg_resources -pkg_resources.require("TurboGears") - -import turbogears -import cherrypy - -cherrypy.lowercase_api = True - -class ConfigurationError(Exception): - pass - -def start(): - '''Start the CherryPy application server.''' - setupdir = os.path.dirname(os.path.dirname(__file__)) - curdir = os.getcwd() - - # First look on the command line for a desired config file, - # if it's not on the command line, then look for 'setup.py' - # in the current directory. If there, load configuration - # from a file called 'dev.cfg'. If it's not there, the project - # is probably installed and we'll look first for a file called - # 'prod.cfg' in the current directory and then for a default - # config file called 'default.cfg' packaged in the egg. - if len(sys.argv) > 1: - configfile = sys.argv[1] - elif os.path.exists(os.path.join(setupdir, 'setup.py')) \ - and os.path.exists(os.path.join(setupdir, 'dev.cfg')): - configfile = os.path.join(setupdir, 'dev.cfg') - elif os.path.exists(os.path.join(curdir, 'fas.cfg')): - configfile = os.path.join(curdir, 'fas.cfg') - elif os.path.exists(os.path.join('/etc/fas.cfg')): - configfile = os.path.join('/etc/fas.cfg') - else: - try: - configfile = pkg_resources.resource_filename( - pkg_resources.Requirement.parse("fas"), - "config/default.cfg") - except pkg_resources.DistributionNotFound: - raise ConfigurationError("Could not find default configuration.") - - turbogears.update_config(configfile=configfile, - modulename="fas.config") - - from fas.controllers import Root - turbogears.start_server(Root()) diff --git a/fas/build/lib/fas/config/__init__.py b/fas/build/lib/fas/config/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/fas/build/lib/fas/config/log.cfg b/fas/build/lib/fas/config/log.cfg deleted file mode 100644 index ce776f8..0000000 --- a/fas/build/lib/fas/config/log.cfg +++ /dev/null @@ -1,29 +0,0 @@ -# LOGGING -# Logging is often deployment specific, but some handlers and -# formatters can be defined here. - -[logging] -[[formatters]] -[[[message_only]]] -format='*(message)s' - -[[[full_content]]] -format='*(asctime)s *(name)s *(levelname)s *(message)s' - -[[handlers]] -[[[debug_out]]] -class='StreamHandler' -level='DEBUG' -args='(sys.stdout,)' -formatter='full_content' - -[[[access_out]]] -class='StreamHandler' -level='INFO' -args='(sys.stdout,)' -formatter='message_only' - -[[[error_out]]] -class='StreamHandler' -level='ERROR' -args='(sys.stdout,)' diff --git a/fas/build/lib/fas/controllers.py b/fas/build/lib/fas/controllers.py deleted file mode 100644 index b092bf5..0000000 --- a/fas/build/lib/fas/controllers.py +++ /dev/null @@ -1,145 +0,0 @@ -from turbogears import controllers, expose, config -from model import * -from turbogears import identity, redirect, widgets, validate, validators, error_handler -from cherrypy import request, response - -from turbogears import exception_handler -import turbogears -import cherrypy -import time - -from fas.user import User -from fas.group import Group -from fas.cla import CLA -from fas.json_request import JsonRequest -from fas.help import Help -from fas.auth import * -#from fas.openid_fas import OpenID - -import os -import sys -reload(sys) -sys.setdefaultencoding('utf-8') - -def add_custom_stdvars(vars): - return vars.update({"gettext": _}) - -turbogears.view.variable_providers.append(add_custom_stdvars) - -def get_locale(locale=None): - if locale: - return locale - try: - return turbogears.identity.current.user.locale - except AttributeError: - return turbogears.i18n.utils._get_locale() - -config.update({'i18n.get_locale': get_locale}) - -# from fas import json -# import logging -# log = logging.getLogger("fas.controllers") - -#TODO: Appropriate flash icons for errors, etc. -# mmcgrath wonders if it will be handy to expose an encrypted mailer with fas over json for our apps - -class Root(controllers.RootController): - - user = User() - group = Group() - cla = CLA() - json = JsonRequest() - help = Help() - #openid = OpenID() - - # TODO: Find a better place for this. - os.environ['GNUPGHOME'] = config.get('gpghome') - - @expose(template="fas.templates.welcome", allow_json=True) - def index(self): - if turbogears.identity.not_anonymous(): - if 'tg_format' in request.params \ - and request.params['tg_format'] == 'json': - # redirects don't work with JSON calls. This is a bit of a - # hack until we can figure out something better. - return dict() - turbogears.redirect('/home') - return dict(now=time.ctime()) - - @expose(template="fas.templates.home", allow_json=True) - @identity.require(identity.not_anonymous()) - def home(self): - user_name = turbogears.identity.current.user_name - person = People.by_username(user_name) - cla = CLADone(person) - return dict(person=person, cla=cla) - - @expose(template="fas.templates.about") - def about(self): - return dict() - - @expose(template="fas.templates.login", allow_json=True) - def login(self, forward_url=None, previous_url=None, *args, **kwargs): - '''Page to become authenticated to the Account System. - - This shows a small login box to type in your username and password - from the Fedora Account System. - - Arguments: - :forward_url: The url to send to once authentication succeeds - :previous_url: The url that sent us to the login page - ''' - if forward_url == '.': - forward_url = turbogears.url('/../home') - if not identity.current.anonymous \ - and identity.was_login_attempted() \ - and not identity.get_identity_errors(): - # User is logged in - turbogears.flash(_('Welcome, %s') % People.by_username(turbogears.identity.current.user_name).human_name) - if 'tg_format' in request.params \ - and request.params['tg_format'] == 'json': - # When called as a json method, doesn't make any sense to - # redirect to a page. Returning the logged in identity - # is better. - return dict(user = identity.current.user) - if not forward_url: - forward_url = turbogears.url('/') - raise redirect(forward_url) - - forward_url=None - previous_url= request.path - - if identity.was_login_attempted(): - msg=_("The credentials you supplied were not correct or " - "did not grant access to this resource.") - elif identity.get_identity_errors(): - msg=_("You must provide your credentials before accessing " - "this resource.") - else: - msg=_("Please log in.") - forward_url= '.' - - cherrypy.response.status=403 - return dict(message=msg, previous_url=previous_url, logging_in=True, - original_parameters=request.params, - forward_url=forward_url) - - @expose(allow_json=True) - def logout(self): - identity.current.logout() - turbogears.flash(_('You have successfully logged out.')) - if 'tg_format' in request.params \ - and request.params['tg_format'] == 'json': - # When called as a json method, doesn't make any sense to - # redirect to a page. Returning the logged in identity - # is better. - return dict(status=True) - raise redirect('/') - - @expose() - def language(self, locale): - locale_key = config.get("i18n.session_key", "locale") - cherrypy.session[locale_key] = locale - raise redirect(request.headers.get("Referer", "/")) - - diff --git a/fas/build/lib/fas/feeds.py b/fas/build/lib/fas/feeds.py deleted file mode 100644 index 93a64c8..0000000 --- a/fas/build/lib/fas/feeds.py +++ /dev/null @@ -1,17 +0,0 @@ -import urllib -from xml.dom import minidom - - -class Koji: - def __init__(self, userName, url='http://publictest8/koji/recentbuilds?user='): - buildFeed = minidom.parse(urllib.urlopen(url + userName)) - try: - self.userLink = buildFeed.getElementsByTagName('link')[0].childNodes[0].data - self.builds = {} - for build in buildFeed.getElementsByTagName('item'): - link = build.getElementsByTagName('link')[0].childNodes[0].data - self.builds[link] = {} - self.builds[link]['title'] = build.getElementsByTagName('title')[0].childNodes[0].data - self.builds[link]['pubDate'] = build.getElementsByTagName('pubDate')[0].childNodes[0].data - except IndexError: - return diff --git a/fas/build/lib/fas/group.py b/fas/build/lib/fas/group.py deleted file mode 100644 index c96b92c..0000000 --- a/fas/build/lib/fas/group.py +++ /dev/null @@ -1,532 +0,0 @@ -import turbogears -from turbogears import controllers, expose, paginate, identity, redirect, widgets, validate, validators, error_handler -from turbogears.database import session - -import cherrypy -import sqlalchemy - -import fas -from fas.auth import * -from fas.user import KnownUser - -import re -import turbomail - -class KnownGroup(validators.FancyValidator): - '''Make sure that a group already exists''' - def _to_python(self, value, state): - return value.strip() - def validate_python(self, value, state): - try: - g = Groups.by_name(value) - except InvalidRequestError: - raise validators.Invalid(_("The group '%s' does not exist.") % value, value, state) - -class UnknownGroup(validators.FancyValidator): - '''Make sure that a group doesn't already exist''' - def _to_python(self, value, state): - return value.strip() - def validate_python(self, value, state): - try: - g = Groups.by_name(value) - except InvalidRequestError: - pass - else: - raise validators.Invalid(_("The group '%s' already exists.") % value, value, state) - -class GroupCreate(validators.Schema): - - name = validators.All( - UnknownGroup, - validators.String(max=32, min=3), - validators.Regex(regex='^[a-z0-9\-_]+$'), - ) - display_name = validators.NotEmpty - owner = validators.All( - KnownUser, - validators.NotEmpty, - ) - prerequisite = KnownGroup - #group_type = something - -class GroupSave(validators.Schema): - groupname = validators.All(KnownGroup, validators.String(max=32, min=3)) - display_name = validators.NotEmpty - owner = KnownUser - prerequisite = KnownGroup - #group_type = something - -class GroupApply(validators.Schema): - groupname = KnownGroup - targetname = KnownUser - -class GroupSponsor(validators.Schema): - groupname = KnownGroup - targetname = KnownUser - -class GroupRemove(validators.Schema): - groupname = KnownGroup - targetname = KnownUser - -class GroupUpgrade(validators.Schema): - groupname = KnownGroup - targetname = KnownUser - -class GroupDowngrade(validators.Schema): - groupname = KnownGroup - targetname = KnownUser - -class GroupView(validators.Schema): - groupname = KnownGroup - -class GroupEdit(validators.Schema): - groupname = KnownGroup - -class GroupInvite(validators.Schema): - groupname = KnownGroup - -class GroupSendInvite(validators.Schema): - groupname = KnownGroup - target = validators.Email(not_empty=True, strip=True), - -#class findUser(widgets.WidgetsList): -# username = widgets.AutoCompleteField(label=_('Username'), search_controller='search', search_param='username', result_name='people') -# action = widgets.HiddenField(default='apply', validator=validators.String(not_empty=True)) -# groupname = widgets.HiddenField(validator=validators.String(not_empty=True)) -# -#findUserForm = widgets.ListForm(fields=findUser(), submit_text=_('Invite')) - -class Group(controllers.Controller): - - def __init__(self): - '''Create a Group Controller.''' - - @identity.require(turbogears.identity.not_anonymous()) - def index(self): - '''Perhaps show a nice explanatory message about groups here?''' - return dict() - - def jsonRequest(self): - return 'tg_format' in cherrypy.request.params and \ - cherrypy.request.params['tg_format'] == 'json' - - @expose(template="fas.templates.error") - def error(self, tg_errors=None): - '''Show a friendly error message''' - if not tg_errors: - turbogears.redirect('/') - return dict(tg_errors=tg_errors) - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=GroupView()) - @error_handler(error) - @expose(template="fas.templates.group.view", allow_json=True) - def view(self, groupname): - '''View group''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - group = Groups.by_name(groupname) - - if not canViewGroup(person, group): - turbogears.flash(_("You cannot view '%s'") % group.name) - turbogears.redirect('/group/list') - return dict() - else: - return dict(group=group) - - @identity.require(turbogears.identity.not_anonymous()) - @expose(template="fas.templates.group.new") - def new(self): - '''Display create group form''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - - if not canCreateGroup(person, Groups.by_name(config.get('admingroup'))): - turbogears.flash(_('Only FAS adminstrators can create groups.')) - turbogears.redirect('/') - return dict() - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=GroupCreate()) - @error_handler(error) - @expose(template="fas.templates.group.new") - def create(self, name, display_name, owner, group_type, needs_sponsor=0, user_can_remove=1, prerequisite='', joinmsg=''): - '''Create a group''' - - groupname = name - person = People.by_username(turbogears.identity.current.user_name) - person_owner = People.by_username(owner) - - if not canCreateGroup(person, Groups.by_name(config.get('admingroup'))): - turbogears.flash(_('Only FAS adminstrators can create groups.')) - turbogears.redirect('/') - try: - owner = People.by_username(owner) - group = Groups() - group.name = name - group.display_name = display_name - group.owner_id = person_owner.id - group.group_type = group_type - group.needs_sponsor = bool(needs_sponsor) - group.user_can_remove = bool(user_can_remove) - if prerequisite: - prerequisite = Groups.by_name(prerequisite) - group.prerequisite = prerequisite - group.joinmsg = joinmsg - # Log here - session.flush() - except TypeError: - turbogears.flash(_("The group: '%s' could not be created.") % groupname) - return dict() - else: - try: - owner.apply(group, person) # Apply... - session.flush() - owner.sponsor(group, person) - owner.upgrade(group, person) - owner.upgrade(group, person) - except KeyError: - turbogears.flash(_("The group: '%(group)s' has been created, but '%(user)s' could not be added as a group administrator.") % {'group': group.name, 'user': owner.username}) - else: - turbogears.flash(_("The group: '%s' has been created.") % group.name) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=GroupEdit()) - @error_handler(error) - @expose(template="fas.templates.group.edit") - def edit(self, groupname): - '''Display edit group form''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - group = Groups.by_name(groupname) - - if not canAdminGroup(person, group): - turbogears.flash(_("You cannot edit '%s'.") % group.name) - turbogears.redirect('/group/view/%s' % group.name) - return dict(group=group) - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=GroupSave()) - @error_handler(error) - @expose(template="fas.templates.group.edit") - def save(self, groupname, display_name, owner, group_type, needs_sponsor=0, user_can_remove=1, prerequisite='', joinmsg=''): - '''Edit a group''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - group = Groups.by_name(groupname) - - if not canEditGroup(person, group): - turbogears.flash(_("You cannot edit '%s'.") % group.name) - turbogears.redirect('/group/view/%s' % group.name) - else: - try: - owner = People.by_username(owner) - group.display_name = display_name - group.owner = owner - group.group_type = group_type - group.needs_sponsor = bool(needs_sponsor) - group.user_can_remove = bool(user_can_remove) - if prerequisite: - prerequisite = Groups.by_name(prerequisite) - group.prerequisite = prerequisite - group.joinmsg = joinmsg - # Log here - session.flush() - except: - turbogears.flash(_('The group details could not be saved.')) - else: - turbogears.flash(_('The group details have been saved.')) - turbogears.redirect('/group/view/%s' % group.name) - return dict(group=group) - - @identity.require(turbogears.identity.not_anonymous()) - @expose(template="fas.templates.group.list", allow_json=True) - def list(self, search='*'): - username = turbogears.identity.current.user_name - person = People.by_username(username) - - memberships = {} - groups = [] - re_search = re.sub(r'\*', r'%', search).lower() - results = Groups.query.filter(Groups.name.like(re_search)).order_by('name').all() - if self.jsonRequest(): - membersql = sqlalchemy.select([PersonRoles.c.person_id, PersonRoles.c.group_id, PersonRoles.c.role_type], PersonRoles.c.role_status=='approved').order_by(PersonRoles.c.group_id) - members = membersql.execute() - for member in members: - try: - memberships[member[1]].append({'person_id': member[0], 'role_type': member[2]}) - except KeyError: - memberships[member[1]]=[{'person_id': member[0], 'role_type': member[2]}] - for group in results: - if canViewGroup(person, group): - groups.append(group) - if not len(groups): - turbogears.flash(_("No Groups found matching '%s'") % search) - return dict(groups=groups, search=search, memberships=memberships) - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=GroupApply()) - @error_handler(error) - @expose(template='fas.templates.group.view') - def apply(self, groupname, targetname=None): - '''Apply to a group''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - if not targetname: - target = person - else: - target = People.by_username(targetname) - group = Groups.by_name(groupname) - - if not canApplyGroup(person, group, target): - turbogears.flash(_('%(user)s can not apply to %(group)s.') % \ - {'user': target.username, 'group': group.name }) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - else: - try: - target.apply(group, person) - except fas.ApplyError, e: - turbogears.flash(_('%(user)s could not apply to %(group)s: %(error)s') % \ - {'user': target.username, 'group': group.name, 'error': e}) - turbogears.redirect('/group/view/%s' % group.name) - else: - # TODO: How do we handle gettext calls for these kinds of emails? - # TODO: CC to right place, put a bit more thought into how to most elegantly do this - # TODO: Maybe that @fedoraproject.org (and even -sponsors) should be configurable somewhere? - message = turbomail.Message(config.get('accounts_email'), '%(group)s-sponsors@%(host)s' % {'group': group.name, 'host': config.get('email_host')}, \ - "Fedora '%(group)s' sponsor needed for %(user)s" % {'user': target.username, 'group': group.name}) - url = config.get('base_url_filter.base_url') + '/group/edit/%s' % groupname - - message.plain = _(''' -Fedora user %(user)s, aka %(name)s <%(email)s> has requested -membership for %(applicant)s (%(applicant_name)s) in the %(group)s group and needs a sponsor. - -Please go to %(url)s to take action. -''') % {'user': person.username, 'name': person.human_name, 'applicant': target.username, 'applicant_name': target.human_name, 'email': person.email, 'url': url, 'group': group.name} - turbomail.enqueue(message) - turbogears.flash(_('%(user)s has applied to %(group)s!') % \ - {'user': target.username, 'group': group.name}) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=GroupSponsor()) - @error_handler(error) - @expose(template='fas.templates.group.view') - def sponsor(self, groupname, targetname): - '''Sponsor user''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - target = People.by_username(targetname) - group = Groups.by_name(groupname) - - if not canSponsorUser(person, group, target): - turbogears.flash(_("You cannot sponsor '%s'") % target.username) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - else: - try: - target.sponsor(group, person) - except fas.SponsorError, e: - turbogears.flash(_("%(user)s could not be sponsored in %(group)s: %(error)s") % \ - {'user': target.username, 'group': group.name, 'error': e}) - turbogears.redirect('/group/view/%s' % group.name) - else: - import turbomail - message = turbomail.Message(config.get('accounts_email'), target.email, "Your Fedora '%s' membership has been sponsored" % group.name) - message.plain = _(''' -%(name)s <%(email)s> has sponsored you for membership in the %(group)s -group of the Fedora account system. If applicable, this change should -propagate into the e-mail aliases and CVS repository within an hour. - -%(joinmsg)s -''') % {'group': group.name, 'name': person.human_name, 'email': person.email, 'joinmsg': group.joinmsg} - turbomail.enqueue(message) - turbogears.flash(_("'%s' has been sponsored!") % target.human_name) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=GroupRemove()) - @error_handler(error) - @expose(template='fas.templates.group.view') - def remove(self, groupname, targetname): - '''Remove user from group''' - # TODO: Add confirmation? - username = turbogears.identity.current.user_name - person = People.by_username(username) - target = People.by_username(targetname) - group = Groups.by_name(groupname) - - if not canRemoveUser(person, group, target): - turbogears.flash(_("You cannot remove '%(user)s' from '%(group)s'.") % {'user': target.username, 'group': group.name}) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - else: - try: - target.remove(group, target) - except fas.RemoveError, e: - turbogears.flash(_("%(user)s could not be removed from %(group)s: %(error)s") % \ - {'user': target.username, 'group': group.name, 'error': e}) - turbogears.redirect('/group/view/%s' % group.name) - else: - message = turbomail.Message(config.get('accounts_email'), target.email, "Your Fedora '%s' membership has been removed" % group.name) - message.plain = _(''' -%(name)s <%(email)s> has removed you from the '%(group)s' -group of the Fedora Accounts System This change is effective -immediately for new operations, and should propagate into the e-mail -aliases within an hour. -''') % {'group': group.name, 'name': person.human_name, 'email': person.email} - turbomail.enqueue(message) - turbogears.flash(_('%(name)s has been removed from %(group)s') % \ - {'name': target.username, 'group': group.name}) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=GroupUpgrade()) - @error_handler(error) - @expose(template='fas.templates.group.view') - def upgrade(self, groupname, targetname): - '''Upgrade user in group''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - target = People.by_username(targetname) - group = Groups.by_name(groupname) - - if not canUpgradeUser(person, group, target): - turbogears.flash(_("You cannot upgrade '%s'") % target.username) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - else: - try: - target.upgrade(group, person) - except fas.UpgradeError, e: - turbogears.flash(_('%(name)s could not be upgraded in %(group)s: %(error)s') % \ - {'name': target.username, 'group': group.name, 'error': e}) - turbogears.redirect('/group/view/%s' % group.name) - else: - import turbomail - message = turbomail.Message(config.get('accounts_email'), target.email, "Your Fedora '%s' membership has been upgraded" % group.name) - # Should we make person.upgrade return this? - role = PersonRoles.query.filter_by(group=group, member=target).one() - status = role.role_type - message.plain = _(''' -%(name)s <%(email)s> has upgraded you to %(status)s status in the -'%(group)s' group of the Fedora Accounts System This change is -effective immediately for new operations, and should propagate -into the e-mail aliases within an hour. -''') % {'group': group.name, 'name': person.human_name, 'email': person.email, 'status': status} - turbomail.enqueue(message) - turbogears.flash(_('%s has been upgraded!') % target.username) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=GroupDowngrade()) - @error_handler(error) - @expose(template='fas.templates.group.view') - def downgrade(self, groupname, targetname): - '''Upgrade user in group''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - target = People.by_username(targetname) - group = Groups.by_name(groupname) - - if not canDowngradeUser(person, group, target): - turbogears.flash(_("You cannot downgrade '%s'") % target.username) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - else: - try: - target.downgrade(group, person) - except fas.DowngradeError, e: - turbogears.flash(_('%(name)s could not be downgraded in %(group)s: %(error)s') % \ - {'name': target.username, 'group': group.name, 'error': e}) - turbogears.redirect('/group/view/%s' % group.name) - else: - import turbomail - message = turbomail.Message(config.get('accounts_email'), target.email, "Your Fedora '%s' membership has been downgraded" % group.name) - role = PersonRoles.query.filter_by(group=group, member=target).one() - status = role.role_type - message.plain = _(''' -%(name)s <%(email)s> has downgraded you to %(status)s status in the -'%(group)s' group of the Fedora Accounts System This change is -effective immediately for new operations, and should propagate -into the e-mail aliases within an hour. -''') % {'group': group.name, 'name': person.human_name, 'email': person.email, 'status': status} - turbomail.enqueue(message) - turbogears.flash(_('%s has been downgraded!') % target.username) - turbogears.redirect('/group/view/%s' % group.name) - return dict() - - @identity.require(turbogears.identity.not_anonymous()) - @error_handler(error) - @expose(template="genshi-text:fas.templates.group.dump", format="text", content_type='text/plain; charset=utf-8') - def dump(self, groupname=None): - username = turbogears.identity.current.user_name - person = People.by_username(username) - if not groupname: -# groupname = config.get('cla_done_group') - people = People.query.order_by('username').all() - else: - people = [] - groups = Groups.by_name(groupname) - for role in groups.approved_roles: - people.append(role.member) - if not canViewGroup(person, groups): - turbogears.flash(_("You cannot view '%s'") % group.name) - turbogears.redirect('/group/list') - return dict() - - return dict(people=people) - - @identity.require(identity.not_anonymous()) - @validate(validators=GroupInvite()) - @error_handler(error) - @expose(template='fas.templates.group.invite') - def invite(self, groupname): - username = turbogears.identity.current.user_name - person = People.by_username(username) - group = Groups.by_name(groupname) - - return dict(person=person, group=group) - - @identity.require(identity.not_anonymous()) - @validate(validators=GroupSendInvite()) - @error_handler(error) - @expose(template='fas.templates.group.invite') - def sendinvite(self, groupname, target): - import turbomail - username = turbogears.identity.current.user_name - person = People.by_username(username) - group = Groups.by_name(groupname) - - if isApproved(person, group): - message = turbomail.Message(person.email, target, _('Come join The Fedora Project!')) - message.plain = _(''' -%(name)s <%(email)s> has invited you to join the Fedora -Project! We are a community of users and developers who produce a -complete operating system from entirely free and open source software -(FOSS). %(name)s thinks that you have knowledge and skills -that make you a great fit for the Fedora community, and that you might -be interested in contributing. - -How could you team up with the Fedora community to use and develop your -skills? Check out http://fedoraproject.org/join-fedora for some ideas. -Our community is more than just software developers -- we also have a -place for you whether you're an artist, a web site builder, a writer, or -a people person. You'll grow and learn as you work on a team with other -very smart and talented people. - -Fedora and FOSS are changing the world -- come be a part of it!''') % {'name': person.human_name, 'email': person.email} - turbomail.enqueue(message) - turbogears.flash(_('Message sent to: %s') % target) - turbogears.redirect('/group/view/%s' % group.name) - else: - turbogears.flash(_("You are not in the '%s' group.") % group.name) - return dict(target=target, person=person, group=group) - diff --git a/fas/build/lib/fas/help.py b/fas/build/lib/fas/help.py deleted file mode 100644 index b00aedd..0000000 --- a/fas/build/lib/fas/help.py +++ /dev/null @@ -1,50 +0,0 @@ -import turbogears -from turbogears import controllers, expose, paginate, identity, redirect, widgets, validate, validators, error_handler -from turbogears.database import session - -from fas.auth import * - -# TODO: gettext like crazy. -class Help(controllers.Controller): - help = { 'none' : ['Error', '

We could not find that help item

'], - 'user_ircnick' : ['IRC Nick (Optional)', '

IRC Nick is used to identify yourself on irc.freenode.net. Please register your nick on irc.freenode.net first, then fill this in so people can find you online when they need to

'], - 'user_email' : ['Email (Required)', '

This email address should be your prefered email contact and will be used to send various official emails to. This is also where your @fedoraproject.org email will get forwarded

'], - 'user_human_name' : ['Full Name (Required)', '

Your Human Name or "real life" name

'], - 'user_gpg_keyid' : ['GPG Key', '

A GPG key is generally used to prove that a message or email came from you or to encrypt information so that only the recipients can read it. This can be used when a password reset is sent to your email.

'], - 'user_telephone' : ['Telephone', '

Required in order to complete the CLA. Sometimes during a time of emergency someone from the Fedora Project may need to contact you. For more information see our Privacy Policy

'], - 'user_postal_address': ['Postal Address', '

Required in order to complete the CLA. This should be a mailing address where you can be contacted. See our Privacy Policy about any concerns.

'], - 'user_timezone': ['Timezone (Optional)', '

Please specify the time zone you are in.

'], - 'user_comments': ['Comments (Optional)', '

Misc comments about yourself.

'], - 'user_account_status': ['Account Status', '

Shows account status, possible values include

  • Valid
  • Disabled
  • Expired

'], - 'user_cla' : ['CLA', '

In order to become a full Fedora contributor you must complete the Contributor License Agreement. This license is a legal agreement between you and Red Hat. Full status allows people to contribute content and code and is recommended for anyone interested in getting involved in the Fedora Project.

'], - 'user_ssh_key' : ['Public SSH Key', '

Many resources require public key authentiaction to work. By uploading your public key to us, you can then log in to our servers. Type "man ssh-keygen" for more information on creating your key. Once created you will want to upload ~/.ssh/id_dsa.pub or ~/.ssh/id_rsa.pub

'], - 'user_locale': ['Locale', '

For non-english speaking peoples this allows individuals to select which locale they are in.

'], - - 'group_apply': ['Apply', '

Applying for a group is like applying for a job and it can certainly take a while to get in. Many groups have their own rules about how to actually get approved or sponsored. For more information on how the account system works see the about page.

'], - 'group_remove': ['Remove', '''

Removing a person from a group will cause that user to no longer be in the group. They will need to re-apply to get in. Admins can remove anyone, Sponsors can remove users, users can't remove anyone.

'''], - 'group_upgrade': ['Upgrade', '''

Upgrade a persons status in this group.

  • from user -> to sponsor
  • From sponsor -> administrator
  • administrators cannot be upgraded beyond administrator

'''], - 'group_downgrade': ['Downgrade', '''

Downgrade a persons status in the group.

  • from administrator -> to sponsor
  • From sponsor -> user
  • users cannot be downgraded below user, you may want to remove them

'''], - 'group_approve': ['Approve', '''

A sponsor or administrator can approve users to be in a group. Once the user has applied for the group, go to the group's page and click approve to approve the user.

'''], - 'group_sponsor': ['Sponsor', '''

A sponsor or administrator can sponsor users to be in a gruop. Once the user has applied for the group, go to the group's page and click approve to sponsor the user. Sponsorship of a user implies that you are approving a user and may mentor and answer their questions as they come up.

'''], - 'group_user_add': ['Add User', '''

Manually add a user to a group. Place their username in this field and click 'Add'

'''], - 'group_name': ['Group Name', '''

The name of the group you'd like to create. It should be alphanumeric though '-'s are allowed

'''], - 'group_display_name': ['Display Name', '''

More human readable name of the group

'''], - 'group_owner': ['Group Owner', '''

The name of the owner who will run this group

'''], - 'group_type': ['Group Type', '''

Normally it is safe to leave this blank. Though some values include 'tracking', 'shell', 'cvs', 'git', 'hg', 'svn', and 'mtn'. This value only really matters if the group is to end up getting shell access or commit access somewhere like fedorahosted.

'''], - 'group_needs_sponsor': ['Needs Sponsor', '''

If your group requires sponsorship (recommended), this means that when a user is approved by a sponsor. That relationship is recorded in the account system. If user A sponsors user N, then in viewing the members of this group, people will know to contact user A about user N if something goes wrong. If this box is unchecked, this means that only approval is needed and no relationship is recorded about who did the approving

'''], - 'group_self_removal': ['Self Removal', '''

Should users be able to remove themselves from this group without sponsor / admin intervention? (recommended yes)

'''], - 'group_prerequisite': ['Must Belong To', '''

Before a user can join this group, they must belong to the group listed in this box. This value cannot be removed without administrative intervention, only changed. Recommended values are for the 'cla_done' group.

'''], - 'group_join_message': ['Join Message', '''

This message will go out to users when they join the group. It should be informative and offer tips about what to do next. A description of the group would also be valuable here

'''], - 'gencert': ['Client Side Cert', '''

The client side cert is generally used to grant access to upload packages to Fedora or for other authentication purposes like with koji. If you are not a package maintainer there is no need to worry about the client side cert

'''], - } - - def __init__(self): - '''Create a JsonRequest Controller.''' - - @expose(template="fas.templates.help") - def get_help(self, id='none'): - try: - helpItem = self.help[id] - except KeyError: - return dict(title='Error', helpItem=['Error', '

We could not find that help item

']) - return dict(help=helpItem) diff --git a/fas/build/lib/fas/json_request.py b/fas/build/lib/fas/json_request.py deleted file mode 100644 index 8e75438..0000000 --- a/fas/build/lib/fas/json_request.py +++ /dev/null @@ -1,73 +0,0 @@ -import turbogears -from turbogears import controllers, expose, identity - -import sqlalchemy - -from fas.model import People -from fas.model import Groups -from fas.model import Log - -from fas.auth import * - -class JsonRequest(controllers.Controller): - def __init__(self): - """Create a JsonRequest Controller.""" - - @identity.require(turbogears.identity.not_anonymous()) - @expose("json", allow_json=True) - def index(self): - """Return a help message""" - return dict(help='This is a JSON interface.') - - @identity.require(turbogears.identity.not_anonymous()) - @expose("json", allow_json=True) - def person_by_id(self, id): - try: - person = People.by_id(id) - person.jsonProps = { - 'People': ('approved_memberships', 'unapproved_memberships') - } - return dict(success=True, person=person) - except InvalidRequestError: - return dict(success=False) - - @identity.require(turbogears.identity.not_anonymous()) - @expose("json", allow_json=True) - def person_by_username(self, username): - try: - person = People.by_username(username) - person.jsonProps = { - 'People': ('approved_memberships', 'unapproved_memberships') - } - return dict(success=True, person=person) - except InvalidRequestError: - return dict(success=False) - - @identity.require(turbogears.identity.not_anonymous()) - @expose("json", allow_json=True) - def group_by_id(self, id): - try: - group = Groups.by_id(id) - return dict(success=True, group=group) - except InvalidRequestError: - return dict(success=False) - - @identity.require(turbogears.identity.not_anonymous()) - @expose("json", allow_json=True) - def group_by_name(self, groupname): - try: - group = Groups.by_name(groupname) - return dict(success=True, group=group) - except InvalidRequestError: - return dict(success=False) - - @identity.require(turbogears.identity.not_anonymous()) - @expose("json", allow_json=True) - def user_id(self): - people = {} - peoplesql = sqlalchemy.select([People.c.id, People.c.username]) - persons = peoplesql.execute() - for person in persons: - people[person[0]] = person[1] - return dict(people=people) - diff --git a/fas/build/lib/fas/model.py b/fas/build/lib/fas/model.py deleted file mode 100644 index 57786f5..0000000 --- a/fas/build/lib/fas/model.py +++ /dev/null @@ -1,470 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright © 2008 Red Hat, Inc. All rights reserved. -# -# This copyrighted material is made available to anyone wishing to use, modify, -# copy, or redistribute it subject to the terms and conditions of the GNU -# General Public License v.2. This program is distributed in the hope that it -# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the -# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# See the GNU General Public License for more details. You should have -# received a copy of the GNU General Public License along with this program; -# if not, write to the Free Software Foundation, Inc., 51 Franklin Street, -# Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat trademarks that are -# incorporated in the source code or documentation are not subject to the GNU -# General Public License and may only be used or replicated with the express -# permission of Red Hat, Inc. -# -# Author(s): Toshio Kuratomi -# Ricky Zhou -# - -''' -Model for the Fedora Account System -''' -from datetime import datetime -import pytz -from turbogears.database import metadata, mapper, get_engine -# import some basic SQLAlchemy classes for declaring the data model -# (see http://www.sqlalchemy.org/docs/04/ormtutorial.html) -from sqlalchemy import Table, Column, ForeignKey -from sqlalchemy.orm import relation -# import some datatypes for table columns from SQLAlchemy -# (see http://www.sqlalchemy.org/docs/04/types.html for more) -from sqlalchemy import String, Unicode, Integer, DateTime -# A few sqlalchemy tricks: -# Allow viewing foreign key relations as a dictionary -from sqlalchemy.orm.collections import column_mapped_collection, attribute_mapped_collection -# Allow us to reference the remote table of a many:many as a simple list -from sqlalchemy.ext.associationproxy import association_proxy -from sqlalchemy import select, and_ - -from sqlalchemy.exceptions import InvalidRequestError - -from turbogears.database import session - -from turbogears import identity, config - -import turbogears - -from fedora.tg.json import SABase -import fas - -# Bind us to the database defined in the config file. -get_engine() - -# -# Tables Mapped from the DB -# - -PeopleTable = Table('people', metadata, autoload=True) -PersonRolesTable = Table('person_roles', metadata, autoload=True) - -ConfigsTable = Table('configs', metadata, autoload=True) -GroupsTable = Table('groups', metadata, autoload=True) -GroupRolesTable = Table('group_roles', metadata, autoload=True) -BugzillaQueueTable = Table('bugzilla_queue', metadata, autoload=True) -LogTable = Table('log', metadata, autoload=True) -RequestsTable = Table('requests', metadata, autoload=True) - -# -# Selects for filtering roles -# -ApprovedRolesSelect = PersonRolesTable.select(and_( - PeopleTable.c.id==PersonRolesTable.c.person_id, - PersonRolesTable.c.role_status=='approved')).alias('approved') -UnApprovedRolesSelect = PersonRolesTable.select(and_( - PeopleTable.c.id==PersonRolesTable.c.person_id, - PersonRolesTable.c.role_status!='approved')).alias('unapproved') - -# The identity schema -- These must follow some conventions that TG -# understands and are shared with other Fedora services via the python-fedora -# module. - -visits_table = Table('visit', metadata, - Column('visit_key', String(40), primary_key=True), - Column('created', DateTime, nullable=False, default=datetime.now(pytz.utc)), - Column('expiry', DateTime) -) - -visit_identity_table = Table('visit_identity', metadata, - Column('visit_key', String(40), ForeignKey('visit.visit_key'), - primary_key=True), - Column('user_id', Integer, ForeignKey('people.id'), index=True) -) - -# -# Mapped Classes -# - -class People(SABase): - '''Records for all the contributors to Fedora.''' - - @classmethod - def by_id(cls, id): - ''' - A class method that can be used to search users - based on their unique id - ''' - return cls.query.filter_by(id=id).one() - - @classmethod - def by_email_address(cls, email): - ''' - A class method that can be used to search users - based on their email addresses since it is unique. - ''' - return cls.query.filter_by(email=email).one() - - @classmethod - def by_username(cls, username): - ''' - A class method that permits to search users - based on their username attribute. - ''' - return cls.query.filter_by(username=username).one() - - # If we're going to do logging here, we'll have to pass the person that did the applying. - def apply(cls, group, requester): - ''' - Apply a person to a group - ''' - if group in cls.memberships: - raise fas.ApplyError, _('user is already in this group') - else: - role = PersonRoles() - role.role_status = 'unapproved' - role.role_type = 'user' - role.member = cls - role.group = group - - def upgrade(cls, group, requester): - ''' - Upgrade a user in a group - requester for logging purposes - ''' - if not group in cls.memberships: - raise fas.UpgradeError, _('user is not a member') - else: - role = PersonRoles.query.filter_by(member=cls, group=group).one() - if role.role_type == 'administrator': - raise fas.UpgradeError, _('administrators cannot be upgraded any further') - elif role.role_type == 'sponsor': - role.role_type = 'administrator' - elif role.role_type == 'user': - role.role_type = 'sponsor' - - def downgrade(cls, group, requester): - ''' - Downgrade a user in a group - requester for logging purposes - ''' - if not group in cls.memberships: - raise fas.DowngradeError, _('user is not a member') - else: - role = PersonRoles.query.filter_by(member=cls, group=group).one() - if role.role_type == 'user': - raise fas.DowngradeError, _('users cannot be downgraded any further') - elif role.role_type == 'sponsor': - role.role_type = 'user' - elif role.role_type == 'administrator': - role.role_type = 'sponsor' - - def sponsor(cls, group, requester): - # If we want to do logging, this might be the place. - if not group in cls.unapproved_memberships: - raise fas.SponsorError, _('user is not an unapproved member') - role = PersonRoles.query.filter_by(member=cls, group=group).one() - role.role_status = 'approved' - role.sponsor = requester - role.approval = datetime.now(pytz.utc) - cls._handle_auto_add(group, requester) - - def _handle_auto_add(cls, group, requester): - """ - Handle automatic group approvals - """ - auto_approve_groups = config.get('auto_approve_groups') - associations = auto_approve_groups.split('|') - approve_group_queue = [] - for association in associations: - (groupname, approve_groups) = association.split(':', 1) - if groupname == group.name: - approve_group_queue.extend(approve_groups.split(',')) - for groupname in approve_group_queue: - approve_group = Groups.by_name(groupname) - cls._auto_add(approve_group, requester) - - def _auto_add(cls, group, requester): - """ - Ensure that a person is approved in a group - """ - try: - role = PersonRoles.query.filter_by(member=cls, group=group).one() - if role.role_status != 'approved': - role.role_status = 'approved' - role.sponsor = requester - role.approval = datetime.now(pytz.utc) - except InvalidRequestError: - role = PersonRoles() - role.role_status = 'approved' - role.role_type = 'user' - role.member = cls - role.group = group - - def remove(cls, group, requester): - if not group in cls.memberships: - raise fas.RemoveError, _('user is not a member') - else: - role = PersonRoles.query.filter_by(member=cls, group=group).one() - session.delete(role) - - def __repr__(cls): - return "User(%s,%s)" % (cls.username, cls.human_name) - - def __json__(self): - '''We want to make sure we keep a tight reign on sensistive information. - Thus we strip out certain information unless a user is an admin or the - current user. - - Current access restrictions - =========================== - - Anonymous users can see: - :id: The id in the account system and on the shell servers - :username: Username in FAS - :human_name: Human name of the person - :comments: Comments that the user leaves about themselves - :creation: Date this account was created - :ircnick: User's nickname on IRC - :last_seen: timestamp the user last logged into anything tied to - the account system - :status: Whether the user is active, inactive, on vacation, etc - :status_change: timestamp that the status was last updated - :locale: User's default locale for Fedora Services - :timezone: User's timezone - :latitude: Used for constructing maps of contributors - :longitude: Used for contructing maps of contributors - - Authenticated Users add: - :ssh_key: Public key for connecting to over ssh - :gpg_keyid: gpg key of the user - :affiliation: company or group the user wishes to identify with - :certificate_serial: serial number of the user's Fedora SSL - Certificate - - User Themselves add: - :password: hashed password to identify the user - :passwordtoken: used when the user needs to reset a password - :password_changed: last time the user changed the password - :postal_address: user's postal address - :telephone: user's telephone number - :facsimile: user's FAX number - - Admins gets access to this final field as well: - :internal_comments: Comments an admin wants to write about a user - - Note: There are a few other resources that are not located directly in - the People structure that you are likely to want to pass to consuming - code like email address and groups. Please see the documentation on - SABase.__json__() to find out how to set jsonProps to handle those. - ''' - props = super(People, self).__json__() - if not identity.in_group('admin'): - # Only admins can see internal_comments - del props['internal_comments'] - del props['emailtoken'] - del props['passwordtoken'] - if identity.current.anonymous: - # Anonymous users can't see any of these - del props['email'] - del props['unverified_email'] - del props['ssh_key'] - del props['gpg_keyid'] - del props['affiliation'] - del props['certificate_serial'] - del props['password'] - del props['password_changed'] - del props['postal_address'] - del props['telephone'] - del props['facsimile'] - # TODO: Are we still doing the fas-system thing? I think I saw a systems users somewhere... - elif not identity.current.user.username == self.username and 'fas-system' not in identity.current.groups: - # Only an admin or the user themselves can see these fields - del props['unverified_email'] - del props['password'] - del props['postal_address'] - del props['password_changed'] - del props['telephone'] - del props['facsimile'] - - return props - - memberships = association_proxy('roles', 'group') - approved_memberships = association_proxy('approved_roles', 'group') - unapproved_memberships = association_proxy('unapproved_roles', 'group') - -class PersonRoles(SABase): - '''Record people that are members of groups.''' - def __repr__(cls): - return "PersonRole(%s,%s,%s,%s)" % (cls.member.username, cls.group.name, cls.role_type, cls.role_status) - groupname = association_proxy('group', 'name') - -class Configs(SABase): - '''Configs for applications that a Fedora Contributor uses.''' - pass - -class Groups(SABase): - '''Group that people can belong to.''' - - @classmethod - def by_id(cls, id): - ''' - A class method that can be used to search groups - based on their unique id - ''' - return cls.query.filter_by(id=id).one() - - @classmethod - def by_email_address(cls, email): - ''' - A class method that can be used to search groups - based on their email addresses since it is unique. - ''' - return cls.query.filter_by(email=email).one() - - - @classmethod - def by_name(cls, name): - ''' - A class method that permits to search groups - based on their name attribute. - ''' - return cls.query.filter_by(name=name).one() - - def __repr__(cls): - return "Groups(%s,%s)" % (cls.name, cls.display_name) - - # People in the group - people = association_proxy('roles', 'member') - # Groups in the group - groups = association_proxy('group_members', 'member') - # Groups that this group belongs to - memberships = association_proxy('group_roles', 'group') - -class GroupRoles(SABase): - '''Record groups that are members of other groups.''' - pass - -class BugzillaQueue(SABase): - '''Queued up changes that need to be applied to bugzilla.''' - pass - -class Log(SABase): - '''Write simple logs of changes to the database.''' - pass - -class Requests(SABase): - ''' - Requests for certain resources may be restricted based on the user or host. - ''' - pass - -# -# Classes for mapping arbitrary selectables (This is similar to a view in -# python rather than in the db -# - -class ApprovedRoles(PersonRoles): - '''Only display roles that are approved.''' - pass - -class UnApprovedRoles(PersonRoles): - '''Only show Roles that are not approved.''' - pass - -# -# Classes for the SQLAlchemy Visit Manager -# - -class Visit(SABase): - '''Track how many people are visiting the website. - - It doesn't currently make sense for us to track this here so we clear this - table of stale records every hour. - ''' - @classmethod - def lookup_visit(cls, visit_key): - return cls.query.get(visit_key) - -class VisitIdentity(SABase): - '''Associate a user with a visit cookie. - - This allows users to log in to app. - ''' - pass - -# -# set up mappers between tables and classes -# - -# -# mappers for filtering roles -# -mapper(ApprovedRoles, ApprovedRolesSelect, properties = { - 'group': relation(Groups, backref='approved_roles', lazy = False) - }) -mapper(UnApprovedRoles, UnApprovedRolesSelect, properties = { - 'group': relation(Groups, backref='unapproved_roles', lazy = False) - }) - -mapper(People, PeopleTable, properties = { - # This name is kind of confusing. It's to allow person.group_roles['groupname'] in order to make auth.py (hopefully) slightly faster. - 'group_roles': relation(PersonRoles, - collection_class = attribute_mapped_collection('groupname'), - primaryjoin = PeopleTable.c.id==PersonRolesTable.c.person_id), - 'approved_roles': relation(ApprovedRoles, backref='member', - primaryjoin = PeopleTable.c.id==ApprovedRoles.c.person_id), - 'unapproved_roles': relation(UnApprovedRoles, backref='member', - primaryjoin = PeopleTable.c.id==UnApprovedRoles.c.person_id) - }) -mapper(PersonRoles, PersonRolesTable, properties = { - 'member': relation(People, backref = 'roles', lazy = False, - primaryjoin=PersonRolesTable.c.person_id==PeopleTable.c.id), - 'group': relation(Groups, backref='roles', lazy = False, - primaryjoin=PersonRolesTable.c.group_id==GroupsTable.c.id), - 'sponsor': relation(People, uselist=False, - primaryjoin = PersonRolesTable.c.sponsor_id==PeopleTable.c.id) - }) -mapper(Configs, ConfigsTable, properties = { - 'person': relation(People, backref = 'configs') - }) -mapper(Groups, GroupsTable, properties = { - 'owner': relation(People, uselist=False, - primaryjoin = GroupsTable.c.owner_id==PeopleTable.c.id), - 'prerequisite': relation(Groups, uselist=False, - primaryjoin = GroupsTable.c.prerequisite_id==GroupsTable.c.id) - }) -# GroupRoles are complex because the group is a member of a group and thus -# is referencing the same table. -mapper(GroupRoles, GroupRolesTable, properties = { - 'member': relation(Groups, backref = 'group_roles', - primaryjoin = GroupsTable.c.id==GroupRolesTable.c.member_id), - 'group': relation(Groups, backref = 'group_members', - primaryjoin = GroupsTable.c.id==GroupRolesTable.c.group_id), - 'sponsor': relation(People, uselist=False, - primaryjoin = GroupRolesTable.c.sponsor_id==PeopleTable.c.id) - }) -mapper(BugzillaQueue, BugzillaQueueTable, properties = { - 'group': relation(Groups, backref = 'pending'), - 'person': relation(People, backref = 'pending'), - ### TODO: test to be sure SQLAlchemy only loads the backref on demand - 'author': relation(People, backref='changes') - }) -mapper(Requests, RequestsTable, properties = { - 'person': relation(People, backref='requests') - }) -mapper(Log, LogTable) - -# TurboGears Identity -mapper(Visit, visits_table) -mapper(VisitIdentity, visit_identity_table, - properties=dict(users=relation(People, backref='visit_identity'))) diff --git a/fas/build/lib/fas/openid_fas.py b/fas/build/lib/fas/openid_fas.py deleted file mode 100644 index f9ca8c7..0000000 --- a/fas/build/lib/fas/openid_fas.py +++ /dev/null @@ -1,112 +0,0 @@ -import turbogears -from turbogears import controllers, expose, paginate, identity, redirect, widgets, validate, validators, error_handler, config -from cherrypy import session - -import cherrypy - -from openid.server.server import Server as OpenIDServer -from openid.server.server import BROWSER_REQUEST_MODES -from openid.server.server import OPENID_PREFIX -from openid.store.filestore import FileOpenIDStore - -from fas.auth import * - -from fas.user import KnownUser - -class UserID(validators.Schema): - targetname = KnownUser - -class OpenID(controllers.Controller): - - def __init__(self): - '''Create a OpenID Controller.''' - store = FileOpenIDStore(config.get('openidstore')) - self.openid_server = OpenIDServer(store)#, turbogears.url('/openid/server')) - - @expose() - def index(self): - turbogears.redirect('/openid/about') - return dict() - - @expose(template="fas.templates.openid.about") - def about(self): - '''Display an explanatory message about the OpenID service''' - username = turbogears.identity.current.user_name - return dict(username=username) - - @expose(template="genshi-text:fas.templates.openid.auth", format="text", content_type='text/plain; charset=utf-8') - def server(self, **query): - '''Perform OpenID auth''' - openid_server = self.openid_server - openid_query = {} - openid_request = None - if not session.has_key('openid_trusted'): - session['openid_trusted'] = [] - if query.has_key('url') and query.has_key('trusted') and query['trusted'] == 'allow': - session['openid_trusted'].append(query['url']) - if query.has_key('openid'): - try: - for key in query['openid'].keys(): - openid_key = OPENID_PREFIX + key - openid_query[openid_key] = query['openid'][key] - openid_request = openid_server.decodeRequest(openid_query) - session['openid_request'] = openid_request - except KeyError: - turbogears.flash(_('The OpenID request could not be decoded.')) - elif session.has_key('openid_request'): - openid_request = session['openid_request'] - if openid_request is None: - turbogears.redirect('/openid/about') - return dict() - else: - openid_response = None - if openid_request.mode in BROWSER_REQUEST_MODES: - username = turbogears.identity.current.user_name; - url = None - if username is not None: - url = config.get('base_url') + turbogears.url('/openid/id/%s' % username) - if openid_request.identity == url: - if openid_request.trust_root in session['openid_trusted']: - openid_response = openid_request.answer(True) - elif openid_request.immediate: - openid_response = openid_request.answer(False, server_url=config.get('base_url') + turbogears.url('/openid/server')) - else: - if query.has_key('url') and not query.has_key('allow'): - openid_response = openid_request.answer(False, server_url=config.get('base_url') + turbogears.url('/openid/server')) - else: - turbogears.redirect('/openid/trusted', url=openid_request.trust_root) - elif openid_request.immediate: - openid_response = openid_request.answer(False, server_url=config.get('base_url') + turbogears.url('/openid/server')) - else: - turbogears.redirect('/openid/login') - return dict() - else: - openid_response = openid_server.handleRequest(openid_request) - web_response = openid_server.encodeResponse(openid_response) - for name, value in web_response.headers.items(): - cherrypy.response.headers[name] = value; - cherrypy.response.status = web_response.code - return dict(body=web_response.body) - - @identity.require(turbogears.identity.not_anonymous()) - @expose(template="fas.templates.openid.trusted") - def trusted(self, url): - '''Ask the user if they trust a site for OpenID authentication''' - return dict(url=url) - - @identity.require(turbogears.identity.not_anonymous()) - @expose() - def login(self): - '''This exists only to make the user login and then redirect to /openid/server''' - turbogears.redirect('/openid/server') - return dict() - - - @expose(template="fas.templates.openid.id") - @validate(validators=UserID()) - def id(self, username): - '''The "real" OpenID URL''' - person = People.by_username(username) - server = config.get('base_url') + turbogears.url('/openid/server') - return dict(person=person, server=server) - diff --git a/fas/build/lib/fas/openssl_fas.py b/fas/build/lib/fas/openssl_fas.py deleted file mode 100644 index 1681d22..0000000 --- a/fas/build/lib/fas/openssl_fas.py +++ /dev/null @@ -1,82 +0,0 @@ -# Pretty much all copied from pyOpenSSL's certgen.py example and func's certs.py - -from OpenSSL import crypto -TYPE_RSA = crypto.TYPE_RSA -TYPE_DSA = crypto.TYPE_DSA - -def retrieve_key_from_file(keyfile): - fo = open(keyfile, 'r') - buf = fo.read() - keypair = crypto.load_privatekey(crypto.FILETYPE_PEM, buf) - return keypair - -def retrieve_cert_from_file(certfile): - fo = open(certfile, 'r') - buf = fo.read() - cert = crypto.load_certificate(crypto.FILETYPE_PEM, buf) - return cert - -def createKeyPair(type, bits): - """ - Create a public/private key pair. - - Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA - bits - Number of bits to use in the key - Returns: The public/private key pair in a PKey object - """ - pkey = crypto.PKey() - pkey.generate_key(type, bits) - return pkey - -def createCertRequest(pkey, digest="md5", **name): - """ - Create a certificate request. - - Arguments: pkey - The key to associate with the request - digest - Digestion method to use for signing, default is md5 - **name - The name of the subject of the request, possible - arguments are: - C - Country name - ST - State or province name - L - Locality name - O - Organization name - OU - Organizational unit name - CN - Common name - emailAddress - E-mail address - Returns: The certificate request in an X509Req object - """ - req = crypto.X509Req() - subj = req.get_subject() - - for (key,value) in name.items(): - setattr(subj, key, value) - - req.set_pubkey(pkey) - req.sign(pkey, digest) - return req - -def createCertificate(req, (issuerCert, issuerKey), serial, (notBefore, notAfter), digest="md5"): - """ - Generate a certificate given a certificate request. - - Arguments: req - Certificate reqeust to use - issuerCert - The certificate of the issuer - issuerKey - The private key of the issuer - serial - Serial number for the certificate - notBefore - Timestamp (relative to now) when the certificate - starts being valid - notAfter - Timestamp (relative to now) when the certificate - stops being valid - digest - Digest method to use for signing, default is md5 - Returns: The signed certificate in an X509 object - """ - cert = crypto.X509() - cert.set_serial_number(serial) - cert.gmtime_adj_notBefore(notBefore) - cert.gmtime_adj_notAfter(notAfter) - cert.set_issuer(issuerCert.get_subject()) - cert.set_subject(req.get_subject()) - cert.set_pubkey(req.get_pubkey()) - cert.sign(issuerKey, digest) - return cert - diff --git a/fas/build/lib/fas/release.py b/fas/build/lib/fas/release.py deleted file mode 100644 index 35e271d..0000000 --- a/fas/build/lib/fas/release.py +++ /dev/null @@ -1,18 +0,0 @@ -''' -Release information about the Fedora Accounts System -''' - -VERSION = '0.8.1' -NAME = 'fas' -DESCRIPTION = 'The Fedora Account System' -LONG_DESCRIPTION = ''' -Manage the accounts of contributors to the Fedora Project. -''' -AUTHOR = 'Ricky Zhou, Mike McGrath, and Toshio Kuratomi' -EMAIL = 'fedora-infrastructure-list@fedoraproject.org' -COPYRIGHT = '2007-2008 Red Hat, Inc.' - -# if it's open source, you might want to specify these -URL = 'https://admin.fedoraproject.org/accounts/' -DOWNLOAD_URL = 'https://fas2.fedorahosted.org/' -LICENSE = 'GPLv2' diff --git a/fas/build/lib/fas/safasprovider.py b/fas/build/lib/fas/safasprovider.py deleted file mode 100644 index ac0220e..0000000 --- a/fas/build/lib/fas/safasprovider.py +++ /dev/null @@ -1,219 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright © 2007-2008 Red Hat, Inc. All rights reserved. -# -# This copyrighted material is made available to anyone wishing to use, modify, -# copy, or redistribute it subject to the terms and conditions of the GNU -# General Public License v.2. This program is distributed in the hope that it -# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the -# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# See the GNU General Public License for more details. You should have -# received a copy of the GNU General Public License along with this program; -# if not, write to the Free Software Foundation, Inc., 51 Franklin Street, -# Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat trademarks that are -# incorporated in the source code or documentation are not subject to the GNU -# General Public License and may only be used or replicated with the express -# permission of Red Hat, Inc. -# -# Red Hat Author(s): Toshio Kuratomi -# - -''' -This plugin provides authentication of passwords against the Fedora Account -System. -''' - - - -from sqlalchemy.orm import class_mapper -from turbogears import config, identity -from turbogears.identity.saprovider import SqlAlchemyIdentity, \ - SqlAlchemyIdentityProvider -from turbogears.database import session -from turbogears.util import load_class - -import gettext -t = gettext.translation('python-fedora', '/usr/share/locale', fallback=True) -_ = t.ugettext - -import crypt - -import logging -log = logging.getLogger('turbogears.identity.safasprovider') - -try: - set, frozenset -except NameError: - from sets import Set as set, ImmutableSet as frozenset - -# Global class references -- -# these will be set when the provider is initialised. -user_class = None -visit_identity_class = None - -class SaFasIdentity(SqlAlchemyIdentity): - def __init__(self, visit_key, user=None): - super(SaFasIdentity, self).__init__(visit_key, user) - - def _get_user(self): - try: - return self._user - except AttributeError: - # User hasn't already been set - pass - # Attempt to load the user. After this code executes, there *WILL* be - # a _user attribute, even if the value is None. - ### TG: Difference: Can't use the inherited method b/c of global var - visit = visit_identity_class.query.filter_by(visit_key = self.visit_key).first() - if not visit: - self._user = None - return None - self._user = user_class.query.get(visit.user_id) - return self._user - user = property(_get_user) - - def _get_user_name(self): - if not self.user: - return None - ### TG: Difference: Different name for the field - return self.user.username - user_name = property(_get_user_name) - - def _get_groups(self): - try: - return self._groups - except AttributeError: - # Groups haven't been computed yet - pass - if not self.user: - self._groups = frozenset() - else: - ### TG: Difference. Our model has a many::many for people:groups - # And an association proxy that links them together - self._groups = frozenset([g.name for g in self.user.approved_memberships]) - return self._groups - groups = property(_get_groups) - - def logout(self): - ''' - Remove the link between this identity and the visit. - ''' - if not self.visit_key: - return - try: - ### TG: Difference: Can't inherit b/c this uses a global var - visit = visit_identity_class.query.filter_by(visit_key=self.visit_key).first() - session.delete(visit) - # Clear the current identity - anon = SqlAlchemyIdentity(None,None) - identity.set_current_identity(anon) - except: - pass - else: - session.flush() - -class SaFasIdentityProvider(SqlAlchemyIdentityProvider): - ''' - IdentityProvider that authenticates users against the fedora account system - ''' - def __init__(self): - global visit_identity_class - global user_class - - user_class_path = config.get("identity.saprovider.model.user", None) - user_class = load_class(user_class_path) - visit_identity_class_path = config.get("identity.saprovider.model.visit", None) - log.info(_("Loading: %(visitmod)s") % \ - {'visitmod': visit_identity_class_path}) - visit_identity_class = load_class(visit_identity_class_path) - - def create_provider_model(self): - ''' - Create the database tables if they don't already exist. - ''' - class_mapper(user_class).local_table.create(checkfirst=True) - class_mapper(visit_identity_class).local_table.create(checkfirst=True) - - def validate_identity(self, user_name, password, visit_key): - ''' - Look up the identity represented by user_name and determine whether the - password is correct. - - Must return either None if the credentials weren't valid or an object - with the following properties: - user_name: original user name - user: a provider dependant object (TG_User or similar) - groups: a set of group IDs - permissions: a set of permission IDs - ''' - user = user_class.query.filter_by(username=user_name).first() - if not user: - log.warning("No such user: %s", user_name) - return None - if not self.validate_password(user, user_name, password): - log.info("Passwords don't match for user: %s", user_name) - return None - - log.info("associating user (%s) with visit (%s)", user.username, - visit_key) - # Link the user to the visit - link = visit_identity_class.query.filter_by(visit_key=visit_key).first() - if not link: - link = visit_identity_class() - link.visit_key = visit_key - link.user_id = user.id - else: - link.user_id = user.id - session.flush() - return SaFasIdentity(visit_key, user) - - def validate_password(self, user, user_name, password): - ''' - Check the supplied user_name and password against existing credentials. - Note: user_name is not used here, but is required by external - password validation schemes that might override this method. - If you use SqlAlchemyIdentityProvider, but want to check the passwords - against an external source (i.e. PAM, LDAP, Windows domain, etc), - subclass SqlAlchemyIdentityProvider, and override this method. - - Arguments: - :user: User information. Not used. - :user_name: Given username. - :password: Given, plaintext password. - - Returns: True if the password matches the username. Otherwise False. - Can return False for problems within the Account System as well. - ''' - - return user.password == crypt.crypt(password, user.password) - - def load_identity(self, visit_key): - '''Lookup the principal represented by visit_key. - - Arguments: - :visit_key: The session key for whom we're looking up an identity. - - Must return an object with the following properties: - user_name: original user name - user: a provider dependant object (TG_User or similar) - groups: a set of group IDs - permissions: a set of permission IDs - ''' - return SaFasIdentity(visit_key) - - def anonymous_identity(self): - ''' - Must return an object with the following properties: - user_name: original user name - user: a provider dependant object (TG_User or similar) - groups: a set of group IDs - permissions: a set of permission IDs - ''' - - return SaFasIdentity(None) - - def authenticated_identity(self, user): - ''' - Constructs Identity object for user that has no associated visit_key. - ''' - return SaFasIdentity(None, user) diff --git a/fas/build/lib/fas/templates/__init__.py b/fas/build/lib/fas/templates/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/fas/build/lib/fas/templates/about.html b/fas/build/lib/fas/templates/about.html deleted file mode 100644 index d6dbd9f..0000000 --- a/fas/build/lib/fas/templates/about.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - ${_('About FAS')} - - -

${_('FAS - The Open Account System')}

-

${_('''FAS is designed around an open architecture. Unlike the traditional account systems where a single admin or group of admins decide who gets to be in what group, FAS is completely designed to be self operating per team. Every group is given at least one administrator who can then approve other people in the group. Also, unlike traditional account systems. FAS allows people to apply for the groups they want to be in. This paridigm is interesting as it allows anyone to find out who is in what groups and contact them. This openness is brought over from the same philosophies that make Open Source popular.''')}

-

${_('Etiquette')}

-

${_("People shouldn't assume that by applying for a group that they're then in that group. Consider it like applying for another job. It often takes time. For best odds of success, learn about the group you're applying for and get to know someone in the group. Find someone with sponsor or admin access and ask them if they'd have time to mentor you. Plan on spending at least a few days learning about the group, doing a mundain task, participating on the mailing list. Sometimes this process can take weeks depending on the group. It's best to know you will get sponsored before you apply.")}

-

${_('Users, Sponsors, Administrators')}

-

${_('''Once you're in the group, you're in the group. Sponsorship and Administrators typically have special access in the group in questions. Some groups consider sponsorship level to be of a higher involvement, partial ownership of the group for example. But as far as the account system goes the disctinction is easy. Sponsors can approve new users and make people into sponsors. They cannot, however, downgrade or remove other sponsors. They also cannot change administrators in any way. Administrators can do anything to anyone in the group.''')}

- - diff --git a/fas/build/lib/fas/templates/cla/__init__.py b/fas/build/lib/fas/templates/cla/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/fas/build/lib/fas/templates/cla/cla.html b/fas/build/lib/fas/templates/cla/cla.html deleted file mode 100644 index 34643a3..0000000 --- a/fas/build/lib/fas/templates/cla/cla.html +++ /dev/null @@ -1,82 +0,0 @@ -
-

The Fedora Project - Individual Contributor License Agreement (CLA) -

- http://fedoraproject.org/wiki/Legal/Licenses/CLA -

- Thank you for your interest in The Fedora Project (the "Project"). In order to clarify the intellectual property license granted with Contributions from any person or entity, Red hat, Inc. ("Red Hat"), as maintainer of the Project, must have a Contributor License Agreement (CLA) on file that has been signed by each Contributor, indicating agreement to the license terms below. This license is for Your protection as a Contributor as well as the protection of the Project and its users; it does not change your rights to use your own Contributions for any other purpose. -

-

- If you have not already done so, please complete an original signed Agreement. Use black ink, and hand-print or type the items other than the signature. Send the completed Agreement to -

-
- Fedora Project, c/o Red Hat, Inc.,
- Attn: Legal Affairs
- 1801 Varsity Drive
- Raleigh, North Carolina, 27606 U.S.A. -
-

- If necessary, you may send it by facsimile to the Project at +1-919-754-3704 or e-mail a signed pdf copy of the document to fedora-legal@redhat.com. Please read this document carefully before signing and keep a copy for your records. -

-

- Full name: ${person.human_name}
- E-Mail: ${person.email}
- Address: ${person.postal_address}
- Telephone: ${person.telephone} - -

-

- You and the Project hereby accept and agree to the following terms and conditions: -

-
    -
  1. - Contributors and Contributions. -
      -
    1. - The Project and any individual or legal entity that voluntarily submits to the Project a Contribution are collectively addressed herein as "Contributors". For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. -
    2. -
    3. - A "Contribution" is any original work, including any modification or addition to an existing work, that has been submitted for inclusion in, or documentation of, any of the products owned or managed by the Project, where such work originates from that particular Contributor or from some entity acting on behalf of that Contributor. -
    4. -
    5. - A Contribution is "submitted" when any form of electronic, verbal, or written communication is sent to the Project, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of discussing or improving software or documentation of the Project, but excluding communication that is conspicuously marked or otherwise designated in writing by you as "Not a Contribution." -
    6. -
    7. - Any Contribution submitted by you to the Project shall be under the terms and conditions of this License, without any additional terms or conditions, unless you explicitly state otherwise in the submission. -
    8. -
    -
  2. -
  3. - Contributor Grant of License. You hereby grant to Red Hat, Inc., on behalf of the Project, and to recipients of software distributed by the Project: -
      -
    1. - a perpetual, non-exclusive, worldwide, fully paid-up, royalty free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute your Contribution and such derivative works; and, -
    2. -
    3. - a perpetual, non-exclusive, worldwide, fully paid-up, royalty free, irrevocable (subject to Section 3) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer your Contribution and derivative works thereof, where such license applies only to those patent claims licensable by you that are necessarily infringed by your Contribution alone or by combination of your Contribution with the work to which you submitted the Contribution. Except for the license granted in this section, you reserve all right, title and interest in and to your Contributions. -
    4. -
    -
  4. -
  5. - Reciprocity. As of the date any such litigation is filed, your patent grant shall immediately terminate with respect to any party that institutes patent litigation against you (including a cross-claim or counterclaim in a lawsuit) alleging that your Contribution, or the work to which you have contributed, constitutes direct or contributory patent infringement. -
  6. -
  7. - You represent that you are legally entitled to grant the above license. If your employer(s) has rights to intellectual property that you create that includes your Contributions, you represent that you have received permission to make Contributions on behalf of that employer, that your employer has waived such rights for your Contributions to the Project, or that your employer has executed a separate Corporate CLA with the Project. -
  8. -
  9. - You represent that each of your Contributions is your original creation (see section 7 for submissions on behalf of others). You represent that your Contribution submission(s) include complete details of any third-party license or other restriction (including, but not limited to, related copyright, atents and trademarks) of which you are personally aware and which are associated with any part of your Contribution. -
  10. -
  11. - You are not expected to provide support for your Contributions, except to the extent you desire to provide support. You may provide support for free, for a fee, or not at all. Your Contributions are provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. -
  12. -
  13. - Should you wish to submit work that is not your original creation, you may submit it to the Project separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which you are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [named here]". -
  14. -
  15. - You agree to notify the Project of any facts or circumstances of which you become aware that would make these representations inaccurate in any respect. -
  16. -
  17. - The Project is under no obligations to accept and include every contribution. -
  18. -
-
diff --git a/fas/build/lib/fas/templates/cla/cla.txt b/fas/build/lib/fas/templates/cla/cla.txt deleted file mode 100644 index 7d6d482..0000000 --- a/fas/build/lib/fas/templates/cla/cla.txt +++ /dev/null @@ -1,145 +0,0 @@ - The Fedora Project - Individual Contributor License Agreement (CLA) - http://fedoraproject.org/wiki/Legal/Licenses/CLA - - Thank you for your interest in The Fedora Project (the - "Project"). In order to clarify the intellectual property license - granted with Contributions from any person or entity, Red hat, - Inc. ("Red Hat"), as maintainer of the Project, must have a - Contributor License Agreement (CLA) on file that has been signed - by each Contributor, indicating agreement to the license terms - below. This license is for Your protection as a Contributor as - well as the protection of the Project and its users; it does not - change your rights to use your own Contributions for any other - purpose. - - If you have not already done so, please complete an original signed - Agreement. Use black ink, and hand-print or type the items other than - the signature. Send the completed Agreement to - - Fedora Project, c/o Red Hat, Inc., - Attn: Legal Affairs - 1801 Varsity Drive - Raleigh, North Carolina, 27606 U.S.A. - - If necessary, you may send it by facsimile to the Project at - +1-919-754-3704 or e-mail a signed pdf copy of the document to - fedora-legal@redhat.com. Please read this document carefully before - signing and keep a copy for your records. - - Full name: ${person.human_name} E-Mail: ${person.email} - - Address: -${person.postal_address} - - Telephone: ${person.telephone} - - Facsimile: ${person.facsimile} - - You and the Project hereby accept and agree to the following terms and conditions: - - 1. Contributors and Contributions. - - A. The Project and any individual or legal entity that - voluntarily submits to the Project a Contribution are - collectively addressed herein as "Contributors". For legal - entities, the entity making a Contribution and all other - entities that control, are controlled by, or are under common - control with that entity are considered to be a single - Contributor. For the purposes of this definition, "control" - means (i) the power, direct or indirect, to cause the direction - or management of such entity, whether by contract or otherwise, - or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such - entity. - - B. A "Contribution" is any original work, including any - modification or addition to an existing work, that has been - submitted for inclusion in, or documentation of, any of the - products owned or managed by the Project, where such work - originates from that particular Contributor or from some entity - acting on behalf of that Contributor. - - C. A Contribution is "submitted" when any form of electronic, - verbal, or written communication is sent to the Project, - including but not limited to communication on electronic - mailing lists, source code control systems, and issue tracking - systems that are managed by, or on behalf of, the Project for - the purpose of discussing or improving software or - documentation of the Project, but excluding communication that - is conspicuously marked or otherwise designated in writing by - you as "Not a Contribution." - - D. Any Contribution submitted by you to the Project shall be - under the terms and conditions of this License, without any - additional terms or conditions, unless you explicitly state - otherwise in the submission. - - 2. Contributor Grant of License. You hereby grant to Red Hat, - Inc., on behalf of the Project, and to recipients of software - distributed by the Project: - - (a) a perpetual, non-exclusive, worldwide, fully paid-up, - royalty free, irrevocable copyright license to reproduce, - prepare derivative works of, publicly display, publicly - perform, sublicense, and distribute your Contribution and such - derivative works; and, - - (b) a perpetual, non-exclusive, worldwide, fully paid-up, - royalty free, irrevocable (subject to Section 3) patent license - to make, have made, use, offer to sell, sell, import, and - otherwise transfer your Contribution and derivative works - thereof, where such license applies only to those patent claims - licensable by you that are necessarily infringed by your - Contribution alone or by combination of your Contribution with - the work to which you submitted the Contribution. Except for - the license granted in this section, you reserve all right, - title and interest in and to your Contributions. - - 3. Reciprocity. As of the date any such litigation is filed, your - patent grant shall immediately terminate with respect to any - party that institutes patent litigation against you (including - a cross-claim or counterclaim in a lawsuit) alleging that your - Contribution, or the work to which you have contributed, - constitutes direct or contributory patent infringement. - - 4. You represent that you are legally entitled to grant the above - license. If your employer(s) has rights to intellectual - property that you create that includes your Contributions, you - represent that you have received permission to make - Contributions on behalf of that employer, that your employer - has waived such rights for your Contributions to the Project, - or that your employer has executed a separate Corporate CLA - with the Project. - - 5. You represent that each of your Contributions is your original - creation (see section 7 for submissions on behalf of others). - You represent that your Contribution submission(s) include - complete details of any third-party license or other - restriction (including, but not limited to, related copyright, - atents and trademarks) of which you are personally aware and - which are associated with any part of your Contribution. - - 6. You are not expected to provide support for your Contributions, - except to the extent you desire to provide support. You may - provide support for free, for a fee, or not at all. Your - Contributions are provided on an "AS IS" BASIS, WITHOUT - WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or - conditions of NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR - A PARTICULAR PURPOSE. - - 7. Should you wish to submit work that is not your original - creation, you may submit it to the Project separately from any - Contribution, identifying the complete details of its source - and of any license or other restriction (including, but not - limited to, related patents, trademarks, and license - agreements) of which you are personally aware, and - conspicuously marking the work as "Submitted on behalf of a - third-party: [named here]". - - 8. You agree to notify the Project of any facts or circumstances - of which you become aware that would make these representations - inaccurate in any respect. - - 9. The Project is under no obligations to accept and include every contribution. diff --git a/fas/build/lib/fas/templates/cla/index.html b/fas/build/lib/fas/templates/cla/index.html deleted file mode 100644 index ff8f9e6..0000000 --- a/fas/build/lib/fas/templates/cla/index.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - ${_('Fedora Accounts System')} - - -

${_('Fedora Contributor License Agreement')}

- ${Markup(_('<a href="%(url)s">Text Version</a>') % {'url': tg.url('/cla/text')})} - - ${Markup(_('<a href="%(url)s">Text Version</a>') % {'url': tg.url('/cla/text')})} -

- ${Markup(_('You have already sucessfully complete the CLA.') % {'url': tg.url('/cla/text')})} -

- -
-
- - -
-
-
- - diff --git a/fas/build/lib/fas/templates/error.html b/fas/build/lib/fas/templates/error.html deleted file mode 100644 index c72b965..0000000 --- a/fas/build/lib/fas/templates/error.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - ${_('Fedora Accounts System')} - - - -

${_('Error!')}

-

${_('The following error(s) have occured with your request:')}

-
    -
  • - ${field}: ${str(error)} -
  • -
- - diff --git a/fas/build/lib/fas/templates/group/__init__.py b/fas/build/lib/fas/templates/group/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/fas/build/lib/fas/templates/group/dump.txt b/fas/build/lib/fas/templates/group/dump.txt deleted file mode 100644 index 7219bd4..0000000 --- a/fas/build/lib/fas/templates/group/dump.txt +++ /dev/null @@ -1,3 +0,0 @@ -#for person in sorted(people) -${person.username},${person.email},${person.human_name},user,0 -#end diff --git a/fas/build/lib/fas/templates/group/edit.html b/fas/build/lib/fas/templates/group/edit.html deleted file mode 100644 index 8df9316..0000000 --- a/fas/build/lib/fas/templates/group/edit.html +++ /dev/null @@ -1,55 +0,0 @@ - - - - - ${_('Edit Group')} - - -

${_('Edit Group: %s') % group.name}

-
-
- - - -
-
- - - -
-
- - - -
-
- - - - -
-
- - - -   -
-
- - - -   -
-
- - - -
-
- -
-
- - diff --git a/fas/build/lib/fas/templates/group/invite.html b/fas/build/lib/fas/templates/group/invite.html deleted file mode 100644 index 0c537a8..0000000 --- a/fas/build/lib/fas/templates/group/invite.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - ${_('Invite a new community member!')} - - -

${_('Invite a new community member!')}

-
-
- - ${_('To email:')}
- ${_('From:')} ${person.email}
- ${_('Subject:')} Invitation to join the Fedora Team!
- ${_('Message:')} -
-

- ${person.human_name} <${person.email}> has invited you to join the Fedora - Project! We are a community of users and developers who produce a - complete operating system from entirely free and open source software - (FOSS). ${person.human_name} thinks that you have knowledge and skills - that make you a great fit for the Fedora community, and that you might - be interested in contributing. -

-

- How could you team up with the Fedora community to use and develop your - skills? Check out http://fedoraproject.org/join-fedora for some ideas. - Our community is more than just software developers -- we also have a - place for you whether you're an artist, a web site builder, a writer, or - a people person. You'll grow and learn as you work on a team with other - very smart and talented people. -

-

- Fedora and FOSS are changing the world -- come be a part of it! -

-
- -
-
- - diff --git a/fas/build/lib/fas/templates/group/list.html b/fas/build/lib/fas/templates/group/list.html deleted file mode 100644 index 59c147e..0000000 --- a/fas/build/lib/fas/templates/group/list.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - ${_('Groups List')} - - - - -

Create New Group

- Create Group -
- -

${_('List (%s)') % search}

-

${_('Search Groups')}

-
-

${_('"*" is a wildcard (Ex: "cvs*")')}

-
- - -
-
-

${_('Results')}

- - - - - - - - - - - - - -
${_('Group')}${_('Description')}${_('Status')}
${group.name}${ group.display_name } - - ${_('Approved')} - ${_('Unapproved')} - - ${_('Apply')} - -
- - diff --git a/fas/build/lib/fas/templates/group/new.html b/fas/build/lib/fas/templates/group/new.html deleted file mode 100644 index f74862c..0000000 --- a/fas/build/lib/fas/templates/group/new.html +++ /dev/null @@ -1,57 +0,0 @@ - - - - - ${_('Create a new FAS Group')} - - -

${_('Create a new FAS Group')}

-
-
- - - -
-
- - - -
-
- - - -
-
- - - -
-
- -   - -
-
- -   - -
-
- - - -
-
- - - -
-
- -
-
- - diff --git a/fas/build/lib/fas/templates/group/view.html b/fas/build/lib/fas/templates/group/view.html deleted file mode 100644 index 44d4cc8..0000000 --- a/fas/build/lib/fas/templates/group/view.html +++ /dev/null @@ -1,123 +0,0 @@ - - - - - ${_('View Group')} - - - -

${group.display_name} (${group.name})

-

- ${_('My Status:')} - ${_('Approved')} - ${_('Unapproved')} - ${_('Not a Member')} -

-
-
- - -
-
- ${_('Remove me')} - -

Group Details ${_('(edit)')}

-
-
-
${_('Name:')}
${group.name} 
-
${_('Description:')}
${group.display_name} 
-
${_('Owner:')}
${group.owner.username} 
-
${_('Type:')}
${group.group_type} 
-
${_('Needs Sponsor:')}
- ${_('Yes')} - ${_('No')} -  
-
${_('Self Removal:')}
- ${_('Yes')} - ${_('No')} -  
-
${_('Join Message:')}
${group.joinmsg} 
-
${_('Prerequisite:')}
-
${group.prerequisite.name} 
-
 
-
${_('Created:')}
${group.creation} 
- -
${_('Add User:')}
-
-
- - - -
-
-
-
-
- -

${_('Members')}

- - - - - - - - - - - - - - - - - - - - - - - - -
${_('Username')}${_('Sponsor')}${_('Date Added')}${_('Date Approved')}${_('Approval')}${_('Role Type')}${_('Action')}
${role[1].member.username}${role[1].sponsor.username}${_('None')}${role[1].creation.astimezone(timezone).strftime('%Y-%m-%d %H:%M:%S %Z')}${role[1].approval.astimezone(timezone).strftime('%Y-%m-%d %H:%M:%S %Z')}${_('None')}${role[1].role_status}${role[1].role_type} -
    -
  • - - ${_('Sponsor')} - - - - ${_('Approve')} - - -
  • -
  • - ${_('Remove')} - -
  • -
  • - ${_('Upgrade')} - -
  • -
  • - ${_('Downgrade')} - -
  • -
-
- - diff --git a/fas/build/lib/fas/templates/help.html b/fas/build/lib/fas/templates/help.html deleted file mode 100644 index b3dd861..0000000 --- a/fas/build/lib/fas/templates/help.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - ${help[0]} - - - ${XML(help[1])} - - diff --git a/fas/build/lib/fas/templates/home.html b/fas/build/lib/fas/templates/home.html deleted file mode 100644 index a12d0b9..0000000 --- a/fas/build/lib/fas/templates/home.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - ${_('Fedora Accounts System')} - - - -

${_('Todo queue:')}

- - -
-
    -
  • - ${Markup(_('<strong>%(user)s</strong> requests approval to join <a href="group/view/%(group)s">%(group)s</a>.') % {'user': role.member.username, 'group': group.name, 'group': group.name})} -
  • -
-
-
-
-
    -
  • ${Markup(_('CLA not completed. To become a full Fedora Contributor please <a href="%s">complete the CLA</a>.') % tg.url('/cla/'))}
  • -
  • ${Markup(_('You have not submitted an SSH key, some Fedora resources require an SSH key. Please submit yours by editing <a href="%s">My Account</a>') % tg.url('/user/edit'))}
  • -
-
- - ${_('Download a client-side certificate')}  - -
- - diff --git a/fas/build/lib/fas/templates/login.html b/fas/build/lib/fas/templates/login.html deleted file mode 100644 index 24bf545..0000000 --- a/fas/build/lib/fas/templates/login.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - ${_('Login to the Fedora Accounts System')} - - - -

${_('Login')}

-

${message}

-
-
-
-
- - - -
-
- - - diff --git a/fas/build/lib/fas/templates/master.html b/fas/build/lib/fas/templates/master.html deleted file mode 100644 index 4838960..0000000 --- a/fas/build/lib/fas/templates/master.html +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - -
- - -
-
- - ${_('Logged in:')} ${tg.identity.user.username} - -
- -
-
- -
-
- ${tg_flash} -
-
-
- -
-
- - diff --git a/fas/build/lib/fas/templates/openid/__init__.py b/fas/build/lib/fas/templates/openid/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/fas/build/lib/fas/templates/openid/about.html b/fas/build/lib/fas/templates/openid/about.html deleted file mode 100644 index 2cbe67f..0000000 --- a/fas/build/lib/fas/templates/openid/about.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - ${_('Fedora Accounts System')} - - -

${_('Fedora Project OpenID Provider')}

-

- ${Markup_('Description goes here, <a href="http://username.fedorapeople.org/">username.fedorapeople.org</a>')} -

- - diff --git a/fas/build/lib/fas/templates/openid/auth.txt b/fas/build/lib/fas/templates/openid/auth.txt deleted file mode 100644 index 34accd5..0000000 --- a/fas/build/lib/fas/templates/openid/auth.txt +++ /dev/null @@ -1 +0,0 @@ -${body} diff --git a/fas/build/lib/fas/templates/openid/id.html b/fas/build/lib/fas/templates/openid/id.html deleted file mode 100644 index 01a5220..0000000 --- a/fas/build/lib/fas/templates/openid/id.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - ${_('Fedora Accounts System')} - - - -

${_('User %s') % person.username}

-
-
-
${_('Username:')}
-
${person.username}
-
${_('Name:')}
-
${person.human_name}
-
-
- - diff --git a/fas/build/lib/fas/templates/openid/trusted.html b/fas/build/lib/fas/templates/openid/trusted.html deleted file mode 100644 index 0affc19..0000000 --- a/fas/build/lib/fas/templates/openid/trusted.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - ${_('Fedora Accounts System')} - - -

${_('Fedora Project OpenID Provider')}

-
-
- - -
- -
-
- - diff --git a/fas/build/lib/fas/templates/user/__init__.py b/fas/build/lib/fas/templates/user/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/fas/build/lib/fas/templates/user/cert.txt b/fas/build/lib/fas/templates/user/cert.txt deleted file mode 100644 index 692f231..0000000 --- a/fas/build/lib/fas/templates/user/cert.txt +++ /dev/null @@ -1,2 +0,0 @@ -${cert} -${key} diff --git a/fas/build/lib/fas/templates/user/changepass.html b/fas/build/lib/fas/templates/user/changepass.html deleted file mode 100644 index 189c024..0000000 --- a/fas/build/lib/fas/templates/user/changepass.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - ${_('Change Password')} - - -

${_('Change Password')}

-
-
    -
    -
    -
    -
    -
-
- - diff --git a/fas/build/lib/fas/templates/user/edit.html b/fas/build/lib/fas/templates/user/edit.html deleted file mode 100644 index 0b25090..0000000 --- a/fas/build/lib/fas/templates/user/edit.html +++ /dev/null @@ -1,88 +0,0 @@ - - - - - ${_('Edit Account')} - - -

${_('Edit Account (%s)') % target.username}

-
-
- - - -
- -
- - - - ${Markup(_('(pending change to %(email)s - <a href="%(url)s">cancel</a>)') % {'email': target.unverified_email, 'url': tg.url('/user/verifyemail/1/cancel')})} - - -
- -
- - - -
-
- - - -
-
- - - -
-
- - - -
-
- - - - -
-
- - - -
-
- - - - - -
-
- - - -
- -
- - diff --git a/fas/build/lib/fas/templates/user/list.html b/fas/build/lib/fas/templates/user/list.html deleted file mode 100644 index d2679b7..0000000 --- a/fas/build/lib/fas/templates/user/list.html +++ /dev/null @@ -1,45 +0,0 @@ - - - - - ${_('Users List')} - - - -

${_('List (%s)') % search}

-
-

${_('"*" is a wildcard (Ex: "ric*")')}

-
- - -
-
-

${_('Results')}

- - - - - - - - - - - - - - -
${_('Username')}${_('Account Status')}
${person.username} - - ${_('CLA Done')} - ${_('Not Done')} -
- - diff --git a/fas/build/lib/fas/templates/user/new.html b/fas/build/lib/fas/templates/user/new.html deleted file mode 100644 index 786cd5b..0000000 --- a/fas/build/lib/fas/templates/user/new.html +++ /dev/null @@ -1,42 +0,0 @@ - - - - - ${_('Sign up for a Fedora account')} - - -

${_('Sign up for a Fedora account')}

-
-
- - -
-
- - -
-
- - -
- -
- -
-
- - diff --git a/fas/build/lib/fas/templates/user/resetpass.html b/fas/build/lib/fas/templates/user/resetpass.html deleted file mode 100644 index d110add..0000000 --- a/fas/build/lib/fas/templates/user/resetpass.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - ${_('Reset Password')} - - -

${_('Reset Password')}

-
-
    -
    -
    -
    -
    -
-
- - diff --git a/fas/build/lib/fas/templates/user/verifyemail.html b/fas/build/lib/fas/templates/user/verifyemail.html deleted file mode 100644 index 9c5dab7..0000000 --- a/fas/build/lib/fas/templates/user/verifyemail.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - ${_('Confirm Email Change Request')} - - -

${_('Confirm Email Change Request')}

-
-
-

- ${_('Do you really want to change your email to: %s?') % person.unverified_email} -

- - ${_('Cancel')} -
-
- - diff --git a/fas/build/lib/fas/templates/user/verifypass.html b/fas/build/lib/fas/templates/user/verifypass.html deleted file mode 100644 index 763dd54..0000000 --- a/fas/build/lib/fas/templates/user/verifypass.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - ${_('Reset Password')} - - -

${_('Reset Password')}

-
-
    -
    -
    - -
-
- - diff --git a/fas/build/lib/fas/templates/user/view.html b/fas/build/lib/fas/templates/user/view.html deleted file mode 100644 index 9f2bf6c..0000000 --- a/fas/build/lib/fas/templates/user/view.html +++ /dev/null @@ -1,99 +0,0 @@ - - - - - ${_('View Account')} - - - - - -

${_('Account Details')} ${_('(edit)')}

-
-
-
${_('Account Name:')}
${person.username}
-
${_('Real Name:')}
${person.human_name}
-
${_('Email:')}
${person.email} - - ${Markup(_('(pending change to %(email)s - <a href="%(url)s">cancel</a>)') % {'email': person.unverified_email, 'url': tg.url('/user/verifyemail/1/cancel')})} - -
-
${_('Telephone Number:')}
${person.telephone} 
-
${_('Postal Address:')}
${person.postal_address} 
- -
${_('IRC Nick:')}
${person.ircnick} 
-
${_('PGP Key:')}
${person.gpg_keyid} 
-
${_('Public SSH Key:')}
-
${person.ssh_key[:20]}.... 
-
No ssh key provided 
-
-
${_('Comments:')}
${person.comments} 
-
${_('Password:')}
${_('Valid')} (change)
-
${_('Account Status:')}
- ${_('Active')} - ${_('Vacation')} - ${_('Inactive')} - ${_('Pinged')} -
-
${_('CLA:')}
- ${_('CLA Done')} - ${_('Not Done')} (${_('Complete it!')}) -
-
-
-

${_('Your Roles')}

-

${_('%s\'s Roles') % person.human_name}

- - - - - diff --git a/fas/build/lib/fas/templates/welcome.html b/fas/build/lib/fas/templates/welcome.html deleted file mode 100644 index 9d58e38..0000000 --- a/fas/build/lib/fas/templates/welcome.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - ${_('Welcome to FAS2')} - - - -

- ${Markup(_('Welcome to the Fedora Accounts System 2. Please submit bugs to <a href="https://fedorahosted.org/fas2">https://fedorahosted.org/fas2/</a> or stop by #fedora-admin on irc.freenode.net.'))} -

- - - diff --git a/fas/build/lib/fas/tests/__init__.py b/fas/build/lib/fas/tests/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/fas/build/lib/fas/tests/test_controllers.py b/fas/build/lib/fas/tests/test_controllers.py deleted file mode 100644 index b3acfac..0000000 --- a/fas/build/lib/fas/tests/test_controllers.py +++ /dev/null @@ -1,37 +0,0 @@ -import unittest -import turbogears -from turbogears import testutil -from fas.controllers import Root -import cherrypy - -cherrypy.root = Root() - -class TestPages(unittest.TestCase): - - def setUp(self): - turbogears.startup.startTurboGears() - - def tearDown(self): - """Tests for apps using identity need to stop CP/TG after each test to - stop the VisitManager thread. - See http://trac.turbogears.org/turbogears/ticket/1217 for details. - """ - turbogears.startup.stopTurboGears() - - def test_method(self): - "the index method should return a string called now" - import types - result = testutil.call(cherrypy.root.index) - assert type(result["now"]) == types.StringType - - def test_indextitle(self): - "The indexpage should have the right title" - testutil.createRequest("/") - response = cherrypy.response.body[0].lower() - assert "welcome to turbogears" in response - - def test_logintitle(self): - "login page should have the right title" - testutil.createRequest("/login") - response = cherrypy.response.body[0].lower() - assert "login" in response diff --git a/fas/build/lib/fas/tests/test_model.py b/fas/build/lib/fas/tests/test_model.py deleted file mode 100644 index 8d0187f..0000000 --- a/fas/build/lib/fas/tests/test_model.py +++ /dev/null @@ -1,22 +0,0 @@ -# If your project uses a database, you can set up database tests -# similar to what you see below. Be sure to set the db_uri to -# an appropriate uri for your testing database. sqlite is a good -# choice for testing, because you can use an in-memory database -# which is very fast. - -from turbogears import testutil, database -# from fas.model import YourDataClass, User - -# database.set_db_uri("sqlite:///:memory:") - -# class TestUser(testutil.DBTest): -# def get_model(self): -# return User -# def test_creation(self): -# "Object creation should set the name" -# obj = User(user_name = "creosote", -# email_address = "spam@python.not", -# display_name = "Mr Creosote", -# password = "Wafer-thin Mint") -# assert obj.display_name == "Mr Creosote" - diff --git a/fas/build/lib/fas/user.py b/fas/build/lib/fas/user.py deleted file mode 100644 index f3ab6ad..0000000 --- a/fas/build/lib/fas/user.py +++ /dev/null @@ -1,656 +0,0 @@ -import turbogears -from turbogears import controllers, expose, paginate, identity, redirect, widgets, validate, validators, error_handler, config -from turbogears.database import session -import cherrypy - -import turbomail - -import sqlalchemy - -import os -import re -import gpgme -import StringIO -import crypt -import random -import subprocess -from OpenSSL import crypto - -from fas.model import People -from fas.model import Log - -from fas import openssl_fas -from fas.auth import * - -from random import Random -import sha -from base64 import b64encode - -class KnownUser(validators.FancyValidator): - '''Make sure that a user already exists''' - def _to_python(self, value, state): - return value.strip() - def validate_python(self, value, state): - try: - p = People.by_username(value) - except InvalidRequestError: - raise validators.Invalid(_("'%s' does not exist.") % value, value, state) - -class UnknownUser(validators.FancyValidator): - '''Make sure that a user doesn't already exist''' - def _to_python(self, value, state): - return value.strip() - def validate_python(self, value, state): - try: - p = People.by_username(value) - except InvalidRequestError: - return - except: - raise validators.Invalid(_("Error: Could not create - '%s'") % value, value, state) - - raise validators.Invalid(_("'%s' already exists.") % value, value, state) - -class NonFedoraEmail(validators.FancyValidator): - '''Make sure that an email address is not @fedoraproject.org''' - def _to_python(self, value, state): - return value.strip() - def validate_python(self, value, state): - if value.endswith('@fedoraproject.org'): - raise validators.Invalid(_("To prevent email loops, your email address cannot be @fedoraproject.org."), value, state) - -class ValidSSHKey(validators.FancyValidator): - ''' Make sure the ssh key uploaded is valid ''' - def _to_python(self, value, state): - - return value.file.read() - def validate_python(self, value, state): -# value = value.file.read() - print dir(value) - keylines = value.split('\n') - print "KEYLINES: %s" % keylines - for keyline in keylines: - if not keyline: - continue - keyline = keyline.strip() - m = re.match('^(rsa|dsa|ssh-rsa|ssh-dss) [ \t]*[^ \t]+.*$', keyline) - if not m: - raise validators.Invalid(_('Error - Not a valid ssh key: %s') % keyline, value, state) - -class ValidUsername(validators.FancyValidator): - '''Make sure that a username isn't blacklisted''' - def _to_python(self, value, state): - return value.strip() - def validate_python(self, value, state): - username_blacklist = config.get('username_blacklist') - if re.compile(username_blacklist).match(value): - raise validators.Invalid(_("'%s' is an illegal username.") % value, value, state) - -class UserSave(validators.Schema): - targetname = KnownUser - human_name = validators.All( - validators.String(not_empty=True, max=42), - validators.Regex(regex='^[^\n:<>]+$'), - ) - ssh_key = ValidSSHKey(max=5000) - email = validators.All( - validators.Email(not_empty=True, strip=True, max=128), - NonFedoraEmail(not_empty=True, strip=True, max=128), - ) - #fedoraPersonBugzillaMail = validators.Email(strip=True, max=128) - #fedoraPersonKeyId- Save this one for later :) - postal_address = validators.String(max=512) - -class UserCreate(validators.Schema): - username = validators.All( - UnknownUser, - ValidUsername(not_empty=True), - validators.String(max=32, min=3), - validators.Regex(regex='^[a-z][a-z0-9]+$'), - ) - human_name = validators.All( - validators.String(not_empty=True, max=42), - validators.Regex(regex='^[^\n:<>]+$'), - ) - email = validators.All( - validators.Email(not_empty=True, strip=True), - NonFedoraEmail(not_empty=True, strip=True), - ) - #fedoraPersonBugzillaMail = validators.Email(strip=True) - postal_address = validators.String(max=512) - -class UserSetPassword(validators.Schema): - currentpassword = validators.String - # TODO (after we're done with most testing): Add complexity requirements? - password = validators.String(min=8) - passwordcheck = validators.String - chained_validators = [validators.FieldsMatch('password', 'passwordcheck')] - -class UserResetPassword(validators.Schema): - # TODO (after we're done with most testing): Add complexity requirements? - password = validators.String(min=8) - passwordcheck = validators.String - chained_validators = [validators.FieldsMatch('password', 'passwordcheck')] - -class UserView(validators.Schema): - username = KnownUser - -class UserEdit(validators.Schema): - targetname = KnownUser - -def generate_password(password=None, length=16): - ''' Generate Password ''' - secret = {} # contains both hash and password - - if not password: - # Exclude 1,l and 0,O - chars = '23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ' - password = '' - for i in xrange(length): - password += random.choice(chars) - - secret['hash'] = crypt.crypt(password, "$1$%s" % generate_salt(8)) - secret['pass'] = password - - return secret - -def generate_salt(length=8): - chars = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' - salt = '' - for i in xrange(length): - salt += random.choice(chars) - return salt - -def generate_token(length=32): - chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' - token = '' - for i in xrange(length): - token += random.choice(chars) - return token - -class User(controllers.Controller): - - def __init__(self): - '''Create a User Controller. - ''' - - @identity.require(turbogears.identity.not_anonymous()) - def index(self): - '''Redirect to view - ''' - turbogears.redirect('/user/view/%s' % turbogears.identity.current.user_name) - - def jsonRequest(self): - return 'tg_format' in cherrypy.request.params and \ - cherrypy.request.params['tg_format'] == 'json' - - - @expose(template="fas.templates.error") - def error(self, tg_errors=None): - '''Show a friendly error message''' - if not tg_errors: - turbogears.redirect('/') - return dict(tg_errors=tg_errors) - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=UserView()) - @error_handler(error) - @expose(template="fas.templates.user.view", allow_json=True) - def view(self, username=None): - '''View a User. - ''' - if not username: - username = turbogears.identity.current.user_name - person = People.by_username(username) - if turbogears.identity.current.user_name == username: - personal = True - else: - personal = False - if isAdmin(person): - admin = True - # TODO: Should admins be able to see personal info? If so, enable this. - # Either way, let's enable this after the testing period. - #personal = True - else: - admin = False - cla = CLADone(person) - person.jsonProps = { - 'People': ('approved_memberships', 'unapproved_memberships') - } - return dict(person=person, cla=cla, personal=personal, admin=admin) - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=UserEdit()) - @error_handler(error) - @expose(template="fas.templates.user.edit") - def edit(self, targetname=None): - '''Edit a user - ''' - username = turbogears.identity.current.user_name - person = People.by_username(username) - - if targetname: - target = People.by_username(targetname) - else: - target = person - if not canEditUser(person, target): - turbogears.flash(_('You cannot edit %s') % target.username ) - turbogears.redirect('/user/view/%s', target.username) - return dict() - return dict(target=target) - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=UserSave()) - @error_handler(error) - @expose(template='fas.templates.user.edit') - def save(self, targetname, human_name, telephone, postal_address, email, ssh_key=None, ircnick=None, gpg_keyid=None, comments='', locale='en', timezone='UTC'): - username = turbogears.identity.current.user_name - target = targetname - person = People.by_username(username) - target = People.by_username(target) - emailflash = '' - - if not canEditUser(person, target): - turbogears.flash(_("You do not have permission to edit '%s'") % target.username) - turbogears.redirect('/user/view/%s', target.username) - return dict() - try: - target.human_name = human_name - if target.email != email: - token = generate_token() - target.unverified_email = email - target.emailtoken = token - message = turbomail.Message(config.get('accounts_email'), email, _('Email Change Requested for %s') % person.username) - # TODO: Make this email friendlier. - message.plain = _(''' -You have recently requested to change your Fedora Account System email -to this address. To complete the email change, you must confirm your -ownership of this email by visiting the following URL (you will need to -login with your Fedora account first): - -https://admin.fedoraproject.org/accounts/user/verifyemail/%s -''') % token - emailflash = _(' Before your new email takes effect, you must confirm it. You should receive an email with instructions shortly.') - turbomail.enqueue(message) - target.ircnick = ircnick - target.gpg_keyid = gpg_keyid - target.telephone = telephone - if ssh_key: - target.ssh_key = ssh_key - target.postal_address = postal_address - target.comments = comments - target.locale = locale - target.timezone = timezone - except TypeError: - turbogears.flash(_('Your account details could not be saved: %s') % e) - else: - turbogears.flash(_('Your account details have been saved.') + ' ' + emailflash) - turbogears.redirect("/user/view/%s" % target.username) - return dict(target=target) - - # TODO: This took about 55 seconds for me to load - might want to limit it to the right accounts (systems user, accounts group) - @identity.require(turbogears.identity.not_anonymous()) - @error_handler(error) - @expose(template="fas.templates.user.list", allow_json=True) - def list(self, search="a*"): - '''List users - ''' - re_search = re.sub(r'\*', r'%', search).lower() - if self.jsonRequest(): - people = [] - peoplesql = sqlalchemy.select([People.c.id, People.c.username, People.c.human_name, People.c.ssh_key, People.c.password]) - persons = peoplesql.execute() - for person in persons: - people.append({ - 'id' : person[0], - 'username' : person[1], - 'human_name' : person[2], - 'ssh_key' : person[3], - 'password' : person[4]}) - else: - people = People.query.filter(People.username.like(re_search)).order_by('username') - if people.count() < 0: - turbogears.flash(_("No users found matching '%s'") % search) - return dict(people=people, search=search) - - @identity.require(turbogears.identity.not_anonymous()) - @error_handler(error) - @expose(format='json') - def email_list(self, search='*'): - re_search = re.sub(r'\*', r'%', search).lower() - people = People.query.filter(People.username.like(re_search)).order_by('username') - emails = {} - for person in people: - emails[person.username] = person.email - return dict(emails=emails) - - @identity.require(turbogears.identity.not_anonymous()) - @error_handler(error) - @expose(template='fas.templates.user.verifyemail') - def verifyemail(self, token, cancel=False): - username = turbogears.identity.current.user_name - person = People.by_username(username) - if cancel: - person.emailtoken = '' - turbogears.flash(_('Your pending email change has been canceled. The email change token has been invalidated.')) - turbogears.redirect('/user/view/%s' % username) - return dict() - if not person.unverified_email: - turbogears.flash(_('You do not have any pending email changes.')) - turbogears.redirect('/user/view/%s' % username) - return dict() - if person.emailtoken and (person.emailtoken != token): - turbogears.flash(_('Invalid email change token.')) - turbogears.redirect('/user/view/%s' % username) - return dict() - return dict(person=person, token=token) - - @identity.require(turbogears.identity.not_anonymous()) - @error_handler(error) - @expose() - def setemail(self, token): - username = turbogears.identity.current.user_name - person = People.by_username(username) - if not (person.unverified_email and person.emailtoken): - turbogears.flash(_('You do not have any pending email changes.')) - turbogears.redirect('/user/view/%s' % username) - return dict() - if person.emailtoken != token: - turbogears.flash(_('Invalid email change token.')) - turbogears.redirect('/user/view/%s' % username) - return dict() - ''' Log this ''' - oldEmail = person.email - person.email = person.unverified_email - Log(author_id=person.id, description='Email changed from %s to %s' % (oldEmail, person.email)) - person.unverified_email = '' - session.flush() - turbogears.flash(_('You have successfully changed your email to \'%s\'') % person.email) - turbogears.redirect('/user/view/%s' % username) - return dict() - - @error_handler(error) - @expose(template='fas.templates.user.new') - def new(self): - if turbogears.identity.not_anonymous(): - turbogears.flash(_('No need to sign up, you have an account!')) - turbogears.redirect('/user/view/%s' % turbogears.identity.current.user_name) - return dict() - - @validate(validators=UserCreate()) - @error_handler(error) - @expose(template='fas.templates.new') - def create(self, username, human_name, email, telephone=None, postal_address=None): - # TODO: Ensure that e-mails are unique? - # Also, perhaps implement a timeout- delete account - # if the e-mail is not verified (i.e. the person changes - # their password) withing X days. - try: - person = People() - person.username = username - person.human_name = human_name - person.telephone = telephone - person.email = email - person.password = '*' - person.status = 'active' - session.flush() - newpass = generate_password() - message = turbomail.Message(config.get('accounts_email'), person.email, _('Welcome to the Fedora Project!')) - message.plain = _(''' -You have created a new Fedora account! -Your new password is: %s - -Please go to https://admin.fedoraproject.org/accounts/ to change it. - -Welcome to the Fedora Project. Now that you've signed up for an -account you're probably desperate to start contributing, and with that -in mind we hope this e-mail might guide you in the right direction to -make this process as easy as possible. - -Fedora is an exciting project with lots going on, and you can -contribute in a huge number of ways, using all sorts of different -skill sets. To find out about the different ways you can contribute to -Fedora, you can visit our join page which provides more information -about all the different roles we have available. - -http://fedoraproject.org/en/join-fedora - -If you already know how you want to contribute to Fedora, and have -found the group already working in the area you're interested in, then -there are a few more steps for you to get going. - -Foremost amongst these is to sign up for the team or project's mailing -list that you're interested in - and if you're interested in more than -one group's work, feel free to sign up for as many mailing lists as -you like! This is because mailing lists are where the majority of work -gets organised and tasks assigned, so to stay in the loop be sure to -keep up with the messages. - -Once this is done, it's probably wise to send a short introduction to -the list letting them know what experience you have and how you'd like -to help. From here, existing members of the team will help you to find -your feet as a Fedora contributor. - -And finally, from all of us here at the Fedora Project, we're looking -forward to working with you! -''') % newpass['pass'] - turbomail.enqueue(message) - person.password = newpass['hash'] - except IntegrityError: - turbogears.flash(_("An account has already been registered with that email address.")) - turbogears.redirect('/user/new') - return dict() - else: - turbogears.flash(_('Your password has been emailed to you. Please log in with it and change your password')) - turbogears.redirect('/user/changepass') - return dict() - - @identity.require(turbogears.identity.not_anonymous()) - @error_handler(error) - @expose(template="fas.templates.user.changepass") - def changepass(self): - return dict() - - @identity.require(turbogears.identity.not_anonymous()) - @validate(validators=UserSetPassword()) - @error_handler(error) - @expose(template="fas.templates.user.changepass") - def setpass(self, currentpassword, password, passwordcheck): - username = turbogears.identity.current.user_name - person = People.by_username(username) - -# current_encrypted = generate_password(currentpassword) -# print "PASS: %s %s" % (current_encrypted, person.password) - if not person.password == crypt.crypt(currentpassword, person.password): - turbogears.flash('Your current password did not match') - return dict() - # TODO: Enable this when we need to. - #if currentpassword == password: - # turbogears.flash('Your new password cannot be the same as your old one.') - # return dict() - newpass = generate_password(password) - try: - person.password = newpass['hash'] - Log(author_id=person.id, description='Password changed') - # TODO: Make this catch something specific. - except: - Log(author_id=person.id, description='Password change failed!') - turbogears.flash(_("Your password could not be changed.")) - return dict() - else: - turbogears.flash(_("Your password has been changed.")) - turbogears.redirect('/user/view/%s' % turbogears.identity.current.user_name) - return dict() - - @error_handler(error) - @expose(template="fas.templates.user.resetpass") - def resetpass(self): - if turbogears.identity.not_anonymous(): - turbogears.flash(_('You are already logged in!')) - turbogears.redirect('/user/view/%s' % turbogears.identity.current.user_name) - return dict() - - #TODO: Validate - @error_handler(error) - @expose(template="fas.templates.user.resetpass") - def sendtoken(self, username, email, encrypted=False): - import turbomail - # Logged in - if turbogears.identity.current.user_name: - turbogears.flash(_("You are already logged in.")) - turbogears.redirect('/user/view/%s', turbogears.identity.current.user_name) - return dict() - try: - person = People.by_username(username) - except InvalidRequestError: - turbogears.flash(_('Username email combo does not exist!')) - turbogears.redirect('/user/resetpass') - if email != person.email: - turbogears.flash(_("username + email combo unknown.")) - return dict() - token = generate_token() - message = turbomail.Message(config.get('accounts_email'), email, _('Fedora Project Password Reset')) - mail = _(''' -Somebody (hopefully you) has requested a password reset for your account! -To change your password (or to cancel the request), please visit -https://admin.fedoraproject.org/accounts/user/verifypass/%(user)s/%(token)s -''') % {'user': username, 'token': token} - if encrypted: - # TODO: Move this out to a single function (same as - # CLA one), think of how to make sure this doesn't get - # full of random keys (keep a clean Fedora keyring) - # TODO: MIME stuff? - keyid = re.sub('\s', '', person.gpg_keyid) - if not keyid: - turbogears.flash(_("This user does not have a GPG Key ID set, so an encrypted email cannot be sent.")) - return dict() - ret = subprocess.call([config.get('gpgexec'), '--keyserver', config.get('gpg_keyserver'), '--recv-keys', keyid]) - if ret != 0: - turbogears.flash(_("Your key could not be retrieved from subkeys.pgp.net")) - turbogears.redirect('/user/resetpass') - return dict() - else: - try: - # This may not be the neatest fix, but gpgme gave an error when mail was unicode. - plaintext = StringIO.StringIO(mail.encode('utf-8')) - ciphertext = StringIO.StringIO() - ctx = gpgme.Context() - ctx.armor = True - signer = ctx.get_key(re.sub('\s', '', config.get('gpg_fingerprint'))) - ctx.signers = [signer] - recipient = ctx.get_key(keyid) - def passphrase_cb(uid_hint, passphrase_info, prev_was_bad, fd): - os.write(fd, '%s\n' % config.get('gpg_passphrase')) - ctx.passphrase_cb = passphrase_cb - ctx.encrypt_sign([recipient], - gpgme.ENCRYPT_ALWAYS_TRUST, - plaintext, - ciphertext) - message.plain = ciphertext.getvalue() - except: - turbogears.flash(_('Your password reset email could not be encrypted.')) - return dict() - else: - message.plain = mail; - turbomail.enqueue(message) - person.passwordtoken = token - turbogears.flash(_('A password reset URL has been emailed to you.')) - turbogears.redirect('/login') - return dict() - - @error_handler(error) - @expose(template="fas.templates.user.newpass") - # TODO: Validator - def newpass(self, username, token, password=None, passwordcheck=None): - person = People.by_username(username) - if not person.passwordtoken: - turbogears.flash(_('You do not have any pending password changes.')) - turbogears.redirect('/login') - return dict() - if person.passwordtoken != token: - person.emailtoken = '' - turbogears.flash(_('Invalid password change token.')) - turbogears.redirect('/login') - return dict() - return dict(person=person, token=token) - - @error_handler(error) - @expose(template="fas.templates.user.verifypass") - # TODO: Validator - def verifypass(self, username, token, cancel=False): - person = People.by_username(username) - if not person.passwordtoken: - turbogears.flash(_('You do not have any pending password changes.')) - turbogears.redirect('/login') - return dict() - if person.passwordtoken != token: - turbogears.flash(_('Invalid password change token.')) - turbogears.redirect('/login') - return dict() - if cancel: - person.passwordtoken = '' - turbogears.flash(_('Your password reset has been canceled. The password change token has been invalidated.')) - turbogears.redirect('/login') - return dict() - return dict(person=person, token=token) - - @error_handler(error) - @expose() - @validate(validators=UserResetPassword()) - def setnewpass(self, username, token, password, passwordcheck): - person = People.by_username(username) - if not person.passwordtoken: - turbogears.flash(_('You do not have any pending password changes.')) - turbogears.redirect('/login') - return dict() - if person.passwordtoken != token: - person.emailtoken = '' - turbogears.flash(_('Invalid password change token.')) - turbogears.redirect('/login') - return dict() - ''' Log this ''' - newpass = generate_password(password) - person.password = newpass['hash'] - person.passwordtoken = '' - Log(author_id=person.id, description='Password changed') - session.flush() - turbogears.flash(_('You have successfully reset your password. You should now be able to login below.')) - turbogears.redirect('/login') - return dict() - - @identity.require(turbogears.identity.not_anonymous()) - @error_handler(error) - @expose(template="genshi-text:fas.templates.user.cert", format="text", content_type='text/plain; charset=utf-8') - def gencert(self): - username = turbogears.identity.current.user_name - person = People.by_username(username) - if CLADone(person): - person.certificate_serial = person.certificate_serial + 1 - - pkey = openssl_fas.createKeyPair(openssl_fas.TYPE_RSA, 1024); - - digest = config.get('openssl_digest') - expire = config.get('openssl_expire') - cafile = config.get('openssl_ca_file') - - cakey = openssl_fas.retrieve_key_from_file(cafile) - cacert = openssl_fas.retrieve_cert_from_file(cafile) - - req = openssl_fas.createCertRequest(pkey, digest=digest, - C=config.get('openssl_c'), - ST=config.get('openssl_st'), - L=config.get('openssl_l'), - O=config.get('openssl_o'), - OU=config.get('openssl_ou'), - CN=person.username, - emailAddress=person.email, - ) - - cert = openssl_fas.createCertificate(req, (cacert, cakey), person.certificate_serial, (0, expire), digest='md5') - certdump = crypto.dump_certificate(crypto.FILETYPE_PEM, cert) - keydump = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey) - return dict(cert=certdump, key=keydump) - else: - turbogears.flash(_('Before generating a certificate, you must first complete the CLA.')) - turbogears.redirect('/cla/') - - diff --git a/fas/build/scripts-2.5/fasClient b/fas/build/scripts-2.5/fasClient deleted file mode 100755 index 4d36a95..0000000 --- a/fas/build/scripts-2.5/fasClient +++ /dev/null @@ -1,577 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# Copyright © 2007-2008 Red Hat, Inc. All rights reserved. -# -# This copyrighted material is made available to anyone wishing to use, modify, -# copy, or redistribute it subject to the terms and conditions of the GNU -# General Public License v.2. This program is distributed in the hope that it -# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the -# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# See the GNU General Public License for more details. You should have -# received a copy of the GNU General Public License along with this program; -# if not, write to the Free Software Foundation, Inc., 51 Franklin Street, -# Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat trademarks that are -# incorporated in the source code or documentation are not subject to the GNU -# General Public License and may only be used or replicated with the express -# permission of Red Hat, Inc. -# -# Red Hat Author(s): Mike McGrath -# -# TODO: put tmp files in a 700 tmp dir - -import sys -import logging -import syslog -import os -import tempfile -import codecs -import datetime -import time - -from urllib2 import URLError -from fedora.tg.client import BaseClient, AuthError, ServerError -from optparse import OptionParser -from shutil import move, rmtree, copytree -from rhpl.translate import _ - -import ConfigParser - -parser = OptionParser() - -parser.add_option('-i', '--install', - dest = 'install', - default = False, - action = 'store_true', - help = _('Download and sync most recent content')) -parser.add_option('-c', '--config', - dest = 'CONFIG_FILE', - default = '/etc/fas.conf', - metavar = 'CONFIG_FILE', - help = _('Specify config file (default "%default")')) -parser.add_option('--nogroup', - dest = 'no_group', - default = False, - action = 'store_true', - help = _('Do not sync group information')) -parser.add_option('--nopasswd', - dest = 'no_passwd', - default = False, - action = 'store_true', - help = _('Do not sync passwd information')) -parser.add_option('--noshadow', - dest = 'no_shadow', - default = False, - action = 'store_true', - help = _('Do not sync shadow information')) -parser.add_option('--nohome', - dest = 'no_home_dirs', - default = False, - action = 'store_true', - help = _('Do not create home dirs')) -parser.add_option('--nossh', - dest = 'no_ssh_keys', - default = False, - action = 'store_true', - help = _('Do not create ssh keys')) -parser.add_option('-s', '--server', - dest = 'FAS_URL', - default = None, - metavar = 'FAS_URL', - help = _('Specify URL of fas server.')) -parser.add_option('-p', '--prefix', - dest = 'prefix', - default = None, - metavar = 'prefix', - help = _('Specify install prefix. Useful for testing')) -parser.add_option('-e', '--enable', - dest = 'enable', - default = False, - action = 'store_true', - help = _('Enable FAS synced shell accounts')) -parser.add_option('-d', '--disable', - dest = 'disable', - default = False, - action = 'store_true', - help = _('Disable FAS synced shell accounts')) -parser.add_option('-a', '--aliases', - dest = 'aliases', - default = False, - action = 'store_true', - help = _('Sync mail aliases')) - - -(opts, args) = parser.parse_args() - -log = logging.getLogger('fas') - -try: - config = ConfigParser.ConfigParser() - if os.path.exists(opts.CONFIG_FILE): - config.read(opts.CONFIG_FILE) - elif os.path.exists('fas.conf'): - config.read('fas.conf') - print >> sys.stderr, "Could not open %s, defaulting to ./fas.conf" % opts.CONFIG_FILE - else: - print >> sys.stderr, "Could not open %s." % opts.CONFIG_FILE - sys.exit(5) -except ConfigParser.MissingSectionHeaderError, e: - print >> sys.stderr, "Config file does not have proper formatting - %s" % e - sys.exit(6) - -FAS_URL = config.get('global', 'url').strip('"') -if opts.prefix: - prefix = opts.prefix -else: - prefix = config.get('global', 'prefix').strip('"') - -def _chown(arg, dir_name, files): - os.chown(dir_name, arg[0], arg[1]) - for file in files: - os.chown(os.path.join(dir_name, file), arg[0], arg[1]) - -class MakeShellAccounts(BaseClient): - temp = None - groups = None - people = None - memberships = None - emails = None - group_mapping = {} - valid_groups = {} - usernames = {} - - def mk_tempdir(self): - self.temp = tempfile.mkdtemp('-tmp', 'fas-', os.path.join(prefix + config.get('global', 'temp').strip('"'))) - - def rm_tempdir(self): - rmtree(self.temp) - - - def valid_groups(self): - ''' Create a dict of valid groups, including that of group_type ''' - if not self.groups: - self.group_list() - valid_groups = {'groups':[], 'restricted_groups':[], 'ssh_restricted_groups': []} - for restriction in valid_groups: - for group in config.get('host', restriction).strip('"').split(','): - if group == '': - continue - if group == '@all': - for grp in self.groups: - if not grp['name'].startswith('cla'): - valid_groups[restriction].append(grp['name']) - elif group.startswith('@'): - for grp in self.groups: - if grp['group_type'] == group[1:]: - valid_groups[restriction].append(grp['name']) - else: - valid_groups[restriction].append(group) - self.valid_groups = valid_groups - - def valid_group(self, name, restriction=None): - ''' Determine if group is valid on the system ''' - if restriction: - return name in self.valid_groups[restriction] - else: - for restrict_key in self.valid_groups: - if name in self.valid_groups[restrict_key]: - return True - return False - - def valid_user(self, username): - ''' Is the user valid on this system ''' - if not self.valid_groups: - self.valid_groups() - if not self.group_mapping: - self.get_group_mapping() - try: - for restriction in self.valid_groups: - for group in self.valid_groups[restriction]: - if username in self.group_mapping[group]: - return True - except KeyError: - return False - return False - - def ssh_key(self, person): - ''' determine what ssh key a user should have ''' - for group in self.valid_groups['groups']: - try: - if person['username'] in self.group_mapping[group]: - return person['ssh_key'] - except KeyError: - print >> sys.stderr, '%s could not be found in fas but was in your config under "groups"!' % group - continue - for group in self.valid_groups['restricted_groups']: - try: - if person['username'] in self.group_mapping[group]: - return person['ssh_key'] - except KeyError: - print >> sys.stderr, '%s could not be found in fas but was in your config under "restricted_groups"!' % group - continue - for group in self.valid_groups['ssh_restricted_groups']: - try: - if person['username'] in self.group_mapping[group]: - command = config.get('users', 'ssh_restricted_app').strip('"') - options = config.get('users', 'ssh_key_options').strip('"') - key = 'command="%s",%s %s' % (command, options, person['ssh_key']) - return key - except TypeError: - print >> sys.stderr, '%s could not be found in fas but was in your config under "ssh_restricted_groups"!' % group - continue - return 'INVALID\n' - - def shell(self, username): - ''' Determine what shell username should have ''' - for group in self.valid_groups['groups']: - try: - if username in self.group_mapping[group]: - return config.get('users', 'shell').strip('"') - except KeyError: - print >> sys.stderr, '%s could not be found in fas but was in your config under "groups"!' % group - continue - for group in self.valid_groups['restricted_groups']: - try: - if username in self.group_mapping[group]: - return config.get('users', 'restricted_shell').strip('"') - except KeyError: - print >> sys.stderr, '%s could not be found in fas but was in your config under "restricted_groups"!' % group - continue - for group in self.valid_groups['ssh_restricted_groups']: - try: - if username in self.group_mapping[group]: - return config.get('users', 'ssh_restricted_shell').strip('"') - except KeyError: - print >> sys.stderr, '%s could not be found in fas but was in your config under "ssh_restricted_groups"!' % group - continue - - print >> sys.stderr, 'Could not determine shell for %s. Defaulting to /sbin/nologin' % username - return '/sbin/nologin' - - def install_aliases_txt(self): - move(self.temp + '/aliases', prefix + '/etc/aliases') - - def passwd_text(self, people=None): - i = 0 - passwd_file = codecs.open(self.temp + '/passwd.txt', mode='w', encoding='utf-8') - shadow_file = codecs.open(self.temp + '/shadow.txt', mode='w', encoding='utf-8') - os.chmod(self.temp + '/shadow.txt', 00400) - if not self.people: - self.people_list() - for person in self.people: - username = person['username'] - if self.valid_user(username): - uid = person['id'] - human_name = person['human_name'] - password = person['password'] - home_dir = "%s/%s" % (config.get('users', 'home').strip('"'), username) - shell = self.shell(username) - passwd_file.write("=%s %s:x:%i:%i:%s:%s:%s\n" % (uid, username, uid, uid, human_name, home_dir, shell)) - passwd_file.write("0%i %s:x:%i:%i:%s:%s:%s\n" % (i, username, uid, uid, human_name, home_dir, shell)) - passwd_file.write(".%s %s:x:%i:%i:%s:%s:%s\n" % (username, username, uid, uid, human_name, home_dir, shell)) - shadow_file.write("=%i %s:%s:99999:0:99999:7:::\n" % (uid, username, password)) - shadow_file.write("0%i %s:%s:99999:0:99999:7:::\n" % (i, username, password)) - shadow_file.write(".%s %s:%s:99999:0:99999:7:::\n" % (username, username, password)) - i = i + 1 - passwd_file.close() - shadow_file.close() - - def valid_user_group(self, person_id): - ''' Determine if person is valid on this machine as defined in the - config file. I worry that this is going to be horribly inefficient - with large numbers of users and groups.''' - for member in self.memberships: - for group in self.memberships[member]: - if group['person_id'] == person_id: - return True - return False - - def get_usernames(self): - usernames = {} - if not self.people: - self.people_list() - for person in self.people: - uid = person['id'] - if self.valid_user_group(uid): - username = person['username'] - usernames[uid] = username - self.usernames = usernames - - def get_group_mapping(self): - if not self.usernames: - self.get_usernames() - for group in self.groups: - gid = group['id'] - name = group['name'] - try: - ''' Shoot me now I know this isn't right ''' - members = [] - for member in self.memberships[name]: - members.append(self.usernames[member['person_id']]) - memberships = ','.join(members) - self.group_mapping[name] = members - except KeyError: - ''' No users exist in the group ''' - pass - - - def groups_text(self, groups=None, people=None): - i = 0 - file = open(self.temp + '/group.txt', 'w') - if not self.groups: - self.group_list() - if not self.people: - self.people_list() - if not self.usernames: - self.get_usernames() - if not self.group_mapping: - self.get_group_mapping() - ''' First create all of our users/groups combo ''' - for person in self.people: - uid = person['id'] - try: - if self.valid_user(self.usernames[uid]): - username = person['username'] - file.write("=%i %s:x:%i:\n" % (uid, username, uid)) - file.write("0%i %s:x:%i:\n" % (i, username, uid)) - file.write(".%s %s:x:%i:\n" % (username, username, uid)) - i = i + 1 - except KeyError: - continue - - for group in self.groups: - gid = group['id'] - name = group['name'] - try: - ''' Shoot me now I know this isn't right ''' - members = [] - for member in self.memberships[name]: - members.append(self.usernames[member['person_id']]) - memberships = ','.join(members) - self.group_mapping[name] = members - except KeyError: - ''' No users exist in the group ''' - pass - file.write("=%i %s:x:%i:%s\n" % (gid, name, gid, memberships)) - file.write("0%i %s:x:%i:%s\n" % (i, name, gid, memberships)) - file.write(".%s %s:x:%i:%s\n" % (name, name, gid, memberships)) - i = i + 1 - file.close() - - def group_list(self, search='*'): - params = {'search' : search} - request = self.send_request('group/list', auth=True, input=params) - self.groups = request['groups'] - memberships = {} - for group in self.groups: - memberships[group['name']] = [] - try: - for member in request['memberships'][u'%s' % group['id']]: - memberships[group['name']].append(member) - except KeyError: - pass - self.memberships = memberships - self.valid_groups() - return self.groups - - def people_list(self, search='*'): - params = {'search' : search} - self.people = self.send_request('user/list', auth=True, input=params)['people'] - - def email_list(self, search='*'): - params = {'search' : search} - self.emails = self.send_request('user/email_list', auth=True, input=params)['emails'] - return self.emails - - def make_group_db(self): - self.groups_text() - os.system('makedb -o %s/group.db %s/group.txt' % (self.temp, self.temp)) - - def make_passwd_db(self): - self.passwd_text() - os.system('makedb -o %s/passwd.db %s/passwd.txt' % (self.temp, self.temp)) - os.system('makedb -o %s/shadow.db %s/shadow.txt' % (self.temp, self.temp)) - os.chmod(self.temp + '/shadow.db', 00400) - - def install_passwd_db(self): - try: - move(self.temp + '/passwd.db', os.path.join(prefix + '/var/db/passwd.db')) - except IOError, e: - print "ERROR: Could not write passwd db - %s" % e - - def install_shadow_db(self): - try: - move(self.temp + '/shadow.db', os.path.join(prefix + '/var/db/shadow.db')) - except IOError, e: - print "ERROR: Could not write shadow db - %s" % e - - def install_group_db(self): - try: - move(self.temp + '/group.db', os.path.join(prefix + '/var/db/group.db')) - except IOError, e: - print "ERROR: Could not write group db - %s" % e - - def create_homedirs(self): - ''' Create homedirs and home base dir if they do not exist ''' - home_base = os.path.join(prefix + config.get('users', 'home').strip('"')) - if not os.path.exists(home_base): - os.makedirs(home_base, mode=0755) - for person in self.people: - home_dir = os.path.join(home_base, person['username']) - if not os.path.exists(home_dir) and self.valid_user(person['username']): - syslog.syslog('Creating homedir for %s' % person['username']) - copytree('/etc/skel/', home_dir) - os.path.walk(home_dir, _chown, [person['id'], person['id']]) - - def remove_stale_homedirs(self): - ''' Remove homedirs of users that no longer have access ''' - home_base = os.path.join(prefix + config.get('users', 'home').strip('"')) - try: - home_backup_dir = config.get('users', 'home_backup_dir').strip('"') - except ConfigParser.NoOptionError: - home_backup_dir = '/var/tmp/' - users = os.listdir(home_base) - for user in users: - if not self.valid_user(user): - if not os.path.exists(home_backup_dir): - os.makedirs(home_backup_dir) - syslog.syslog('Backed up %s to %s' % (user, home_backup_dir)) - target = '%s-%s' % (user, time.mktime(datetime.datetime.now().timetuple())) - move(os.path.join(home_base, user), os.path.join(prefix + home_backup_dir, target)) - - def create_ssh_keys(self): - ''' Create ssh keys ''' - home_base = prefix + config.get('users', 'home').strip('"') - for person in self.people: - username = person['username'] - if self.valid_user(username): - ssh_dir = os.path.join(home_base, username, '.ssh') - if person['ssh_key']: - key = self.ssh_key(person) - if not os.path.exists(ssh_dir): - os.makedirs(ssh_dir, mode=0700) - f = codecs.open(os.path.join(ssh_dir, 'authorized_keys'), mode='w', encoding='utf-8') - f.write(key + '\n') - f.close() - os.chmod(os.path.join(ssh_dir, 'authorized_keys'), 0600) - os.path.walk(ssh_dir, _chown, [person['id'], person['id']]) - - def make_aliases_txt(self): - ''' update your mail aliases file ''' - if not self.groups: - groups = self.group_list() - if not self.usernames: - self.get_usernames() - - self.emails = self.email_list() - email_file = codecs.open(self.temp + '/aliases', mode='w', encoding='utf-8') - email_template = codecs.open(config.get('host', 'aliases_template').strip('"')) - email_file.write("# Generated by fasClient\n") - for line in email_template.readlines(): - email_file.write(line) - sorted = self.emails.keys() - sorted.sort() - for person in sorted: - email_file.write("%s: %s\n" % (person, self.emails[person])) - for group in self.groups: - name = group['name'] - members = {} - members['member'] = [] - for membership in self.memberships[name]: - role_type = membership['role_type'] - person = self.usernames[membership['person_id']] - if role_type == 'user': - ''' Legacy support ''' - members['member'].append(person) - continue - members['member'].append(person) - try: - members[role_type].append(person) - except KeyError: - members[role_type] = [person] - for role in members: - email_file.write("%s-%ss: %s\n" % (name, role, ','.join(members[role]))) - email_file.close() - -def enable(): - temp = tempfile.mkdtemp('-tmp', 'fas-', config.get('global', 'temp').strip('"')) - - old = open('/etc/sysconfig/authconfig', 'r') - new = open(temp + '/authconfig', 'w') - for line in old: - if line.startswith("USEDB"): - new.write("USEDB=yes\n") - else: - new.write(line) - new.close() - old.close() - try: - move(temp + '/authconfig', '/etc/sysconfig/authconfig') - except IOError, e: - print "ERROR: Could not write /etc/sysconfig/authconfig - %s" % e - sys.exit(5) - os.system('/usr/sbin/authconfig --updateall') - rmtree(temp) - -def disable(): - temp = tempfile.mkdtemp('-tmp', 'fas-', config.get('global', 'temp').strip('"')) - old = open('/etc/sysconfig/authconfig', 'r') - new = open(temp + '/authconfig', 'w') - for line in old: - if line.startswith("USEDB"): - new.write("USEDB=no\n") - else: - new.write(line) - old.close() - new.close() - try: - move(temp + '/authconfig', '/etc/sysconfig/authconfig') - except IOError, e: - print "ERROR: Could not write /etc/sysconfig/authconfig - %s" % e - sys.exit(5) - os.system('/usr/sbin/authconfig --updateall') - rmtree(temp) - - -if __name__ == '__main__': - if opts.enable: - enable() - if opts.disable: - disable() - - if opts.install: - try: - fas = MakeShellAccounts(FAS_URL, config.get('global', 'login').strip('"'), config.get('global', 'password').strip('"'), False) - except AuthError, e: - print >> sys.stderr, e - sys.exit(1) - except URLError, e: - print >> sys.stderr, 'Could not connect to %s - %s' % (FAS_URL, e.reason[1]) - sys.exit(9) - fas.mk_tempdir() - fas.make_group_db() - fas.make_passwd_db() - if not opts.no_group: - fas.install_group_db() - if not opts.no_passwd: - fas.install_passwd_db() - if not opts.no_shadow: - fas.install_shadow_db() - if not opts.no_home_dirs: - fas.create_homedirs() - fas.remove_stale_homedirs() - if not opts.no_ssh_keys: - fas.create_ssh_keys() - fas.rm_tempdir() - if opts.aliases: - try: - fas = MakeShellAccounts(FAS_URL, config.get('global', 'login').strip('"'), config.get('global', 'password').strip('"'), False) - except AuthError, e: - print >> sys.stderr, e - sys.exit(1) - fas.mk_tempdir() - fas.make_aliases_txt() - fas.install_aliases_txt() - - if not (opts.install or opts.enable or opts.disable or opts.aliases): - parser.print_help() diff --git a/fas/build/scripts-2.5/restricted-shell b/fas/build/scripts-2.5/restricted-shell deleted file mode 100755 index 6f4fd1c..0000000 --- a/fas/build/scripts-2.5/restricted-shell +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -tt -# This script allows people to run the commands listed in 'commands' and -# 'commands' only. Be careful though, by adding /bin/bash you've effectively -# disabled this script. Also, via some voodoo you can restrict what flags -# get passed or even completely alter what would normally happen if a command -# were envoked (see scp section below) - -# TODO: better documentation needed for how this file works - - -import sys, os - -commands = { - "git-receive-pack": "/usr/bin/git-receive-pack", - "git-upload-pack": "/usr/bin/git-upload-pack", - "bzr": "/usr/bin/run-bzr", - "hg": "/usr/bin/run-hg", - "mtn": "/usr/bin/run-mtn", - "svnserve": "/usr/bin/run-svnserve", - "scp": "/usr/bin/scp", -} - -if __name__ == '__main__': - orig_cmd = os.environ.get('SSH_ORIGINAL_COMMAND') - if not orig_cmd: - print "Need a command" - sys.exit(1) - allargs = orig_cmd.split() - try: - basecmd = os.path.basename(allargs[0]) - cmd = commands[basecmd] - except: - sys.stderr.write("Invalid command %s\n" % orig_cmd) - sys.exit(2) - - if basecmd in ('git-receive-pack', 'git-upload-pack'): - # git repositories need to be parsed specially - thearg = ' '.join(allargs[1:]) - if thearg[0] == "'" and thearg[-1] == "'": - thearg = thearg.replace("'","") - thearg = thearg.replace("\\'", "") - if thearg[:len('/git/')] != '/git/' or not os.path.isdir(thearg): - print "Invalid repository %s" % thearg - sys.exit(3) - allargs = [thearg] - elif basecmd in ('scp'): - thearg = ' '.join(allargs[1:]) - firstLetter = allargs[2][0] - secondLetter = allargs[2][1] - uploadTarget = "/srv/web/releases/%s/%s/%s/" % (firstLetter, secondLetter, allargs[2]) - if thearg.find('/') != -1: - print "scp yourfile-1.2.tar.gz scm.fedorahosted.org:$YOURPROJECT # No trailing /" - sys.exit(4) - elif not os.path.isdir(uploadTarget): - print "http://fedorahosted.org/releases/%s/%s/%s does not exist!" % (firstLetter, secondLetter, allargs[2]) - sys.exit(5) - else: - newargs = [] - newargs.append(allargs[0]) - newargs.append(allargs[1]) - newargs.append(uploadTarget) - os.execv(cmd, [cmd] + newargs[1:]) - sys.exit(1) - else: - allargs = allargs[1:] - os.execv(cmd, [cmd] + allargs) - sys.exit(1)