these shouldn't be version managed

This commit is contained in:
Mike McGrath 2008-03-15 18:01:58 -05:00
parent 904ded2969
commit c395bc1aaa
56 changed files with 0 additions and 4779 deletions

View file

@ -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

View file

@ -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

View file

@ -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()

View file

@ -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())

View file

@ -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,)'

View file

@ -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", "/"))

View file

@ -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

View file

@ -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)

View file

@ -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', '<p>We could not find that help item</p>'],
'user_ircnick' : ['IRC Nick (Optional)', '<p>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</p>'],
'user_email' : ['Email (Required)', '<p>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</p>'],
'user_human_name' : ['Full Name (Required)', '<p>Your Human Name or "real life" name</p>'],
'user_gpg_keyid' : ['GPG Key', '<p>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.</p>'],
'user_telephone' : ['Telephone', '<p>Required in order to complete the <a href="http://fedoraproject.org/wiki/Legal/Licenses/CLA">CLA</a>. Sometimes during a time of emergency someone from the Fedora Project may need to contact you. For more information see our <a href="http://fedoraproject.org/wiki/Legal/PrivacyPolicy">Privacy Policy</a></p>'],
'user_postal_address': ['Postal Address', '<p>Required in order to complete the <a href="http://fedoraproject.org/wiki/Legal/Licenses/CLA">CLA</a>. This should be a mailing address where you can be contacted. See our <a href="http://fedoraproject.org/wiki/Legal/PrivacyPolicy">Privacy Policy</a> about any concerns.</p>'],
'user_timezone': ['Timezone (Optional)', '<p>Please specify the time zone you are in.</p>'],
'user_comments': ['Comments (Optional)', '<p>Misc comments about yourself.</p>'],
'user_account_status': ['Account Status', '<p>Shows account status, possible values include<ul><li>Valid</li><li>Disabled</li><li>Expired</li></ul></p>'],
'user_cla' : ['CLA', '<p>In order to become a full Fedora contributor you must complete the <a href="http://fedoraproject.org/wiki/Legal/Licenses/CLA">Contributor License Agreement</a>. 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.</p>'],
'user_ssh_key' : ['Public SSH Key', '<p>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</p>'],
'user_locale': ['Locale', '<p>For non-english speaking peoples this allows individuals to select which locale they are in.</p>'],
'group_apply': ['Apply', '<p>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 <a href="../about">about page</a>.</p>'],
'group_remove': ['Remove', '''<p>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.</p>'''],
'group_upgrade': ['Upgrade', '''<p>Upgrade a persons status in this group.<ul><li>from user -> to sponsor</li><li>From sponsor -> administrator</li><li>administrators cannot be upgraded beyond administrator</li></ul></p>'''],
'group_downgrade': ['Downgrade', '''<p>Downgrade a persons status in the group.<ul><li>from administrator -> to sponsor</li><li>From sponsor -> user</li><li>users cannot be downgraded below user, you may want to remove them</li></ul></p>'''],
'group_approve': ['Approve', '''<p>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.</p>'''],
'group_sponsor': ['Sponsor', '''<p>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.</p>'''],
'group_user_add': ['Add User', '''<p>Manually add a user to a group. Place their username in this field and click 'Add'</p>'''],
'group_name': ['Group Name', '''<p>The name of the group you'd like to create. It should be alphanumeric though '-'s are allowed</p>'''],
'group_display_name': ['Display Name', '''<p>More human readable name of the group</p>'''],
'group_owner': ['Group Owner', '''<p>The name of the owner who will run this group</p>'''],
'group_type': ['Group Type', '''<p>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.</p>'''],
'group_needs_sponsor': ['Needs Sponsor', '''<p>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</p>'''],
'group_self_removal': ['Self Removal', '''<p>Should users be able to remove themselves from this group without sponsor / admin intervention? (recommended yes)</p>'''],
'group_prerequisite': ['Must Belong To', '''<p>Before a user can join this group, they must belong to the group listed in this box. <b>This value cannot be removed without administrative intervention, only changed</b>. Recommended values are for the 'cla_done' group.</p>'''],
'group_join_message': ['Join Message', '''<p>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</p>'''],
'gencert': ['Client Side Cert', '''<p>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</p>'''],
}
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', '<p>We could not find that help item</p>'])
return dict(help=helpItem)

View file

@ -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)

View file

@ -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 <tkuratom@redhat.com>
# Ricky Zhou <ricky@fedoraproject.org>
#
'''
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')))

View file

@ -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)

View file

@ -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

View file

@ -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'

View file

@ -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 <tkuratom@redhat.com>
#
'''
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)

View file

@ -1,17 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="master.html" />
<head>
<title>${_('About FAS')}</title>
</head>
<body>
<h2>${_('FAS - The Open Account System')}</h2>
<p>${_('''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.''')}</p>
<h2>${_('Etiquette')}</h2>
<p>${_("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.")}</p>
<h2>${_('Users, Sponsors, Administrators')}</h2>
<p>${_('''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.''')}</p>
</body>
</html>

View file

@ -1,82 +0,0 @@
<div id="cla" xml:lang="en">
<h3>The Fedora Project
Individual Contributor License Agreement (CLA)
</h3>
<a href="http://fedoraproject.org/wiki/Legal/Licenses/CLA">http://fedoraproject.org/wiki/Legal/Licenses/CLA</a>
<p>
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.
</p>
<p>
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
</p>
<address>
Fedora Project, c/o Red Hat, Inc.,<br />
Attn: Legal Affairs<br />
1801 Varsity Drive<br />
Raleigh, North Carolina, 27606 U.S.A.
</address>
<p>
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.
</p>
<p>
Full name: ${person.human_name}<br />
E-Mail: ${person.email}<br />
Address: ${person.postal_address}<br />
Telephone: ${person.telephone}
<!-- Facsimile: ${person.facsimile} -->
</p>
<p>
You and the Project hereby accept and agree to the following terms and conditions:
</p>
<ol>
<li>
Contributors and Contributions.
<ol>
<li>
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.
</li>
<li>
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.
</li>
<li>
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."
</li>
<li>
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.
</li>
</ol>
</li>
<li>
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:
<ol>
<li>
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,
</li>
<li>
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.
</li>
</ol>
</li>
<li>
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.
</li>
<li>
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.
</li>
<li>
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.
</li>
<li>
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.
</li>
<li>
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]".
</li>
<li>
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.
</li>
<li>
The Project is under no obligations to accept and include every contribution.
</li>
</ol>
</div>

