예제 #1
0
파일: __init__.py 프로젝트: nicfit/apex
 def setUpClass(cls):
     """ must add default route 'home' and include apex
         we also must create a default user/pass/group to test
     """
     cls.engine = engine_from_config(settings, prefix='sqlalchemy.')
     DBSession.configure(bind=cls.engine)
     Base.metadata.create_all(cls.engine)
예제 #2
0
파일: libapex.py 프로젝트: webjunkie01/apex
def create_user(**kwargs):
    """
::

    from apex.lib.libapex import create_user

    create_user(username='******', password='******', active='Y', group='group')

    Returns: AuthUser object
    """
    user = AuthUser()

    if 'group' in kwargs:
        try:
            group = DBSession.query(AuthGroup). \
            filter(AuthGroup.name==kwargs['group']).one()

            user.groups.append(group)
        except NoResultFound:
            pass

        del kwargs['group']

    for key, value in kwargs.items():
        setattr(user, key, value)

    DBSession.add(user)
    DBSession.flush()
    return user
예제 #3
0
def create_user(**kwargs):
    """

::

    from apex.lib.libapex import create_user

    create_user(username='******', password='******', active='Y', group='group')


    Returns: AuthUser object
    """
    user = AuthUser()

    if 'group' in kwargs:
        try:
            group = DBSession.query(AuthGroup). \
            filter(AuthGroup.name==kwargs['group']).one()

            user.groups.append(group)
        except NoResultFound:
            pass

        del kwargs['group']

    for key, value in kwargs.items():
        setattr(user, key, value)

    DBSession.add(user)
    DBSession.flush()
    return user
예제 #4
0
def profile_edit(request):
    form = ProfileRecordForm(request.POST)
    if 'record_id' in request.matchdict:
        record = get_profile_record(request.matchdict['id'], \
            request.matchdict['record_id'])
        if not request.POST:
            form.record_type.data = record.record_type
            form.name.data = record.name
            form.contents.data = record.contents
    else:
        record = Profile_Record(profile_id=request.matchdict['id'])

    if request.method == 'POST' and form.validate():
        if request.POST['record_type'] in ['TXT', 'SPF']:
            request.POST['contents'] = '"' + request.POST['contents'] \
                .replace('"','') + '"'
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        return HTTPFound(location= \
            route_url('apex_route53_profile_edit', request, \
            id=request.matchdict['id']))
    return {'title':'Edit Profile Records', \
        'form':form, \
        'profile':get_profile(request.matchdict['id']), \
        'profile_records':get_profile_records(request.matchdict['id'])}
예제 #5
0
def edit(request):
    """ edit(request)
        no return value, called with route_url('apex_edit', request)

        This function will only work if you have set apex.auth_profile.

        This is a very simple edit function it works off your auth_profile
        class, all columns inside your auth_profile class will be rendered.
    """
    title = _('Edit')

    ProfileForm = model_form(
        model=get_module(apex_settings('auth_profile')),
        base_class=ExtendedForm,
        exclude=('id', 'user_id'),
    )

    record = AuthUser.get_profile(request)
    form = ProfileForm(obj=record)
    if request.method == 'POST' and form.validate():
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        flash(_('Profile Updated'))
        return HTTPFound(location=request.url)

    return {'title': title, 'form': form, 'action': 'edit'}
예제 #6
0
파일: __init__.py 프로젝트: nycynik/apex
 def setUpClass(cls):
     """ must add default route 'home' and include apex
         we also must create a default user/pass/group to test
     """
     cls.engine = engine_from_config(settings, prefix='sqlalchemy.')
     DBSession.configure(bind=cls.engine)
     Base.metadata.create_all(cls.engine)
예제 #7
0
def activate(request):
    """
    """
    user_id = request.matchdict.get('user_id')
    user = AuthUser.get_by_id(user_id)
    submitted_hmac = request.matchdict.get('hmac')
    current_time = time.time()
    time_key = int(base64.b64decode(submitted_hmac[10:]))
    if current_time < time_key:
        hmac_key = hmac.new('%s:%s:%d' % (str(user.id), \
                            apex_settings('auth_secret'), time_key), \
                            user.email).hexdigest()[0:10]
        if hmac_key == submitted_hmac[0:10]:
            user.active = 'Y'
            DBSession.merge(user)
            DBSession.flush()
            flash(_('Account activated. Please log in.'))
            activated_route = apex_settings('activated_route')
            if not activated_route:
                activated_route = 'apex_login'
            return HTTPFound(location=route_url(activated_route, request))

    flash(_('Invalid request, please try again'))
    return HTTPFound(location=route_url(apex_settings('came_from_route'), \
                                        request))
예제 #8
0
파일: views.py 프로젝트: cd34/apex-route53
def profile_edit(request):
    form = ProfileRecordForm(request.POST)
    if 'record_id' in request.matchdict:
        record = get_profile_record(request.matchdict['id'], \
            request.matchdict['record_id'])
        if not request.POST:
            form.record_type.data = record.record_type
            form.name.data = record.name
            form.contents.data = record.contents
    else:
        record = Profile_Record(profile_id=request.matchdict['id'])

    if request.method == 'POST' and form.validate():
        if request.POST['record_type'] in ['TXT', 'SPF']:
            request.POST['contents'] = '"' + request.POST['contents'] \
                .replace('"','') + '"'
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        return HTTPFound(location= \
            route_url('apex_route53_profile_edit', request, \
            id=request.matchdict['id']))
    return {'title':'Edit Profile Records', \
        'form':form, \
        'profile':get_profile(request.matchdict['id']), \
        'profile_records':get_profile_records(request.matchdict['id'])}
예제 #9
0
def edit(request):
    """ edit(request)
        no return value, called with route_url('apex_edit', request)

        This function will only work if you have set apex.auth_profile.

        This is a very simple edit function it works off your auth_profile
        class, all columns inside your auth_profile class will be rendered.
    """
    title = _('Edit')

    ProfileForm = model_form(
        model=get_module(apex_settings('auth_profile')),
        base_class=ExtendedForm,
        exclude=('id', 'user_id'),
    )

    record = AuthUser.get_profile(request)
    form = ProfileForm(obj=record)
    if request.method == 'POST' and form.validate():
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        flash(_('Profile Updated'))
        return HTTPFound(location=request.url)

    return {'title': title, 'form': form, 'action': 'edit'}
예제 #10
0
 def __acl__(self):
     dbsession = DBSession()
     groups = dbsession.query(AuthGroup.name).all()
     defaultlist = [ (Allow, Everyone, 'view'),
             (Allow, Authenticated, 'authenticated'),]
     for g in groups:
         defaultlist.append( (Allow, 'group:%s' % g, g[0]) )
     return defaultlist
예제 #11
0
def profile_delete(request):
    record = get_profile_record(request.matchdict['id'], \
        request.matchdict['record_id'])
    DBSession.delete(record)
    DBSession.flush()
    return HTTPFound(location= \
        route_url('apex_route53_profile_edit', request, \
        id=request.matchdict['id']))
예제 #12
0
 def __acl__(self):
     dbsession = DBSession()
     groups = dbsession.query(AuthGroup.name).all()
     defaultlist = [ (Allow, Everyone, 'view'),
             (Allow, Authenticated, 'authenticated'),]
     for g in groups:
         defaultlist.append( (Allow, 'group:%s' % g, g[0]) )
     return defaultlist
예제 #13
0
파일: views.py 프로젝트: cd34/apex-route53
def profile_delete(request):
    record = get_profile_record(request.matchdict['id'], \
        request.matchdict['record_id'])
    DBSession.delete(record)
    DBSession.flush()
    return HTTPFound(location= \
        route_url('apex_route53_profile_edit', request, \
        id=request.matchdict['id']))
예제 #14
0
파일: forms.py 프로젝트: webjunkie01/apex
    def create_user(self, username):
        user = AuthUser(username=username, password=self.data["password"], email=self.data["email"])
        DBSession.add(user)
        settings = get_current_registry().settings
        if settings.has_key("apex.default_user_group"):
            group = DBSession.query(AuthGroup).filter(AuthGroup.name == settings["apex.default_user_group"]).one()
            user.groups.append(group)
        DBSession.flush()

        return user
예제 #15
0
def profiles(request):
    form = ProfileForm(request.POST)
    if request.method == 'POST' and form.validate():
        record = Profile()
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        return HTTPFound(location= \
            route_url('apex_route53_profiles', request))
    return {'title': 'Profiles', 'form': form, 'profiles': get_profiles()}
예제 #16
0
파일: views.py 프로젝트: cd34/apex-route53
def profiles(request):
    form = ProfileForm(request.POST)
    if request.method == 'POST' and form.validate():
        record = Profile()
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        return HTTPFound(location= \
            route_url('apex_route53_profiles', request))
    return {'title':'Profiles', 'form':form, 'profiles':get_profiles()}
예제 #17
0
def apex_remember(request, user_id):
    if asbool(apex_settings('log_logins')):
        if apex_settings('log_login_header'):
            ip_addr=request.environ.get(apex_settings('log_login_header'), \
                    u'invalid value - apex.log_login_header')
        else:
             ip_addr=request.environ['REMOTE_ADDR']
        record = AuthUserLog(user_id=user_id, ip_addr=ip_addr)
        DBSession.add(record)
        DBSession.flush()
    return remember(request, user_id)
예제 #18
0
def apexid_from_token(token):
    """ Returns the apex id from the OpenID Token
    """
    dbsession = DBSession()
    auth = json.loads(dbsession.query(KeyStorage.value). \
                      filter(KeyStorage.key==token).one()[0])
    if 'profile' in auth:
        auth['id'] = auth['profile']['accounts'][0]['userid']
        auth['provider'] = auth['profile']['accounts'][0]['domain']
        return auth
    return None
예제 #19
0
def apexid_from_token(token):
    """ Returns the apex id from the OpenID Token
    """
    dbsession = DBSession()
    auth = json.loads(dbsession.query(KeyStorage.value). \
                      filter(KeyStorage.key==token).one()[0])
    if 'profile' in auth:
        auth['id'] = auth['profile']['accounts'][0]['userid']
        auth['provider'] = auth['profile']['accounts'][0]['domain']
        return auth
    return None
예제 #20
0
파일: libapex.py 프로젝트: webjunkie01/apex
def apex_remember(request, user_id):
    if asbool(apex_settings('log_logins')):
        if apex_settings('log_login_header'):
            ip_addr=request.environ.get(apex_settings('log_login_header'), \
                    u'invalid value - apex.log_login_header')
        else:
            ip_addr = request.environ['REMOTE_ADDR']
        record = AuthUserLog(user_id=user_id, ip_addr=ip_addr)
        DBSession.add(record)
        DBSession.flush()
    return remember(request, user_id)