View file

@ -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.

View file

@ -1,26 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Fedora Accounts System')}</title>
</head>
<body>
<h2>${_('Fedora Contributor License Agreement')}</h2>
${Markup(_('&lt;a href="%(url)s"&gt;Text Version&lt;/a&gt;') % {'url': tg.url('/cla/text')})}
<xi:include href="cla.html" />
${Markup(_('&lt;a href="%(url)s"&gt;Text Version&lt;/a&gt;') % {'url': tg.url('/cla/text')})}
<p py:if="cla">
${Markup(_('You have already sucessfully complete the CLA.') % {'url': tg.url('/cla/text')})}
</p>
<py:if test="not cla">
<form action="${tg.url('/cla/send')}" method="post">
<div>
<input type="submit" id="agree" name="agree" value="${_('I agree')}" />
<input type="submit" value="${_('I do not agree')}" />
</div>
</form>
</py:if>
</body>
</html>

View file

@ -1,25 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="master.html" />
<head>
<title>${_('Fedora Accounts System')}</title>
<style type="text/css">
#content ul
{
list-style: square;
margin: 1ex 3ex;
}
</style>
</head>
<body>
<h2>${_('Error!')}</h2>
<p>${_('The following error(s) have occured with your request:')}</p>
<ul>
<li py:for="field, error in tg_errors.items()">
${field}: ${str(error)}
</li>
</ul>
</body>
</html>

View file

@ -1,3 +0,0 @@
#for person in sorted(people)
${person.username},${person.email},${person.human_name},user,0
#end

View file

@ -1,55 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Edit Group')}</title>
</head>
<body>
<h2>${_('Edit Group: %s') % group.name}</h2>
<form action="${tg.url('/group/save/%s' % group.name)}" method="post">
<div class="field">
<label for="display_name">${_('Display Name:')}</label>
<input type="text" id="display_name" name="display_name" value="${group.display_name}" />
<script type="text/javascript">var group_name = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_name')}'});</script>
</div>
<div class="field">
<label for="group_type">${_('Group Type:')}</label>
<input type="text" id="group_type" name="group_type" value="${group.group_type}" />
<script type="text/javascript">var group_type = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_type')}'});</script>
</div>
<div class="field">
<label for="owner">${_('Group Owner:')}</label>
<input type="text" id="owner" name="owner" value="${group.owner.username}" />
<script type="text/javascript">var group_owner = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_owner')}'});</script>
</div>
<div class="field">
<label for="needs_sponsor">${_('Needs Sponsor:')}</label>
<input py:if="group.needs_sponsor" type="checkbox" id="needs_sponsor" name="needs_sponsor" value="1" checked="checked" />
<input py:if="not group.needs_sponsor" type="checkbox" id="needs_sponsor" name="needs_sponsor" value="1" />
<script type="text/javascript">var group_needs_sponsor = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_needs_sponsor')}'});</script>
</div>
<div class="field">
<label for="user_can_remove">${_('Self Removal:')}</label>
<input py:if="group.user_can_remove" type="checkbox" id="user_can_remove" name="user_can_remove" value="1" checked="checked" />
<input py:if="not group.user_can_remove" type="checkbox" id="user_can_remove" name="user_can_remove" value="1" />
&nbsp;<script type="text/javascript">var group_self_removal = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_self_removal')}'});</script>
</div>
<div class="field">
<label for="prerequisite">${_('Group Prerequisite:')}</label>
<input py:if="group.prerequisite" type="text" id="prerequisite" name="prerequisite" value="${group.prerequisite.name}" />
<input py:if="not group.prerequisite" type="text" id="prerequisite" name="prerequisite" />
&nbsp;<script type="text/javascript">var group_prerequisite = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_prerequisite')}'});</script>
</div>
<div class="field">
<label for="joinmsg">${_('Group Join Message:')}</label>
<textarea id="joinmsg" name="joinmsg">${group.joinmsg}</textarea>
<script type="text/javascript">var group_join_message = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_join_message')}'});</script>
</div>
<div class="field">
<input type="submit" value="${_('Save!')}" />
</div>
</form>
</body>
</html>

View file

@ -1,43 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Invite a new community member!')}</title>
</head>
<body>
<h2>${_('Invite a new community member!')}</h2>
<form method="post" action="${tg.url('/group/sendinvite/%s') % group.name}">
<div>
<!--TODO: Make the email translatable -->
${_('To email:')} <input type="text" value="" name="target" /><br />
${_('From:')} ${person.email}<br />
${_('Subject:')} Invitation to join the Fedora Team!<br />
${_('Message:')}
<div class="message">
<p>
${person.human_name} &lt;<a href="mailto: ${person.email}">${person.email}</a>&gt; 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.
</p>
<p>
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.
</p>
<p>
Fedora and FOSS are changing the world -- come be a part of it!
</p>
</div>
<input type="submit" value="${_('Send!')}" />
</div>
</form>
</body>
</html>

View file