예제 #21
0
def register(request):
    """ register(request):
    no return value, called with route_url('apex_register', request)
    """
    title = _('Register')
    came_from = request.params.get('came_from', \
                    route_url(apex_settings('came_from_route'), request))
    velruse_forms = generate_velruse_forms(request, came_from)

    #This fixes the issue with RegisterForm throwing an UnboundLocalError
    if apex_settings('register_form_class'):
        RegisterForm = get_module(apex_settings('register_form_class'))
    else:
        from apex.forms import RegisterForm

    if 'local' not in apex_settings('provider_exclude', []):
        if asbool(apex_settings('use_recaptcha_on_register')):
            if apex_settings('recaptcha_public_key') and apex_settings('recaptcha_private_key'):
                RegisterForm.captcha = RecaptchaField(
                    public_key=apex_settings('recaptcha_public_key'),
                    private_key=apex_settings('recaptcha_private_key'),
                )

        form = RegisterForm(request.POST, captcha={'ip_address': request.environ['REMOTE_ADDR']})
    else:
        form = None

    if request.method == 'POST' and form.validate():
        user = form.save()
        need_verif = apex_settings('need_mail_verification')
        response = HTTPFound(location=came_from)
        if need_verif:
            try:
                DBSession.add(user)
            except:
                pass
            begin_activation_email_process(request, user)
            user.active = 'N'
            DBSession.flush()
            flash(_('User sucessfully created, '
                    'please verify your account by clicking '
                    'on the link in the mail you just received from us !'), 'success')

            response = HTTPFound(location=came_from)
        else:
            transaction.commit()
            headers = apex_remember(request, user.id, internal_user=True)
            response = HTTPFound(location=came_from, headers=headers)
        return response

    return {'title': title,
            'form': form,
            'velruse_forms': velruse_forms,
            'action': 'register'}
예제 #22
0
파일: forms.py 프로젝트: nycynik/apex
    def create_user(self, auth_id, login):
        id = DBSession.query(AuthID).filter(AuthID.id == auth_id).one()
        user = AuthUser(
            login=login,
            password=self.data['password'],
            email=self.data['email'],
        )
        id.users.append(user)
        DBSession.add(user)
        DBSession.flush()

        return user
예제 #23
0
파일: libapex.py 프로젝트: webjunkie01/apex
def apexid_from_token(token):
    """ Returns the apex id from the OpenID Token
    """
    dbsession = DBSession()
    auth = json.loads(dbsession.query(KeyStorage.value). \
                      filter(KeyStorage.key==token).one()[0])
    if 'profile' in auth:
        id = apexid_from_url(auth['profile']['providerName'], \
                             auth['profile']['identifier'])
        auth['apexid'] = id
        return auth
    return None
예제 #24
0
def registrars(request):
    form = RegistrarForm(request.POST)
    registrars = get_registrars()
    record = Registrar()

    if request.method == 'POST' and form.validate():
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        return HTTPFound(location= \
            route_url('apex_route53_registrars', request))
    return {'title': 'Registrars', 'form': form, 'registrars': registrars}
예제 #25
0
def webhosts(request):
    form = ProviderForm(request.POST)
    providers = DBSession.query(Provider).order_by(Provider.name).all()
    record = Provider()

    if request.method == 'POST' and form.validate():
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        return HTTPFound(location= \
            route_url('apex_route53_webhosts', request))
    return {'title': 'Web Hosts', 'form': form, 'providers': providers}
예제 #26
0
파일: libapex.py 프로젝트: webjunkie01/apex
def apexid_from_token(token):
    """ Returns the apex id from the OpenID Token
    """
    dbsession = DBSession()
    auth = json.loads(dbsession.query(KeyStorage.value). \
                      filter(KeyStorage.key==token).one()[0])
    if 'profile' in auth:
        id = apexid_from_url(auth['profile']['providerName'], \
                             auth['profile']['identifier'])
        auth['apexid'] = id
        return auth
    return None
예제 #27
0
파일: forms.py 프로젝트: LeoKudrik/apex
    def create_user(self, auth_id, login):
        id = DBSession.query(AuthID).filter(AuthID.id==auth_id).one()
        user = AuthUser(
            login=login,
            password=self.data['password'],
            email=self.data['email'],
        )
        id.users.append(user)
        DBSession.add(user)
        DBSession.flush()

        return user
예제 #28
0
파일: libapex.py 프로젝트: nicfit/apex
def apex_remember(request, user, max_age=None):
    if asbool(apex_settings('log_logins')):
        if apex_settings('log_login_header'):
            ip_addr = request.environ.get(apex_settings('log_login_header'),
                    'invalid value - apex.log_login_header')
        else:
            ip_addr = str(request.environ['REMOTE_ADDR'])
        record = AuthUserLog(auth_id=user.auth_id, user_id=user.id,
            ip_addr=ip_addr)
        DBSession.add(record)
        DBSession.flush()
    return remember(request, user.auth_id, max_age=max_age)
예제 #29
0
파일: views.py 프로젝트: cd34/apex-route53
def webhosts(request):
    form = ProviderForm(request.POST)
    providers = DBSession.query(Provider).order_by(Provider.name).all()
    record = Provider()

    if request.method == 'POST' and form.validate():
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        return HTTPFound(location= \
            route_url('apex_route53_webhosts', request))
    return {'title':'Web Hosts', 'form':form, 'providers':providers}
예제 #30
0
파일: views.py 프로젝트: cd34/apex-route53
def registrars(request):
    form = RegistrarForm(request.POST)
    registrars = get_registrars()
    record = Registrar()

    if request.method == 'POST' and form.validate():
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        return HTTPFound(location= \
            route_url('apex_route53_registrars', request))
    return {'title':'Registrars', 'form':form, 'registrars':registrars}
예제 #31
0
def apex_remember(request, user, max_age=None):
    if asbool(apex_settings('log_logins')):
        if apex_settings('log_login_header'):
            ip_addr = request.environ.get(apex_settings('log_login_header'), \
                    u'invalid value - apex.log_login_header')
        else:
             ip_addr = unicode(request.environ['REMOTE_ADDR'])
        record = AuthUserLog(auth_id=user.auth_id, user_id=user.id, \
            ip_addr=ip_addr)
        DBSession.add(record)
        DBSession.flush()
    return remember(request, user.auth_id, max_age=max_age)