@ -1,54 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Groups List')}</title>
</head>
<body>
<?python
from fas.model import Groups, People
person = People.by_username(tg.identity.user.username)
?>
<span py:if="Groups.by_name('accounts') in person.approved_memberships">
<h2>Create New Group</h2>
<a href="${tg.url('/group/new')}">Create Group</a>
</span>
<h2>${_('List (%s)') % search}</h2>
<h3>${_('Search Groups')}</h3>
<form method="get" action="${tg.url('/group/list')}">
<p>${_('"*" is a wildcard (Ex: "cvs*")')}</p>
<div>
<input type="text" value="${search}" name="search" size="15 "/>
<input type="submit" value="${_('Search')}" />
</div>
</form>
<h3>${_('Results')}</h3>
<ul class="letters">
<li py:for="letter in 'abcdefghijklmnopqrstuvwxyz'.upper()"><a href="${tg.url('/group/list/%s*' % letter)}">${letter}</a></li>
<li><a href="${tg.url('/group/list/*')}">${_('All')}</a></li>
</ul>
<table py:if="groups">
<thead>
<tr><th>${_('Group')}</th><th>${_('Description')}</th><th>${_('Status')}</th></tr>
</thead>
<tbody>
<tr py:for="group in groups">
<td><a href="${tg.url('/group/view/%s' % group.name)}">${group.name}</a></td>
<td>${ group.display_name }</td>
<td>
<a py:if="group in person.memberships" href="${tg.url('/group/view/%s' % group.name)}">
<span class="approved" py:if="group in person.approved_memberships">${_('Approved')}</span>
<span class="unapproved" py:if="group in person.unapproved_memberships">${_('Unapproved')}</span>
</a>
<a py:if="group not in person.memberships" href="${tg.url('/group/apply/%s/%s' % (group.name, person.username))}"><span>${_('Apply')}</span></a>
<script py:if="group not in person.memberships" type="text/javascript">var hb1 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_apply')}'});</script>
</td>
</tr>
</tbody>
</table>
</body>
</html>

View file

@ -1,57 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Create a new FAS Group')}</title>
</head>
<body>
<h2>${_('Create a new FAS Group')}</h2>
<form action="${tg.url('/group/create')}" method="post">
<div class="field">
<label for="name">${_('Group Name:')}</label>
<input type="text" id="name" name="name" />
<script type="text/javascript">var group_name = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_name')}'});</script>
</div>
<div class="field">
<label for="display_name">${_('Display Name:')}</label>
<input type="text" id="display_name" name="display_name" />
<script type="text/javascript">var group_display_name = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_display_name')}'});</script>
</div>
<div class="field">
<label for="owner">${_('Group Owner:')}</label>
<input type="text" id="owner" name="owner" />
<script type="text/javascript">var group_owner = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_owner')}'});</script>
</div>
<div class="field">
<label for="group_type">${_('Group Type:')}</label>
<input type="text" id="group_type" name="group_type" value="tracking" />
<script type="text/javascript">var group_type = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_type')}'});</script>
</div>
<div class="field">
<label for="needs_sponsor">${_('Needs Sponsor:')}</label>
<input type="checkbox" id="needs_sponsor" name="needs_sponsor" value="1" checked="checked" />&nbsp;
<script type="text/javascript">var group_needs_sponsor = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_needs_sponsor')}'});</script>
</div>
<div class="field">
<label for="user_can_remove">${_('Self Removal:')}</label>
<input type="checkbox" id="user_can_remove" name="user_can_remove" value="1" checked="checked" />&nbsp;
<script type="text/javascript">var group_self_removal = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_self_removal')}'});</script>
</div>
<div class="field">
<label for="prerequisite">${_('Must Belong To:')}</label>
<input type="text" id="prerequisite" name="prerequisite" value="cla_done" />
<script type="text/javascript">var group_prerequisite = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_prerequisite')}'});</script>
</div>
<div class="field">
<label for="joinmsg">${_('Join Message:')}</label>
<textarea id="joinmsg" name="joinmsg"></textarea>
<script type="text/javascript">var group_join_message = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_join_message')}'});</script>
</div>
<div class="field">
<input type="submit" value="${_('Create!')}" />
</div>
</form>
</body>
</html>

View file

@ -1,123 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('View Group')}</title>
</head>
<body>
<?python
from fas import auth
from fas.model import People
import pytz
person = People.by_username(tg.identity.user.username)
timezone = pytz.timezone(person.timezone)
can_admin = auth.canAdminGroup(person, group)
can_sponsor = auth.canSponsorGroup(person, group)
?>
<h2>${group.display_name} (${group.name})</h2>
<h3>
${_('My Status:')}
<span py:if="group in person.memberships and group in person.approved_memberships" class="approved">${_('Approved')}</span>
<span py:if="group in person.memberships and not group in person.approved_memberships" class="unapproved">${_('Unapproved')}</span>
<span py:if="not group in person.memberships">${_('Not a Member')}</span>
</h3>
<form py:if="not group in person.memberships" action="${tg.url('/group/apply/%s/%s' % (group.name, person.username))}">
<div>
<!--<input type="text" name="requestField" value="${_('Please let me join...')}" />-->
<input type="submit" value="${('Apply!')}" />
</div>
</form>
<a py:if="group in person.memberships" href="${tg.url('/group/remove/%s/%s' % (group.name, person.username))}">${_('Remove me')}</a>
<script py:if="group in person.memberships" type="text/javascript">var hb7 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_remove')}'});</script>
<h3>Group Details <a py:if="can_admin" href="${tg.url('/group/edit/%s' % group.name)}">${_('(edit)')}</a></h3>
<div class="userbox">
<dl>
<dt>${_('Name:')}</dt><dd>${group.name}&nbsp;</dd>
<dt>${_('Description:')}</dt><dd>${group.display_name}&nbsp;</dd>
<dt>${_('Owner:')}</dt><dd>${group.owner.username}&nbsp;</dd>
<dt>${_('Type:')}</dt><dd>${group.group_type}&nbsp;</dd>
<dt>${_('Needs Sponsor:')}</dt><dd>
<py:if test="group.needs_sponsor">${_('Yes')}</py:if>
<py:if test="not group.needs_sponsor">${_('No')}</py:if>
&nbsp;</dd>
<dt>${_('Self Removal:')}</dt><dd>
<py:if test="group.user_can_remove">${_('Yes')}</py:if>
<py:if test="not group.user_can_remove">${_('No')}</py:if>
&nbsp;</dd>
<dt>${_('Join Message:')}</dt><dd>${group.joinmsg}&nbsp;</dd>
<dt>${_('Prerequisite:')}</dt>
<dd py:if="group.prerequisite">${group.prerequisite.name}&nbsp;</dd>
<dd py:if="not group.prerequisite">&nbsp;</dd>
<dt>${_('Created:')}</dt><dd>${group.creation}&nbsp;</dd>
<py:if test="can_sponsor">
<dt>${_('Add User:')}</dt>
<dd>
<form action="${tg.url('/group/apply/%s' % group.name)}">
<input type='text' size='15' name='targetname'/>
<input type="submit" value="${('Add')}" />
<script type="text/javascript">var group_user_add = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_user_add')}'});</script>
</form>
</dd>
</py:if>
</dl>
</div>
<!--
TODO: Implement this :)
<h3 py:if='me.fedoraRoleStatus == "approved"'>${_('Invite')}</h3>
<span py:if='me.fedoraRoleStatus == "approved"'>${form(action='modifyGroup', value=value, method='get')}</span>
-->
<h3>${_('Members')}</h3>
<table>
<thead>
<tr>
<th>${_('Username')}</th>
<th>${_('Sponsor')}</th>
<th>${_('Date Added')}</th>
<th>${_('Date Approved')}</th>
<th>${_('Approval')}</th>
<th>${_('Role Type')}</th>
<th py:if="can_sponsor">${_('Action')}</th>
</tr>
</thead>
<tr py:for="role in sorted([(role.member.username, role) for role in group.roles ])">
<td><a href="${tg.url('/user/view/%s' % role[1].member.username)}">${role[1].member.username}</a></td>
<td py:if='role[1].sponsor'><a href="${tg.url('/user/view/%s' % role[1].sponsor.username)}">${role[1].sponsor.username}</a></td>
<td py:if='not role[1].sponsor'>${_('None')}</td>
<td>${role[1].creation.astimezone(timezone).strftime('%Y-%m-%d %H:%M:%S %Z')}</td>
<td py:if='role[1].approval'>${role[1].approval.astimezone(timezone).strftime('%Y-%m-%d %H:%M:%S %Z')}</td>
<td py:if='not role[1].approval'>${_('None')}</td>
<td>${role[1].role_status}</td>
<td>${role[1].role_type}</td>
<!-- This section includes all action items -->
<td py:if="can_sponsor">
<ul class="actions">
<li py:if="role[1].role_status == 'unapproved'">
<py:if test="group.needs_sponsor">
<a href="${tg.url('/group/sponsor/%s/%s' % (group.name, role[1].member.username))}">${_('Sponsor')}</a>
<script type="text/javascript">var hb1 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_sponsor')}'});</script>
</py:if>
<py:if test="not group.needs_sponsor">
<a href="${tg.url('/group/sponsor/%s/%s' % (group.name, role[1].member.username))}">${_('Approve')}</a>
<script type="text/javascript">var hb2 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_approve')}'});</script>
</py:if>
</li>
<li>
<a href="${tg.url('/group/remove/%s/%s' % (group.name, role[1].member.username))}">${_('Remove')}</a>
<script type="text/javascript">var hb3 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_remove')}'});</script>
</li>
<li py:if="role[1].role_type != 'administrator' or auth.canDowngradeUser(person, group, role[1].member)">
<a href="${tg.url('/group/upgrade/%s/%s' % (group.name, role[1].member.username))}">${_('Upgrade')}</a>
<script type="text/javascript">var hb4 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_upgrade')}'});</script>
</li>
<li py:if="role[1].role_type != 'user' or auth.canDowngradeUser(person, group, role[1].member)">
<a href="${tg.url('/group/downgrade/%s/%s' % (group.name, role[1].member.username))}">${_('Downgrade')}</a>
<script type="text/javascript">var hb5 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/group_downgrade')}'});</script>
</li>
</ul>
</td>
</tr>
</table>
</body>
</html>

View file

@ -1,12 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<head>
<title>${help[0]}</title>
</head>
<body>
${XML(help[1])}
</body>
</html>

View file

@ -1,33 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="master.html" />
<head>
<title>${_('Fedora Accounts System')}</title>
</head>
<body>
<?python from fas import auth ?>
<h2>${_('Todo queue:')}</h2>
<py:for each="group in sorted(person.memberships)">
<py:if test="auth.canSponsorGroup(person, group) and group.unapproved_roles">
<dd>
<ul class="queue">
<li py:for="role in group.unapproved_roles[:5]">
${Markup(_('&lt;strong&gt;%(user)s&lt;/strong&gt; requests approval to join &lt;a href="group/view/%(group)s"&gt;%(group)s&lt;/a&gt;.') % {'user': role.member.username, 'group': group.name, 'group': group.name})}
</li>
</ul>
</dd>
</py:if>
</py:for>
<ul class="queue">
<li py:if="not cla" class="unapproved">${Markup(_('CLA not completed. To become a full Fedora Contributor please &lt;a href="%s"&gt;complete the CLA&lt;/a&gt;.') % tg.url('/cla/'))}</li>
<li py:if="not person.ssh_key">${Markup(_('You have not submitted an SSH key, some Fedora resources require an SSH key. Please submit yours by editing &lt;a href="%s"&gt;My Account&lt;/a&gt;') % tg.url('/user/edit'))}</li>
</ul>
<div>
<!-- TODO: Make this entire page more friendly -->
<a href="${tg.url('/user/gencert')}">${_('Download a client-side certificate')}</a>&nbsp;
<script type="text/javascript">var gencert = new HelpBalloon({dataURL: '${tg.url('/help/get_help/gencert')}'});</script>
</div>
</body>
</html>

View file