예제 #32
0
def apex_callback(request):
    """ apex_callback(request):
    no return value, called with route_url('apex_callback', request)

    This is the URL that Velruse returns an OpenID request to
    """
    redir = request.GET.get('came_from', \
                route_url(apex_settings('came_from_route'), request))
    headers = []
    if 'token' in request.POST:
        auth = apexid_from_token(request.POST['token'])
        if auth:
            user = AuthUser.get_by_login(auth['id'])
            if not user:
                auth_info = auth['profile']['accounts'][0]
                id = AuthID()
                DBSession.add(id)
                user = AuthUser(
                    login=auth_info['userid'],
                    provider=auth_info['domain'],
                )
                if auth['profile'].has_key('verifiedEmail'):
                    user.email = auth['profile']['verifiedEmail']
                id.users.append(user)
                if apex_settings('default_user_group'):
                    for name in apex_settings('default_user_group'). \
                                              split(','):
                        group = DBSession.query(AuthGroup). \
                           filter(AuthGroup.name==name.strip()).one()
                        id.groups.append(group)
                if apex_settings('create_openid_after'):
                    openid_after = get_module(
                        apex_settings('create_openid_after'))
                    openid_after().after_signup(user)
                DBSession.flush()
            if apex_settings('openid_required'):
                openid_required = False
                for required in apex_settings('openid_required').split(','):
                    if not getattr(user, required):
                        openid_required = True
                if openid_required:
                    request.session['id'] = id.id
                    request.session['userid'] = user.id
                    return HTTPFound(location='%s?came_from=%s' % \
                        (route_url('apex_openid_required', request), \
                        request.GET.get('came_from', \
                        route_url(apex_settings('came_from_route'), request))))
            headers = apex_remember(request, user)
            redir = request.GET.get('came_from', \
                        route_url(apex_settings('came_from_route'), request))
            flash(_('Successfully Logged in, welcome!'), 'success')
    return HTTPFound(location=redir, headers=headers)
예제 #33
0
파일: views.py 프로젝트: jkoelker/apex
def apex_callback(request):
    """ apex_callback(request):
    no return value, called with route_url('apex_callback', request)

    This is the URL that Velruse returns an OpenID request to
    """
    redir = request.GET.get('came_from', \
                route_url(apex_settings('came_from_route'), request))
    headers = []
    if 'token' in request.POST:
        auth = apexid_from_token(request.POST['token'])
        if auth:
            user = AuthUser.get_by_login(auth['id'])
            if not user:
                auth_info = auth['profile']['accounts'][0]
                id = AuthID()
                DBSession.add(id)
                user = AuthUser(
                    login=auth_info['userid'],
                    provider=auth_info['domain'],
                )
                if auth['profile'].has_key('verifiedEmail'):
                    user.email = auth['profile']['verifiedEmail']
                id.users.append(user)
                if apex_settings('default_user_group'):
                    for name in apex_settings('default_user_group'). \
                                              split(','):
                        group = DBSession.query(AuthGroup). \
                           filter(AuthGroup.name==name.strip()).one()
                        id.groups.append(group)
                if apex_settings('create_openid_after'):
                    openid_after = get_module(apex_settings('create_openid_after'))
                    openid_after().after_signup(user)
                DBSession.flush()
            if apex_settings('openid_required'):
                openid_required = False
                for required in apex_settings('openid_required').split(','):
                    if not getattr(user, required):
                        openid_required = True
                if openid_required:
                    request.session['id'] = id.id
                    request.session['userid'] = user.id
                    return HTTPFound(location='%s?came_from=%s' % \
                        (route_url('apex_openid_required', request), \
                        request.GET.get('came_from', \
                        route_url(apex_settings('came_from_route'), request))))
            headers = apex_remember(request, user)
            redir = request.GET.get('came_from', \
                        route_url(apex_settings('came_from_route'), request))
            flash(_('Successfully Logged in, welcome!'), 'success')
    return HTTPFound(location=redir, headers=headers)
예제 #34
0
    def setUp(self):
        self.config = testing.setUp()
        self.config.add_route('home', '/')
        self.config.add_settings(settings)
        self.config.include('apex')

        connection = self.engine.connect()

        # begin a non-ORM transaction
        self.trans = connection.begin()

        # bind an individual Session to the connection
        DBSession.configure(bind=connection)
        self.session = self.Session(bind=connection)
예제 #35
0
    def setUp(self):
        self.config = testing.setUp()
        self.config.add_route('home', '/')
        self.config.add_settings(settings)
        self.config.include('apex')

        connection = self.engine.connect()

        # begin a non-ORM transaction
        self.trans = connection.begin()

        # bind an individual Session to the connection
        DBSession.configure(bind=connection)
        self.session = self.Session(bind=connection)
예제 #36
0
파일: forms.py 프로젝트: webjunkie01/apex
    def create_user(self, username):
        user = AuthUser(
            username=username,
            password=self.data['password'],
            email=self.data['email'],
        )
        DBSession.add(user)
        settings = get_current_registry().settings
        if settings.has_key('apex.default_user_group'):
            group = DBSession.query(AuthGroup). \
               filter(AuthGroup.name==settings['apex.default_user_group']).one()
            user.groups.append(group)
        DBSession.flush()

        return user
예제 #37
0
 def __call__(self, form, field):
     message = _('"%s" is an already existing group.')
     data = field.data
     item = DBSession.query(AuthGroup).filter(
         AuthGroup.name == data).first()
     if item is not None:
         raise ValidationError(message % field.data)
예제 #38
0
def change_password(request):
    """ change_password(request):
    no return value, called with route_url('apex_change_password', request)
    """
    title = _('Change your Password')

    came_from = get_came_from(request)
    form = ChangePasswordForm(request.POST)

    if request.method == 'POST' and form.validate():
        user = AuthUser.get_by_id(authenticated_userid(request))
        user.password = form.data['password']
        DBSession.merge(user)
        DBSession.flush()
        return HTTPFound(location=came_from)

    return {'title': title, 'form': form, 'action': 'changepass'}