@ -1,33 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="master.html" />
<head>
<title>${_('Login to the Fedora Accounts System')}</title>
<style type="text/css">
#content ul
{
list-style: square;
margin: 1ex 3ex;
}
</style>
</head>
<body>
<h2>${_('Login')}</h2>
<p>${message}</p>
<form action="${previous_url}" method="post">
<div class="field"><label for="user_name">${_('User Name:')}</label> <input type="text" id="user_name" name="user_name" /></div>
<div class="field"><label for="password">${_('Password:')}</label> <input type="password" id="password" name="password" /></div>
<div class="field">
<input type="submit" name="login" value="${_('Login')}" />
<input py:if="forward_url" type="hidden" name="forward_url" value="${tg.url(forward_url)}" />
<input py:for="name,value in original_parameters.items()" type="hidden" name="${name}" value="${value}" />
</div>
</form>
<ul>
<li><a href="${tg.url('/user/resetpass')}">${_('Forgot Password?')}</a></li>
<li><a href="${tg.url('/user/new')}">${_('Sign Up')}</a></li>
</ul>
</body>
</html>

View file

@ -1,104 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:py="http://genshi.edgewall.org/"
py:strip="">
<?python
_ = lambda text: tg.gettext(text)
?>
<head py:match="head" py:attrs="select('@*')">
<link href="${tg.url('/static/css/style.css')}" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="${tg.url('/static/images/favicon.ico')}" type="image/vnd.microsoft.icon" />
<meta py:replace="select('*|text()')" />
<script type="text/javascript" src="${tg.url('/static/js/prototype.js')}"></script>
<script type="text/javascript" src="${tg.url('/static/js/prototype.improvements.js')}"></script>
<script type="text/javascript" src="${tg.url('/static/js/scriptaculous.js?load=effects')}"></script>
<script type="text/javascript" src="${tg.url('/static/js/HelpBalloon.js')}"></script>
</head>
<body py:match="body" py:attrs="select('@*')">
<div id="wrapper">
<div id="head">
<h1><a href="http://fedoraproject.org/">${_('Fedora')}</a></h1>
<!-- TODO: Make this do something useful, talk about interface :)
<div id="searchbox">
<form action="" method="get">
<label for="q">${_('Search:')}</label>
<input type="text" name="q" id="q" />
<input type="submit" value="${_('Search')}" />
</form>
</div>
-->
</div>
<div id="topnav">
<ul>
<li class="first"><a href="http://fedoraproject.org/">${_('Learn about Fedora')}</a></li>
<li><a href="http://fedoraproject.org/get-fedora.html">${_('Download Fedora')}</a></li>
<li><a href="http://fedoraproject.org/wiki/">${_('Projects')}</a></li>
<li><a href="http://fedoraproject.org/join-fedora.html">${_('Join Fedora')}</a></li>
<li><a href="http://fedoraproject.org/wiki/Communicate">${_('Communicate')}</a></li>
<li><a href="http://docs.fedoraproject.org/">${_('Help/Documentation')}</a></li>
</ul>
</div>
<div id="infobar">
<div id="authstatus">
<span py:if="not tg.identity.anonymous">
<strong>${_('Logged in:')}</strong> ${tg.identity.user.username}
</span>
</div>
<div id="control">
<ul>
<li><a href="${tg.url('/about')}">About</a></li>
<li py:if="not tg.identity.anonymous"><a href="${tg.url('/user/view/%s' % tg.identity.user.username)}">${_('My Account')}</a></li>
<li py:if="not tg.identity.anonymous"><a href="${tg.url('/logout')}">${_('Log Out')}</a></li>
<li py:if="tg.identity.anonymous"><a href="${tg.url('/login')}">${_('Log In')}</a></li>
</ul>
</div>
</div>
<div id="main">
<div id="sidebar">
<ul>
<li class="first"><a href="${tg.url('/home')}">${_('Home')}</a></li>
<div py:if="not tg.identity.anonymous and 'accounts' in tg.identity.groups" py:strip=''>
<!-- TODO: Make these use auth.py -->
<li><a href="${tg.url('/group/new')}">${_('New Group')}</a></li>
<li><a href="${tg.url('/user/list')}">${_('User List')}</a></li>
</div>
<li py:if="not tg.identity.anonymous"><a href="${tg.url('/group/list/A*')}">${_('Group List')}</a></li>
<li py:if="not tg.identity.anonymous"><a href="${tg.url('/group/list/A*')}">${_('Apply For a new Group')}</a></li>
<li><a href="http://fedoraproject.org/wiki/FWN/LatestIssue">${_('News')}</a></li>
</ul>
<!--
<div py:if="tg.identity.anonymous" id="language">
<form action="${tg.url('/language')}" method="get">
<label for="locale">${_('Locale:')}</label>
<input type="text" name="locale" id="locale" />
<input type="submit" value="${_('OK')}" />
</form>
</div>
-->
</div>
<div id="content">
<div py:if="tg_flash" class="flash">
${tg_flash}
</div>
<div py:replace="select('*|text()')" />
</div>
<div id="footer">
<ul id="footlinks">
<li class="first"><a href="${tg.url('/about')}">${_('About')}</a></li>
<li><a href="http://fedoraproject.org/wiki/Communicate">${_('Contact Us')}</a></li>
<li><a href="http://fedoraproject.org/wiki/Legal">${_('Legal &amp; Privacy')}</a></li>
<!--<li><a href="/">Site Map</a></li>-->
<li><a href="${tg.url('/logout')}">${_('Log Out')}</a></li>
</ul>
<p class="copy">
${Markup(_('Copyright &copy; 2007 Red Hat, Inc. and others. All Rights Reserved. Please send any comments or corrections to the &lt;a href="mailto:webmaster@fedoraproject.org"&gt;websites team&lt;/a&gt;.'))}
</p>
<p class="disclaimer">
${_('The Fedora Project is maintained and driven by the community and sponsored by Red Hat. This is a community maintained site. Red Hat is not responsible for content.')}
</p>
</div>
</div>
</div> <!-- End wrapper -->
</body>
</html>