예제 #39
0
파일: views.py 프로젝트: cd34/apex-route53
def ips(request):
    providers = get_providers()
    ips = get_ips()
    if not providers:
        flash('You have no providers defined, please add at least one')
        return HTTPFound(location=route_url('apex_route53_webhosts', request))
    form = IPForm(request.POST, providers=providers)
    form.provider_id.choices = providers
    record = IP()

    if request.method == 'POST' and form.validate():
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        return HTTPFound(location= \
            route_url('apex_route53_ips', request))
    return {'title':'IP Addresses', 'form':form, 'ips':ips}
예제 #40
0
def change_password(request):
    """ change_password(request):
    no return value, called with route_url('apex_change_password', request)
    """
    title = _('Change your Password')

    came_from = get_came_from(request)
    form = ChangePasswordForm(request.POST)

    if request.method == 'POST' and form.validate():
        user = AuthUser.get_by_id(authenticated_userid(request))
        user.password = form.data['password']
        DBSession.merge(user)
        DBSession.flush()
        return HTTPFound(location=came_from)

    return {'title': title, 'form': form, 'action': 'changepass'}
예제 #41
0
def ips(request):
    providers = get_providers()
    ips = get_ips()
    if not providers:
        flash('You have no providers defined, please add at least one')
        return HTTPFound(location=route_url('apex_route53_webhosts', request))
    form = IPForm(request.POST, providers=providers)
    form.provider_id.choices = providers
    record = IP()

    if request.method == 'POST' and form.validate():
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        return HTTPFound(location= \
            route_url('apex_route53_ips', request))
    return {'title': 'IP Addresses', 'form': form, 'ips': ips}
예제 #42
0
    def test_create_user(self):
        # create_user(**kwargs)
        from apex.lib.libapex import create_user
        from apex.models import (AuthUser, DBSession)

        create_user(username='******', password='******')
        # check that auth_id, auth_user, auth_group are added
        self.assertEqual('libtest', DBSession.query(AuthUser.login). \
            filter(AuthUser.login=='libtest').one()[0])
예제 #43
0
def useradd(request):
    """ useradd(request)
    No return value

    Function called from route_url('apex_useradd', request)
    """
    title = _('Create an user')
    velruse_forms = []

    #This fixes the issue with RegisterForm throwing an UnboundLocalError
    if apex_settings('useradd_form_class'):
        UseraddForm = get_module(apex_settings('useradd_form_class'))
    else:
        from apex.forms import UseraddForm
    if 'local' not in apex_settings('provider_exclude', []):
        if asbool(apex_settings('use_recaptcha_on_register')):
            if apex_settings('recaptcha_public_key') and apex_settings(
                    'recaptcha_private_key'):
                UseraddForm.captcha = RecaptchaField(
                    public_key=apex_settings('recaptcha_public_key'),
                    private_key=apex_settings('recaptcha_private_key'),
                )

        form = UseraddForm(
            request.POST,
            captcha={'ip_address': request.environ['REMOTE_ADDR']})
    else:
        form = None
    if request.method == 'POST' and form.validate():
        user = form.save()
        # on creation by an admin, the user must activate itself its account.
        begin_activation_email_process(request, user)
        DBSession.add(user)
        user.active = 'N'
        DBSession.flush()
        flash(
            _('User sucessfully created, An email has been sent '
              'to it\'s email to activate its account.'), 'success')
    return {
        'title': title,
        'form': form,
        'velruse_forms': velruse_forms,
        'action': 'useradd'
    }
예제 #44
0
파일: views.py 프로젝트: nicfit/apex
def activate(request):
    user_id = request.matchdict.get('user_id')
    user = AuthID.get_by_id(user_id)
    submitted_hmac = request.matchdict.get('hmac')
    current_time = time.time()
    time_key = int(base64.b64decode(submitted_hmac[10:]))

    if current_time < time_key:
        hmac_key = get_hmac_key(user, time_key)
        if hmac_key == submitted_hmac[0:10]:
            user.active = 'Y'
            DBSession.merge(user)
            DBSession.flush()
            flash(_('Account activated. Please log in.'))
            return HTTPFound(location=route_url('apex_login',
                                                request))
    flash(_('Invalid request, please try again'))
    return HTTPFound(location=route_url(apex_settings('came_from_route'),
                                        request))
예제 #45
0
    def test_create_user(self):
        # create_user(**kwargs)
        from apex.lib.libapex import create_user
        from apex.models import (AuthUser,
                                 DBSession)

        create_user(username='******', password='******')
        # check that auth_id, auth_user, auth_group are added
        self.assertEqual('libtest', DBSession.query(AuthUser.login). \
            filter(AuthUser.login=='libtest').one()[0])
예제 #46
0
파일: views.py 프로젝트: nicfit/apex
def reset_password(request):
    """ reset_password(request):
    no return value, called with route_url('apex_reset_password', request)
    """
    title = _('Reset My Password')

    if asbool(apex_settings('use_recaptcha_on_reset')):
        if (apex_settings('recaptcha_public_key') and
                apex_settings('recaptcha_private_key')):
            ResetPasswordForm.captcha = RecaptchaField(
                public_key=apex_settings('recaptcha_public_key'),
                private_key=apex_settings('recaptcha_private_key'),
            )
    form = ResetPasswordForm(request.POST,
               captcha={'ip_address': request.environ['REMOTE_ADDR']})
    if request.method == 'POST' and form.validate():
        user_id = request.matchdict.get('user_id')
        user = AuthUser.get_by_id(user_id)
        submitted_hmac = request.matchdict.get('hmac')
        current_time = int(time.time())
        time_key = int(base64.b64decode(submitted_hmac[10:]))
        if current_time < time_key:
            hmac_key = get_hmac_key(user, time_key)
            if hmac_key == submitted_hmac[0:10]:
                #FIXME reset email, no such attribute email
                user.password = form.data['password']
                DBSession.merge(user)
                DBSession.flush()
                flash(_('Password Changed. Please log in.'))
                return HTTPFound(location=route_url('apex_login',
                                                    request))
            else:
                flash(_('Invalid request, please try again'))
                return HTTPFound(location=route_url('apex_forgot',
                                                    request))
        else:
            flash(_('Change request email expired, please try again'))
            return HTTPFound(location=route_url('apex_forgot', request))

    return {'title': title,
            'form': form, 'form_url': request.url,
            "velruse_forms": None}
예제 #47
0
파일: views.py 프로젝트: nicfit/apex
def openid_required(request):
    """ openid_required(request)
    no return value

    If apex_settings.openid_required is set, and the ax/sx from the OpenID
    auth doesn't return the required fields, this is called which builds
    a dynamic form to ask for the missing inforation.

    Called on Registration or Login with OpenID Authentication.
    """
    title = _('OpenID Registration')
    came_from = request.params.get('came_from',
                    route_url(apex_settings('came_from_route'), request))

    # This fixes the issue with RegisterForm throwing an UnboundLocalError
    if apex_settings('openid_register_form_class'):
        OpenIDRequiredForm = get_module(
                apex_settings('openid_register_form_class'))
    else:
        from apex.forms import OpenIDRequiredForm

    for required in apex_settings('openid_required').split(','):
        setattr(OpenIDRequiredForm, required,
            TextField(required, [validators.Required()]))

    form = OpenIDRequiredForm(request.POST,
               captcha={'ip_address': request.environ['REMOTE_ADDR']})

    if request.method == 'POST' and form.validate():
        """
            need to have the AuthUser id that corresponds to the login
            method.
        """
        user = AuthUser.get_by_id(request.session['userid'])
        for required in apex_settings('openid_required').split(','):
            setattr(user, required, form.data[required])
        DBSession.merge(user)
        DBSession.flush()
        headers = apex_remember(request, user)
        return HTTPFound(location=came_from, headers=headers)

    return {'title': title, 'form': form, 'action': 'openid_required'}
예제 #48
0
파일: views.py 프로젝트: nycynik/apex
def openid_required(request):
    """ openid_required(request)
    no return value

    If apex_settings.openid_required is set, and the ax/sx from the OpenID
    auth doesn't return the required fields, this is called which builds
    a dynamic form to ask for the missing information.

    Called on Registration or Login with OpenID Authentication.
    """
    title = _('OpenID Registration')
    came_from = request.params.get('came_from', \
                    route_url(apex_settings('came_from_route'), request))

    #This fixes the issue with RegisterForm throwing an UnboundLocalError
    if apex_settings('openid_register_form_class'):
        OpenIDRequiredForm = get_module(
            apex_settings('openid_register_form_class'))
    else:
        from apex.forms import OpenIDRequiredForm

    for required in apex_settings('openid_required').split(','):
        setattr(OpenIDRequiredForm, required, \
            TextField(required, [validators.Required()]))

    form = OpenIDRequiredForm(request.POST, \
               captcha={'ip_address': request.environ['REMOTE_ADDR']})

    if request.method == 'POST' and form.validate():
        """
            need to have the AuthUser id that corresponds to the login
            method.
        """
        user = AuthUser.get_by_id(request.session['userid'])
        for required in apex_settings('openid_required').split(','):
            setattr(user, required, form.data[required])
        DBSession.merge(user)
        DBSession.flush()
        headers = apex_remember(request, user)
        return HTTPFound(location=came_from, headers=headers)

    return {'title': title, 'form': form, 'action': 'openid_required'}
예제 #49
0
파일: models.py 프로젝트: jbbrokaw/piktio
def copy_game_to_step(game, step):
    """Make a copy of a game object, but only up to the step
    (integer from 1 to 6)"""
    new_game = Game()
    for i in xrange(step):
        attr_name = _STEPS[i] + "_id"
        attached_object = game.__getattribute__(_STEPS[i])
        new_game.__setattr__(attr_name, attached_object.id)
        author = DBSession.query(PiktioProfile)\
            .filter(PiktioProfile.id == attached_object.author_id).one()
        new_game.authors.append(author)
    return new_game
예제 #50
0
def activate(request):
    """
    """
    user_id = request.matchdict.get('user_id')
    user = AuthUser.get_by_id(user_id)
    submitted_hmac = request.matchdict.get('hmac')
    current_time = time.time()
    time_key = int(base64.b64decode(submitted_hmac[10:]))
    if current_time < time_key:
        hmac_key = hmac.new('%s:%s:%d' % (str(user.id), \
                            apex_settings('auth_secret'), time_key), \
                            user.email).hexdigest()[0:10]
        if hmac_key == submitted_hmac[0:10]:
            user.active = 'Y'
            DBSession.merge(user)
            DBSession.flush()
            flash(_('Account activated. Please log in.'))
            return HTTPFound(location=route_url('apex_login', \
                                                request))
    flash(_('Invalid request, please try again'))
    return HTTPFound(location=route_url(apex_settings('came_from_route'), \
                                        request))