View file

@ -1,15 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Fedora Accounts System')}</title>
</head>
<body>
<h2>${_('Fedora Project OpenID Provider')}</h2>
<p>
${Markup_('Description goes here, &lt;a href="http://username.fedorapeople.org/"&gt;username.fedorapeople.org&lt;/a&gt;')}
</p>
</body>
</html>

View file

@ -1 +0,0 @@
${body}

View file

@ -1,21 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Fedora Accounts System')}</title>
<link rel="openid.server" href="${server}" />
</head>
<body>
<h2>${_('User %s') % person.username}</h2>
<div class="userbox">
<dl>
<dt>${_('Username:')}</dt>
<dd>${person.username}</dd>
<dt>${_('Name:')}</dt>
<dd>${person.human_name}</dd>
</dl>
</div>
</body>
</html>

View file

@ -1,20 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Fedora Accounts System')}</title>
</head>
<body>
<h2>${_('Fedora Project OpenID Provider')}</h2>
<form action="${tg.url('/openid/server')}">
<div>
<input type="hidden" id="url" name="url" value="${url}" />
<input type="checkbox" id="trusted" name="trusted" value="allow" />
<label for="trusted">${Markup(_('Allow &lt;strong&gt;%s&lt;/strong&gt; to authenticate to your OpenID identity?') % url)}</label><br />
<input type="submit" value="${_('Submit')}" />
</div>
</form>
</body>
</html>

View file

@ -1,2 +0,0 @@
${cert}
${key}

View file

@ -1,20 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Change Password')}</title>
</head>
<body>
<h2>${_('Change Password')}</h2>
<form action="${tg.url('/user/setpass')}" method="post">
<ul>
<div class="field"><label for="currentpassword">${_('Current Password:')}</label> <input type="password" id="currentpassword" name="currentpassword" /></div>
<div class="field"><label for="password">${_('New Password:')}</label> <input type="password" id="password" name="password" /></div>
<div class="field"><label for="passwordcheck">${_('Confirm Password:')}</label> <input type="password" id="passwordcheck" name="passwordcheck" /></div>
<div class="field"><input type="submit" value="${_('Change Password')}" /></div>
</ul>
</form>
</body>
</html>

View file

@ -1,88 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Edit Account')}</title>
</head>
<body>
<h2>${_('Edit Account (%s)') % target.username}</h2>
<form action="${tg.url('/user/save/%s' % target.username)}" method="post" enctype="multipart/form-data">
<div class="field">
<label for="human_name">${_('Human Name')}:</label>
<input type="text" id="human_name" name="human_name" value="${target.human_name}" />
<script type="text/javascript">var hb1 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_human_name')}'});</script>
</div>
<!--Need to figure out what the interface should be for emails. -->
<div class="field">
<label for="mail">${_('Email')}:</label>
<input type="text" id="email" name="email" value="${target.email}" />
<span py:if="target.unverified_email and target.emailtoken">
${Markup(_('(pending change to %(email)s - &lt;a href="%(url)s"&gt;cancel&lt;/a&gt;)') % {'email': target.unverified_email, 'url': tg.url('/user/verifyemail/1/cancel')})}
</span>
<script type="text/javascript">var hb2 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_email')}'});</script>
</div>
<!-- <div class="field">
<label for="fedoraPersonBugzillaMail">${_('Bugzilla Email')}:</label>
<input type="text" id="fedoraPersonBugzillaMail" name="fedoraPersonBugzillaMail" value="${target.username}" />
</div> -->
<div class="field">
<label for="telephone">${_('Telephone Number')}:</label>
<input type="text" id="telephone" name="telephone" value="${target.telephone}" />
<script type="text/javascript">var hb5 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_telephone')}'});</script>
</div>
<div class="field">
<label for="postal_address">${_('Postal Address')}:</label>
<textarea id="postal_address" name="postal_address">${target.postal_address}</textarea>
<script type="text/javascript">var hb6 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_postal_address')}'});</script>
</div>
<div class="field">
<label for="ircnick">${_('IRC Nick')}:</label>
<input type="text" id="ircnick" name="ircnick" value="${target.ircnick}" />
<script type="text/javascript">var hb3 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_ircnick')}'});</script>
</div>
<div class="field">
<label for="gpg_keyid">${_('PGP Key')}:</label>
<input type="text" id="gpg_keyid" name="gpg_keyid" value="${target.gpg_keyid}" />
<script type="text/javascript">var hb4 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_gpg_keyid')}'});</script>
</div>
<div class="field">
<label for="ssh_key">${_('Public SSH Key')}:</label>
<!--<textarea id="ssh_key" rows='3' cols='50' name="ssh_key">${target.ssh_key}</textarea>-->
<input type="file" name="ssh_key" id="ssh_key" />
<script type="text/javascript">var hb19 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_ssh_key')}'});</script>
</div>
<div class="field">
<label for="timezone">${_('Time Zone')}:</label>
<select id="timezone" name="timezone">
<?python
from pytz import common_timezones
?>
<option py:for="tz in common_timezones" value="${tz}" py:attrs="{'selected': target.timezone == tz and 'selected' or None}">${tz}</option>
</select>
<script type="text/javascript">var hb7 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_timezone')}'});</script>
</div>
<div class="field">
<label for="locale">${_('Locale')}:</label>
<input type="text" id="locale" name="locale" value="${target.locale}" />
<script type="text/javascript">var hb8 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_locale')}'});</script>
<!--
<select id="locale" name="locale">
option py:for="locale in available_locales" value="${locale}" py:attrs="{'selected': target.locale == locale and 'selected' or None}">${locale}</option>
</select>
-->
<!--<script type="text/javascript">var hb7 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/locale')}'});</script>-->
</div>
<div class="field">
<label for="comments ">${_('Comments')}:</label>
<textarea id="comments" name="comments">${target.comments}</textarea>
<script type="text/javascript">var hb8 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_comments')}'});</script>
</div>
<div class="field">
<input type="submit" value="${_('Save!')}" />
<a href="${tg.url('/user/view/%s' % target.username)}">${_('Cancel')}</a>
</div>
</form>
</body>
</html>