예제 #51
0
def useradd(request):
    """ useradd(request)
    No return value

    Function called from route_url('apex_useradd', request)
    """
    title = _('Create an user')
    velruse_forms = []

    #This fixes the issue with RegisterForm throwing an UnboundLocalError
    if apex_settings('useradd_form_class'):
        UseraddForm = get_module(apex_settings('useradd_form_class'))
    else:
        from apex.forms import UseraddForm
    if 'local' not in apex_settings('provider_exclude', []):
        if asbool(apex_settings('use_recaptcha_on_register')):
            if apex_settings('recaptcha_public_key') and apex_settings('recaptcha_private_key'):
                UseraddForm.captcha = RecaptchaField(
                    public_key=apex_settings('recaptcha_public_key'),
                    private_key=apex_settings('recaptcha_private_key'),
                )

        form = UseraddForm(request.POST, captcha={'ip_address': request.environ['REMOTE_ADDR']})
    else:
        form = None
    if request.method == 'POST' and form.validate():
        user = form.save()
        # on creation by an admin, the user must activate itself its account.
        begin_activation_email_process(request, user)
        DBSession.add(user)
        user.active = 'N'
        DBSession.flush()
        flash(_('User sucessfully created, An email has been sent '
                'to it\'s email to activate its account.'), 'success')
    return {'title': title,
            'form': form,
            'velruse_forms': velruse_forms,
            'action': 'useradd'}
예제 #52
0
파일: views.py 프로젝트: nycynik/apex
def reset_password(request):
    """ reset_password(request):
    no return value, called with route_url('apex_reset_password', request)
    """
    title = _('Reset My Password')

    if asbool(apex_settings('use_recaptcha_on_reset')):
        if apex_settings('recaptcha_public_key') and \
            apex_settings('recaptcha_private_key'):
            ResetPasswordForm.captcha = RecaptchaField(
                public_key=apex_settings('recaptcha_public_key'),
                private_key=apex_settings('recaptcha_private_key'),
            )
    form = ResetPasswordForm(request.POST, \
               captcha={'ip_address': request.environ['REMOTE_ADDR']})
    if request.method == 'POST' and form.validate():
        user_id = request.matchdict.get('user_id')
        user = AuthUser.get_by_id(user_id)
        submitted_hmac = request.matchdict.get('hmac')
        current_time = time.time()
        time_key = int(base64.b64decode(submitted_hmac[10:]))
        if current_time < time_key:
            hmac_key = hmac.new('%s:%s:%d' % (str(user.id), \
                                apex_settings('auth_secret'), time_key), \
                                user.email).hexdigest()[0:10]
            if hmac_key == submitted_hmac[0:10]:
                #FIXME reset email, no such attribute email
                user.password = form.data['password']
                DBSession.merge(user)
                DBSession.flush()
                flash(_('Password Changed. Please log in.'))
                return HTTPFound(location=route_url('apex_login', \
                                                    request))
            else:
                flash(_('Invalid request, please try again'))
                return HTTPFound(location=route_url('apex_forgot', \
                                                    request))
    return {'title': title, 'form': form, 'action': 'reset'}
예제 #53
0
파일: views.py 프로젝트: jkoelker/apex
def change_password(request):
    """ change_password(request):
    no return value, called with route_url('apex_change_password', request)
    FIXME doesn't adjust auth_user based on local ID, how do we handle multiple
        IDs that are local? Do we tell person that they don't have local
        permissions?
    """
    title = _('Change your Password')

    came_from = get_came_from(request)
    user = DBSession.query(AuthUser). \
               filter(AuthUser.auth_id==authenticated_userid(request)). \
               filter(AuthUser.provider=='local').first()
    form = ChangePasswordForm(request.POST, user_id=user.id)

    if request.method == 'POST' and form.validate():
        #user = AuthID.get_by_id(authenticated_userid(request))
        user.password = form.data['password']
        DBSession.merge(user)
        DBSession.flush()
        return HTTPFound(location=came_from)

    return {'title': title, 'form': form, 'action': 'changepass'}
예제 #54
0
파일: views.py 프로젝트: nycynik/apex
def change_password(request):
    """ change_password(request):
        no return value, called with route_url('apex_change_password', request)
        FIXME doesn't adjust auth_user based on local ID, how do we handle
        multiple IDs that are local? Do we tell person that they don't have
        local permissions?
    """
    title = _('Change your Password')

    came_from = get_came_from(request)
    user = DBSession.query(AuthUser). \
               filter(AuthUser.auth_id==authenticated_userid(request)). \
               filter(AuthUser.provider=='local').first()
    form = ChangePasswordForm(request.POST, user_id=user.id)

    if request.method == 'POST' and form.validate():
        #user = AuthID.get_by_id(authenticated_userid(request))
        user.password = form.data['password']
        DBSession.merge(user)
        DBSession.flush()
        return HTTPFound(location=came_from)

    return {'title': title, 'form': form, 'action': 'changepass'}
예제 #55
0
def reset_password(request):
    """ reset_password(request):
    no return value, called with route_url('apex_reset_password', request)
    """
    title = _('Reset My Password')

    if asbool(apex_settings('use_recaptcha_on_reset')):
        if apex_settings('recaptcha_public_key') and apex_settings('recaptcha_private_key'):
            ResetPasswordForm.captcha = RecaptchaField(
                public_key=apex_settings('recaptcha_public_key'),
                private_key=apex_settings('recaptcha_private_key'),
            )
    form = ResetPasswordForm(request.POST, \
               captcha={'ip_address': request.environ['REMOTE_ADDR']})
    if request.method == 'POST' and form.validate():
        user_id = request.matchdict.get('user_id')
        user = AuthUser.get_by_id(user_id)
        submitted_hmac = request.matchdict.get('hmac')
        current_time = time.time()
        time_key = int(base64.b64decode(submitted_hmac[10:]))
        if current_time < time_key:
            hmac_key = hmac.new('%s:%s:%d' % (str(user.id), \
                                apex_settings('auth_secret'), time_key), \
                                user.email).hexdigest()[0:10]
            if hmac_key == submitted_hmac[0:10]:
                user.password = form.data['password']
                DBSession.merge(user)
                DBSession.flush()
                flash(_('Password Changed. Please log in.'))
                return HTTPFound(location=route_url('apex_login', \
                                                    request))
            else:
                flash(_('Invalid request, please try again'))
                return HTTPFound(location=route_url('apex_forgot', \
                                                    request))
    return {'title': title, 'form': form, 'action': 'reset'}