View file

@ -1,45 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Users List')}</title>
</head>
<body>
<?python from fas import auth ?>
<h2>${_('List (%s)') % search}</h2>
<form method="get" action="${tg.url('/user/list')}">
<p>${_('"*" is a wildcard (Ex: "ric*")')}</p>
<div>
<input type="text" value="${search}" name="search" size="15 "/>
<input type="submit" value="Search" />
</div>
</form>
<h3>${_('Results')}</h3>
<ul class="letters">
<li py:for="letter in 'abcdefghijklmnopqrstuvwxyz'.upper()"><a href="${tg.url('/user/list/%s*' % letter)}">${letter}</a></li>
<li><a href="${tg.url('/user/list/*')}">${_('All')}</a></li>
</ul>
<table>
<thead>
<tr>
<th>${_('Username')}</th>
<th>${_('Account Status')}</th>
</tr>
</thead>
<tbody>
<tr py:for="person in people">
<td><a href="${tg.url('/user/view/%s' % person.username)}">${person.username}</a></td>
<td>
<?python
cla = auth.CLADone(person)
?>
<span py:if="cla" class="approved">${_('CLA Done')}</span>
<span py:if="not cla" class="unapproved">${_('Not Done')}</span>
</td>
</tr>
</tbody>
</table>
</body>
</html>

View file

@ -1,42 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Sign up for a Fedora account')}</title>
</head>
<body>
<h2>${_('Sign up for a Fedora account')}</h2>
<form action="${tg.url('/user/create')}" method="post">
<div class="field">
<label for="username">${_('Username:')}</label>
<input type="text" id="username" name="username" />
</div>
<div class="field">
<label for="human_name">${_('Full Name:')}</label>
<input type="text" id="human_name" name="human_name" />
</div>
<div class="field">
<label for="email">${_('Email:')}</label>
<input type="text" id="email" name="email" />
</div>
<!--
<div class="field">
<label for="fedoraPersonBugzillaMail">${_('Bugzilla Email:')}</label>
<input type="text" id="mail" name="fedoraPersonBugzillaMail" />
</div>
<div class="field">
<label for="telephone">${_('Telephone Number:')}</label>
<input type="text" id="telephone" name="telephone" />
</div>
<div class="field">
<label for="postal_address">${_('Postal Address:')}</label>
<textarea id="postal_address" name="postal_address"></textarea>
</div>-->
<div class="field">
<input type="submit" value="${_('Sign up!')}" />
</div>
</form>
</body>
</html>

View file

@ -1,20 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Reset Password')}</title>
</head>
<body>
<h2>${_('Reset Password')}</h2>
<form action="${tg.url('/user/sendtoken')}" method="post">
<ul>
<div class="field"><label for="username">${_('Username:')}</label> <input type="text" id="username" name="username" /></div>
<div class="field"><label for="email">${_('Email:')}</label> <input type="text" id="email" name="email" /></div>
<div class="field"><input type="checkbox" id="encrypted" name="encrypted" /> <label style="width: auto; float: none; margin-left: 1ex;" for="encrypted">${_('Encrypt/Sign password reset email')}</label></div>
<div class="field"><input type="submit" value="${_('Reset Password')}" /></div>
</ul>
</form>
</body>
</html>

View file

@ -1,21 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Confirm Email Change Request')}</title>
</head>
<body>
<h2>${_('Confirm Email Change Request')}</h2>
<form action="${tg.url('/user/setemail/%s') % token}" method="post">
<div>
<p>
${_('Do you really want to change your email to: %s?') % person.unverified_email}
</p>
<input type="submit" value="${_('Confirm')}" />
<a href="${tg.url('/user/verifyemail/%s/%s/cancel') % (person.username, token)}">${_('Cancel')}</a>
</div>
</form>
</body>
</html>

View file

@ -1,22 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('Reset Password')}</title>
</head>
<body>
<h2>${_('Reset Password')}</h2>
<form action="${tg.url('/user/setnewpass/%s/%s') % (person.username, token)}" method="post">
<ul>
<div class="field"><label for="password">${_('New Password:')}</label> <input type="password" id="password" name="password" /></div>
<div class="field"><label for="passwordcheck">${_('Confirm Password:')}</label> <input type="password" id="passwordcheck" name="passwordcheck" /></div>
<div class="field">
<input type="submit" value="${_('Change Password')}" />
<a href="${tg.url('/user/verifypass/%s/%s/cancel') % (person.username, token)}">${_('Cancel')}</a>
</div>
</ul>
</form>
</body>
</html>

View file