예제 #56
0
def apexid_from_token(token):
    """ Returns the apex id from the OpenID Token
    """
    dbsession = DBSession()
    auth = get_velruse_token(token)
    if 'profile' in auth:
        pr = auth['profile']
        name = pr.get('displayName', '')
        auth['name'] = name
        if not name or ('twitter' in pr['accounts'][0]['domain']):
            if not name:
                auth['name'] = pr['accounts'][0]['userid']
            name = pr['accounts'][0]['userid']
        id = apexid_from_url(pr['accounts'], name)
        auth['apexid'] = id
        return auth
    return None
예제 #57
0
파일: libapex.py 프로젝트: nicfit/apex
def create_user(**kwargs):
    """

::

    from apex.lib.libapex import create_user

    create_user(username='******', password='******', active='Y')

    Optional Parameters:

    display_name
    group



    Returns: AuthID object
    """
    auth_id = AuthID(active=kwargs.get('active', 'Y'))
    if 'display_name' in kwargs:
        auth_id.display_name = kwargs['display_name']
        del kwargs['display_name']

    user = AuthUser(login=kwargs['username'], password=kwargs['password'],
               active=kwargs.get('active', 'Y'))
    auth_id.users.append(user)

    if 'group' in kwargs:
        try:
            group = DBSession.query(AuthGroup). \
                    filter(AuthGroup.name == kwargs['group']).one()

            auth_id.groups.append(group)
        except NoResultFound:
            pass

        del kwargs['group']

    for key, value in list(kwargs.items()):
        setattr(user, key, value)

    DBSession.add(auth_id)
    DBSession.add(user)
    DBSession.flush()
    return user
예제 #58
0
def create_user(**kwargs):
    """

::

    from apex.lib.libapex import create_user

    create_user(username='******', password='******', active='Y')

    Optional Parameters:

    display_name
    group



    Returns: AuthID object
    """
    auth_id = AuthID(active=kwargs.get('active', 'Y'))
    if 'display_name' in kwargs:
        auth_id.display_name = kwargs['display_name']
        del kwargs['display_name']

    user = AuthUser(login=kwargs['username'], password=kwargs['password'], \
               active=kwargs.get('active', 'Y'))
    auth_id.users.append(user)

    if 'group' in kwargs:
        try:
            group = DBSession.query(AuthGroup). \
            filter(AuthGroup.name==kwargs['group']).one()

            auth_id.groups.append(group)
        except NoResultFound:
            pass

        del kwargs['group']

    for key, value in kwargs.items():
        setattr(user, key, value)

    DBSession.add(auth_id)
    DBSession.add(user)
    DBSession.flush()
    return user
예제 #59
0
파일: models.py 프로젝트: pablomarti/h
def includeme(config):
    config.include('pyramid_tm')
    config.set_request_property(lambda request: DBSession(), 'db', reify=True)
    config.set_request_property(
        lambda request: AuthID.get_by_id(authenticated_userid(request)),
        'user',
        reify=True)

    settings = config.registry.settings
    initialize_sql(engine_from_config(settings, 'sqlalchemy.'), settings)

    if not config.registry.queryUtility(IAuthorizationPolicy):
        authz_policy = ACLAuthorizationPolicy()
        config.set_authorization_policy(authz_policy)

    if not config.registry.queryUtility(IAuthenticationPolicy):
        auth_secret = settings['h.auth_secret']
        authn_policy = AuthTktAuthenticationPolicy(auth_secret,
                                                   callback=groupfinder)
        config.set_authentication_policy(authn_policy)

    config.set_root_factory(RootFactory)
예제 #60
0
def register(request):
    """ register(request):
    no return value, called with route_url('apex_register', request)
    """
    title = _('Register')
    came_from = request.params.get('came_from', \
                    route_url(apex_settings('came_from_route'), request))
    velruse_forms = generate_velruse_forms(request, came_from)

    #This fixes the issue with RegisterForm throwing an UnboundLocalError
    if apex_settings('register_form_class'):
        RegisterForm = get_module(apex_settings('register_form_class'))
    else:
        from apex.forms import RegisterForm

    if 'local' not in apex_settings('provider_exclude', []):
        if asbool(apex_settings('use_recaptcha_on_register')):
            if apex_settings('recaptcha_public_key') and apex_settings(
                    'recaptcha_private_key'):
                RegisterForm.captcha = RecaptchaField(
                    public_key=apex_settings('recaptcha_public_key'),
                    private_key=apex_settings('recaptcha_private_key'),
                )

        form = RegisterForm(
            request.POST,
            captcha={'ip_address': request.environ['REMOTE_ADDR']})
    else:
        form = None

    if request.method == 'POST' and form.validate():
        user = form.save()
        need_verif = apex_settings('need_mail_verification')
        response = HTTPFound(location=came_from)
        if need_verif:
            try:
                DBSession.add(user)
            except:
                pass
            begin_activation_email_process(request, user)
            user.active = 'N'
            DBSession.flush()
            flash(
                _('User sucessfully created, '
                  'please verify your account by clicking '
                  'on the link in the mail you just received from us !'),
                'success')

            response = HTTPFound(location=came_from)
        else:
            transaction.commit()
            headers = apex_remember(request, user.id, internal_user=True)
            response = HTTPFound(location=came_from, headers=headers)
        return response

    return {
        'title': title,
        'form': form,
        'velruse_forms': velruse_forms,
        'action': 'register'
    }