@ -1,99 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="../master.html" />
<head>
<title>${_('View Account')}</title>
</head>
<body>
<?python
from fas import auth
from fas.model import People
viewer = People.by_username(tg.identity.user.username)
?>
<h2 class="account" py:if="personal">${_('Your Fedora Account')}</h2>
<h2 class="account" py:if="not personal">${_('%s\'s Fedora Account') % person.human_name}</h2>
<h3>${_('Account Details')} <a href="${tg.url('/user/edit/%s' % person.username)}" py:if="personal or admin">${_('(edit)')}</a></h3>
<div class="userbox">
<dl>
<dt>${_('Account Name:')}</dt><dd>${person.username}</dd>
<dt>${_('Real Name:')}</dt><dd>${person.human_name}</dd>
<dt>${_('Email:')}</dt><dd>${person.email}
<span py:if="(personal or admin) and person.unverified_email and person.emailtoken">
${Markup(_('(pending change to %(email)s - &lt;a href="%(url)s"&gt;cancel&lt;/a&gt;)') % {'email': person.unverified_email, 'url': tg.url('/user/verifyemail/1/cancel')})}
</span>
</dd>
<py:if test="personal"><dt>${_('Telephone Number:')}</dt><dd>${person.telephone}&nbsp;</dd></py:if>
<py:if test="personal"><dt>${_('Postal Address:')}</dt><dd>${person.postal_address}&nbsp;</dd></py:if>
<!--<dt>${_('Bugzilla Email:')}</dt><dd>${person.username}</dd>-->
<dt>${_('IRC Nick:')}</dt><dd>${person.ircnick}&nbsp;</dd>
<dt>${_('PGP Key:')}</dt><dd>${person.gpg_keyid}&nbsp;</dd>
<py:if test="personal"><dt>${_('Public SSH Key:')}</dt>
<dd py:if="person.ssh_key" title="${person.ssh_key}">${person.ssh_key[:20]}....&nbsp;</dd>
<dd py:if="not person.ssh_key">No ssh key provided&nbsp;</dd>
</py:if>
<dt>${_('Comments:')}</dt><dd>${person.comments}&nbsp;</dd>
<py:if test="personal"><dt>${_('Password:')}</dt><dd><span class="approved">${_('Valid')}</span> <a href="${tg.url('/user/changepass')}">(change)</a></dd></py:if>
<dt>${_('Account Status:')}</dt><dd>
<span py:if="person.status == 'active'" class="approved">${_('Active')}</span>
<span py:if="person.status == 'vacation'" class="approved">${_('Vacation')}</span>
<span py:if="person.status == 'inactive'" class="unapproved">${_('Inactive')}</span>
<span py:if="person.status == 'pinged'" class="approved">${_('Pinged')}</span>
<script type="text/javascript">var hb1 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_account_status')}'});</script></dd>
<dt>${_('CLA:')}</dt><dd>
<span py:if="cla" class="approved">${_('CLA Done')}</span>
<span py:if="not cla" class="unapproved">${_('Not Done')}<py:if test="personal"> (<a href="${tg.url('/cla/')}">${_('Complete it!')}</a>)</py:if></span>
<script type="text/javascript">var hb2 = new HelpBalloon({dataURL: '${tg.url('/help/get_help/user_cla')}'});</script></dd>
</dl>
</div>
<h3 py:if="personal">${_('Your Roles')}</h3>
<h3 py:if="not personal">${_('%s\'s Roles') % person.human_name}</h3>
<!--mpm <ul class="roleslist">
<li py:for="group in sorted(groups.keys())"><span class="team approved">${groupdata[group].fedoraGroupDesc} (${group})</span></li>
<li py:for="group in sorted(groupsPending.keys())"><span class="team unapproved">${groupdata[group].fedoraGroupDesc} (${group})</span></li>
</ul>
-->
<!--
<ul class="actions" py:if="personal">
<li><a href="${tg.url('/group/list/A*')}">${_('(Join another project)')}</a></li>
<li><a href="/">${_('(Create a new project)')}</a></li>
</ul>
-->
<ul id="rolespanel">
<py:for each="group in sorted(person.memberships, lambda x,y: cmp(x.name, y.name))">
<li py:if="auth.canViewGroup(viewer, group)" class="role">
<h4>${group.display_name}</h4> (${group.group_type})
<dl>
<dt>${_('Status:')}</dt>
<dd>
<span class="approved" py:if="group in person.approved_memberships">${_('Approved')}</span>
<span class="unapproved" py:if="group in person.unapproved_memberships">${_('None')}</span>
</dd>
<py:if test="personal">
<dt>${_('Tools:')}</dt>
<dd>
<ul class="tools">
<li><a href="${tg.url('/group/view/%s' % group.name)}">${_('View Group')}</a></li>
<li><a href="${tg.url('/group/invite/%s' % group.name)}">${_('Invite a New Member...')}</a></li>
<li py:if="auth.canSponsorGroup(person, group)"><a href="${tg.url('/group/view/%s' % group.name)}">${_('Manage Group Membership...')}</a></li>
<li py:if="auth.canEditGroup(person, group)"><a href="${tg.url('/group/edit/%s' % group.name)}">${_('Manage Group Details...')}</a></li>
</ul>
</dd>
<py:if test="auth.canSponsorGroup(person, group) and group.unapproved_roles">
<dt>${_('Queue:')}</dt>
<dd>
<ul class="queue">
<li py:for="role in group.unapproved_roles[:5]">
${Markup(_('&lt;strong&gt;%(user)s&lt;/strong&gt; requests approval to join &lt;strong&gt;%(group)s&lt;/strong&gt;.') % {'user': role.member.username, 'group': group.name})}
</li>
</ul>
</dd>
</py:if>
</py:if>
</dl>
</li>
</py:for>
</ul>
</body>
</html>

View file

@ -1,26 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="master.html" />
<head>
<title>${_('Welcome to FAS2')}</title>
<style type="text/css">
#content ul
{
list-style: square;
margin: 1ex 3ex;
}
</style>
</head>
<body>
<p>
${Markup(_('Welcome to the Fedora Accounts System 2. Please submit bugs to &lt;a href="https://fedorahosted.org/fas2"&gt;https://fedorahosted.org/fas2/&lt;/a&gt; or stop by #fedora-admin on irc.freenode.net.'))}
</p>
<ul>
<li><a href="${tg.url('/login')}">${_('Log In')}</a></li>
<li><a href="${tg.url('/user/new')}">${_('New Account')}</a></li>
<li><a href="http://fedoraproject.org/wiki/Join">${_('Why Join?')}</a></li>
</ul>
</body>
</html>

View file

@ -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 "<title>welcome to turbogears</title>" in response
def test_logintitle(self):
"login page should have the right title"
testutil.createRequest("/login")
response = cherrypy.response.body[0].lower()
assert "<title>login</title>" in response

View file

@ -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"

View file

@ -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/')

View file

@ -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 <mmcgrath@redhat.com>
#
# 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()

View file

@ -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)