示例#1
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'}
示例#2
0
def apex_remember(request, user_id, external_user=False, internal_user=False):
    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,
                             external_user=external_user,
                             internal_user=internal_user)
        DBSession.add(record)
        DBSession.flush()
    return remember(request, user_id)
示例#3
0
def apex_remember(request, user_id, external_user=False, internal_user=False):
    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,
                             external_user=external_user,
                             internal_user=internal_user)
        DBSession.add(record)
        DBSession.flush()
    return remember(request, user_id)
示例#4
0
def generate_velruse_forms(request, came_from):
    """ Generates variable form based on OpenID providers
    offered by the velruse backend.
    XXX: If the method is too heavy, please cache it a while.
    """
    velruse_forms = []
    configs = get_providers()
    for vprovider in configs:
        provider = vprovider.replace('velruse.',
                                     '').replace('providers.', '').replace(
                                         'openidconsumer', 'openid')
        if 'ldap' in provider:
            continue
        infos = configs[vprovider]
        if provider_forms.has_key(provider):
            form = provider_forms[provider](
                end_point='%s?csrf_token=%s&came_from=%s' %
                (request.route_url('apex_callback'),
                 request.session.get_csrf_token(), came_from),
                csrf_token=request.session.get_csrf_token(),
            )
            keys = ['process', 'login']
            for key in keys:
                if key in infos:
                    setattr(form, 'velruse_%s' % key, infos[key])
            if provider == 'facebook':
                form.scope.data = apex_settings('velruse_facebook_scope')

            velruse_forms.append(form)
    return velruse_forms
示例#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
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'}
示例#7
0
def generate_velruse_forms(request, came_from):
    """ Generates variable form based on OpenID providers
    offered by the velruse backend.
    XXX: If the method is too heavy, please cache it a while.
    """
    velruse_forms = []
    configs = get_providers()
    for vprovider in configs:
        provider = vprovider.replace(
            'velruse.', '').replace(
                'providers.', '').replace(
                    'openidconsumer', 'openid')
        if 'ldap' in provider:
            continue
        infos = configs[vprovider]
        if provider_forms.has_key(provider):
            form = provider_forms[provider](
                end_point='%s?csrf_token=%s&came_from=%s' % (
                    request.route_url('apex_callback'),
                    request.session.get_csrf_token(),
                    came_from),
                csrf_token = request.session.get_csrf_token(),
            )
            keys = ['process', 'login']
            for key in keys:
                if key in infos:
                    setattr(form, 'velruse_%s' % key, infos[key])
            if provider == 'facebook':
                form.scope.data = apex_settings('velruse_facebook_scope')

            velruse_forms.append(form)
    return velruse_forms
示例#8
0
def begin_activation_email_process(request, user):
    timestamp = time.time() + 3600
    hmac_key = hmac.new(
        '%s:%s:%d' % (str(user.id), apex_settings('auth_secret'), timestamp),
        user.email).hexdigest()[0:10]
    time_key = base64.urlsafe_b64encode('%d' % timestamp)
    email_hash = '%s%s' % (hmac_key, time_key)
    apex_email_activate(request, user.id, user.email, email_hash)
示例#9
0
def begin_activation_email_process(request, user):
    timestamp = time.time()+3600
    hmac_key = hmac.new('%s:%s:%d' % (
        str(user.id),
        apex_settings('auth_secret'),
        timestamp),
        user.email).hexdigest()[0:10]
    time_key = base64.urlsafe_b64encode('%d' % timestamp)
    email_hash = '%s%s' % (hmac_key, time_key)
    apex_email_activate(request, user.id, user.email, email_hash)
示例#10
0
def apex_email_activate(request, user_id, email, hmac):
    message_class_name = get_module(apex_settings('email_message_text', \
                             'apex.lib.libapex.EmailMessageText'))
    message_class = message_class_name()
    message_text = getattr(message_class, 'activate')()
    message_body = translate(request, message_text['body']).replace('%_url_%', \
        route_url('apex_activate', request, user_id=user_id, hmac=hmac))

    apex_email(request, email, translate(request, message_text['subject']),
               translate(request, message_body))
示例#11
0
def apex_email_activate(request, user_id, email, hmac):
    message_class_name = get_module(apex_settings('email_message_text', \
                             'apex.lib.libapex.EmailMessageText'))
    message_class = message_class_name()
    message_text = getattr(message_class, 'activate')()
    message_body = translate(request, message_text['body']).replace('%_url_%', \
        route_url('apex_activate', request, user_id=user_id, hmac=hmac))

    apex_email(request, email,
               translate(request, message_text['subject']),
               translate(request, message_body))
示例#12
0
def apex_email(request, recipients, subject, body, sender=None):
    """ Sends email message
    """
    mailer = get_mailer(request)
    if not sender:
        sender = apex_settings('sender_email')
        if not sender:
            sender = '*****@*****.**'
    message = Message(subject=subject,
                  sender=sender,
                  recipients=[recipients],
                  body=body)
    mailer.send(message)
示例#13
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))
示例#14
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))
示例#15
0
def apex_email(request, recipients, subject, body, sender=None):
    """ Sends email message
    """
    mailer = get_mailer(request)
    if not sender:
        sender = apex_settings('sender_email')
        if not sender:
            sender = '*****@*****.**'
    message = Message(subject=subject,
                      sender=sender,
                      recipients=[recipients],
                      body=body)
    mailer.send(message)
示例#16
0
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():
        user = AuthUser.get_by_id(request.session['id'])
        for required in apex_settings('openid_required').split(','):
            setattr(user, required, form.data[required])
        DBSession.merge(user)
        DBSession.flush()
        headers = apex_remember(request, user.id, external_user=True)
        return HTTPFound(location=came_from, headers=headers)

    return {'title': title, 'form': form, 'action': 'openid_required'}
示例#17
0
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():
        user = AuthUser.get_by_id(request.session['id'])
        for required in apex_settings('openid_required').split(','):
            setattr(user, required, form.data[required])
        DBSession.merge(user)
        DBSession.flush()
        headers = apex_remember(request, user.id, external_user=True)
        return HTTPFound(location=came_from, headers=headers)

    return {'title': title, 'form': form, 'action': 'openid_required'}
示例#18
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'
    }
示例#19
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'}
示例#20
0
def forgot_password(request):
    """ forgot_password(request):
    no return value, called with route_url('apex_forgot_password', request)
    """
    title = _('Forgot my password')

    if asbool(apex_settings('use_recaptcha_on_forgot')):
        if apex_settings('recaptcha_public_key') and apex_settings(
                'recaptcha_private_key'):
            ForgotForm.captcha = RecaptchaField(
                public_key=apex_settings('recaptcha_public_key'),
                private_key=apex_settings('recaptcha_private_key'),
            )
    form = ForgotForm(request.POST, \
               captcha={'ip_address': request.environ['REMOTE_ADDR']})
    if request.method == 'POST' and form.validate():
        """ Special condition - if email imported from OpenID/Auth, we can
            direct the person to the appropriate login through a flash
            message.
        """
        if form.data['email']:
            user = AuthUser.get_by_email(form.data['email'])
            if user.login:
                provider_name = auth_provider.get(user.login[1], 'Unknown')
                flash(_('You used %s as your login provider' % \
                     provider_name))
                return HTTPFound(location=route_url('apex_login', \
                                          request))
        if form.data['username']:
            user = AuthUser.get_by_username(form.data['username'])
        if user:
            timestamp = time.time() + 3600
            hmac_key = hmac.new('%s:%s:%d' % (str(user.id), \
                                apex_settings('auth_secret'), timestamp), \
                                user.email).hexdigest()[0:10]
            time_key = base64.urlsafe_b64encode('%d' % timestamp)
            email_hash = '%s%s' % (hmac_key, time_key)
            apex_email_forgot(request, user.id, user.email, email_hash)
            flash(_('Password Reset email sent.'))
            return HTTPFound(location=route_url('apex_login', \
                                                request))
        flash(_('An error occurred, please contact the support team.'))
    return {'title': title, 'form': form, 'action': 'forgot'}
示例#21
0
def forgot_password(request):
    """ forgot_password(request):
    no return value, called with route_url('apex_forgot_password', request)
    """
    title = _('Forgot my password')

    if asbool(apex_settings('use_recaptcha_on_forgot')):
        if apex_settings('recaptcha_public_key') and apex_settings('recaptcha_private_key'):
            ForgotForm.captcha = RecaptchaField(
                public_key=apex_settings('recaptcha_public_key'),
                private_key=apex_settings('recaptcha_private_key'),
            )
    form = ForgotForm(request.POST, \
               captcha={'ip_address': request.environ['REMOTE_ADDR']})
    if request.method == 'POST' and form.validate():
        """ Special condition - if email imported from OpenID/Auth, we can
            direct the person to the appropriate login through a flash
            message.
        """
        if form.data['email']:
            user = AuthUser.get_by_email(form.data['email'])
            if user.login:
                provider_name = auth_provider.get(user.login[1], 'Unknown')
                flash(_('You used %s as your login provider' % \
                     provider_name))
                return HTTPFound(location=route_url('apex_login', \
                                          request))
        if form.data['username']:
            user = AuthUser.get_by_username(form.data['username'])
        if user:
            timestamp = time.time()+3600
            hmac_key = hmac.new('%s:%s:%d' % (str(user.id), \
                                apex_settings('auth_secret'), timestamp), \
                                user.email).hexdigest()[0:10]
            time_key = base64.urlsafe_b64encode('%d' % timestamp)
            email_hash = '%s%s' % (hmac_key, time_key)
            apex_email_forgot(request, user.id, user.email, email_hash)
            flash(_('Password Reset email sent.'))
            return HTTPFound(location=route_url('apex_login', \
                                                request))
        flash(_('An error occurred, please contact the support team.'))
    return {'title': title, 'form': form, 'action': 'forgot'}
示例#22
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'}
示例#23
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'}
示例#24
0
 def validate_email(form, field):
     need_verif = apex_settings('need_mail_verification')
     if need_verif and not field.data:
         raise validators.ValidationError(
             _('Sorry but you need to input an email.'))
示例#25
0
def get_came_from(request):
    return request.GET.get('came_from',
                           request.POST.get(
                               'came_from',
                               route_url(apex_settings('came_from_route'), request))
                          )
示例#26
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'
    }
示例#27
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 = []
    login_failed = True
    reason = _('Login failed!')
    if 'token' in request.POST:
        token = request.POST['token']
        auth = apexid_from_token(token)
        if auth:
            login_failed = False
            user, email = None, ''
            if 'emails' in  auth['profile']:
                emails = auth['profile']['emails']
                if isinstance(emails[0], dict):
                    email = auth['profile']['emails'][0]['value']
                else:
                    email = auth['profile']['emails'][0]
            else:
                email = auth['profile'].get('verifiedEmail', '').strip()
            # first try by email
            if email:
                user = AuthUser.get_by_email(email)
            # then by id
            if user is None:
                user = search_user(auth['apexid'])
            if not user:
                user_infos = {'login': auth['apexid'], 'username': auth['name']}
                if email:
                    user_infos['email'] = email
                user = create_user(**user_infos)
                if apex_settings('create_openid_after'):
                    openid_after = get_module(apex_settings('create_openid_after'))
                    request = openid_after().after_signup(request, user)
            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'] = 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))))
            using_ldap = 'ldap' in [a.get('domain', '') 
                                    for a in auth.get(
                                        "profile", {}).get("accounts", [])]
            external_user = True
            internal_user = using_ldap
            headers = apex_remember(request, user.id, 
                                    internal_user=internal_user, 
                                    external_user=external_user)
            redir = request.GET.get('came_from', \
                        route_url(apex_settings('came_from_route'), request))
            flash(_('Successfully Logged in, welcome!'), 'success')
        else:
            auth = get_velruse_token(token)
            reasont = ''
            if auth.get('code', None):
                reasont += 'Code %s : ' % auth['code']
            if auth.get('description', ''):
                reasont += _(auth['description'])
            if reasont:
                reason = reasont
            login_failed = True
    if login_failed:
        flash(reason)
    return HTTPFound(location=redir, headers=headers)
示例#28
0
def query_velruse_host(query):
    vurl = apex_settings('velruse_url')
    auth_url = '%s/%s' % (vurl, query)
    req = urllib2.Request(auth_url, None, {'user-agent': 'auth/apex'})
    configs = json.loads(urllib2.urlopen(req).read())
    return configs
示例#29
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 = []
    login_failed = True
    reason = _('Login failed!')
    if 'token' in request.POST:
        token = request.POST['token']
        auth = apexid_from_token(token)
        if auth:
            login_failed = False
            user, email = None, ''
            if 'emails' in auth['profile']:
                emails = auth['profile']['emails']
                if isinstance(emails[0], dict):
                    email = auth['profile']['emails'][0]['value']
                else:
                    email = auth['profile']['emails'][0]
            else:
                email = auth['profile'].get('verifiedEmail', '').strip()
            # first try by email
            if email:
                user = AuthUser.get_by_email(email)
            # then by id
            if user is None:
                user = search_user(auth['apexid'])
            if not user:
                user_infos = {
                    'login': auth['apexid'],
                    'username': auth['name']
                }
                if email:
                    user_infos['email'] = email
                user = create_user(**user_infos)
                if apex_settings('create_openid_after'):
                    openid_after = get_module(
                        apex_settings('create_openid_after'))
                    request = openid_after().after_signup(request, user)
            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'] = 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))))
            using_ldap = 'ldap' in [
                a.get('domain', '')
                for a in auth.get("profile", {}).get("accounts", [])
            ]
            external_user = True
            internal_user = using_ldap
            headers = apex_remember(request,
                                    user.id,
                                    internal_user=internal_user,
                                    external_user=external_user)
            redir = request.GET.get('came_from', \
                        route_url(apex_settings('came_from_route'), request))
            flash(_('Successfully Logged in, welcome!'), 'success')
        else:
            auth = get_velruse_token(token)
            reasont = ''
            if auth.get('code', None):
                reasont += 'Code %s : ' % auth['code']
            if auth.get('description', ''):
                reasont += _(auth['description'])
            if reasont:
                reason = reasont
            login_failed = True
    if login_failed:
        flash(reason)
    return HTTPFound(location=redir, headers=headers)
示例#30
0
def login(request):
    """ login(request)
    No return value

    Function called from route_url('apex_login', request)
    """
    if request.user:
        if 'came_from' in request.params:
            return HTTPFound(location=request.params['came_from'])
    title = _('You need to login')
    came_from = get_came_from(request)
    velruse_forms = generate_velruse_forms(request, came_from)
    providers = get_providers()
    use_captcha = asbool(apex_settings('use_recaptcha_on_login'))
    if 'local' not in apex_settings('provider_exclude', []):
        if use_captcha:
            if apex_settings('recaptcha_public_key') and apex_settings('recaptcha_private_key'):
                LoginForm.captcha = RecaptchaField(
                    public_key=apex_settings('recaptcha_public_key'),
                    private_key=apex_settings('recaptcha_private_key'),
                )
        form = LoginForm(request.POST,
                         captcha={'ip_address': request.environ['REMOTE_ADDR']})
    else:
        form = None

    for vform in velruse_forms:
        if getattr(vform, 'velruse_login', None):
            vform.action = vform.velruse_login

    # allow to include this as a portlet inside other pages
    if (request.method == 'POST'
        and (request.route_url('apex_login') in request.url)):
        local_status = form.validate()
        username = form.data.get('username')
        password = form.data.get('password')
        user = search_user(username)
        if local_status and user:
            if user.active == 'Y':
                headers = apex_remember(request, user.id, internal_user=True)
                return HTTPFound(location=came_from, headers=headers)
        else:
            stop = False
            if use_captcha:
                if 'captcha' in form.errors:
                    stop = True
                    form.came_from.data = came_from
                    form.data['came_from'] = came_from
            if not stop:
                end_point='%s?%s' % (
                    request.route_url('apex_callback'),
                    urlencode(dict(
                        csrf_token=request.session.get_csrf_token(),
                        came_from=came_from,
                    ))
                )
                # try ldap auth if present on velruse
                # idea is to let the browser to the request with
                # an autosubmitted form
                if 'velruse.providers.ldapprovider' in providers:
                    response = AUTOSUBMITED_VELRUSE_LDAP_FORM%(
                        providers['velruse.providers.ldapprovider']['login'],
                        end_point,
                        username,
                        password)
                    return Response(response)

    if not came_from:
        came_from = request.url
    form.came_from.data = came_from

    return {'title': title,
            'form': form,
            'velruse_forms': velruse_forms,
            'form_url': request.route_url('apex_login'),
            'action': 'login'}
示例#31
0
def get_came_from(request):
    return request.GET.get(
        'came_from',
        request.POST.get('came_from',
                         route_url(apex_settings('came_from_route'), request)))
示例#32
0
    message_text = getattr(message_class, 'activate')()
    message_body = translate(request, message_text['body']).replace('%_url_%', \
        route_url('apex_activate', request, user_id=user_id, hmac=hmac))

    apex_email(request, email, translate(request, message_text['subject']),
               translate(request, message_body))


def get_providers():
    logger = logging.getLogger('apex.generate_velruse_forms')
    configs = {}
    try:
        configs = query_velruse_host('auth_providers_list')
    except Exception, e:
        logger.error('Error while gettings providers from velruse: %s' % e)
    if apex_settings('provider_exclude'):
        for provider in apex_settings('provider_exclude').split(','):
            if provider.strip() in configs:
                configs.remove(provider.strip())
    return configs


def generate_velruse_forms(request, came_from):
    """ Generates variable form based on OpenID providers
    offered by the velruse backend.
    XXX: If the method is too heavy, please cache it a while.
    """
    velruse_forms = []
    configs = get_providers()
    for vprovider in configs:
        provider = vprovider.replace('velruse.',
示例#33
0
    message_body = translate(request, message_text['body']).replace('%_url_%', \
        route_url('apex_activate', request, user_id=user_id, hmac=hmac))

    apex_email(request, email,
               translate(request, message_text['subject']),
               translate(request, message_body))


def get_providers():
    logger = logging.getLogger('apex.generate_velruse_forms')
    configs = {}
    try:
        configs = query_velruse_host('auth_providers_list')
    except Exception, e:
        logger.error('Error while gettings providers from velruse: %s' % e)
    if apex_settings('provider_exclude'):
        for provider in apex_settings('provider_exclude').split(','):
            if provider.strip() in configs:
                configs.remove(provider.strip())
    return configs

def generate_velruse_forms(request, came_from):
    """ Generates variable form based on OpenID providers
    offered by the velruse backend.
    XXX: If the method is too heavy, please cache it a while.
    """
    velruse_forms = []
    configs = get_providers()
    for vprovider in configs:
        provider = vprovider.replace(
            'velruse.', '').replace(
示例#34
0
def query_velruse_host(query):
    vurl = apex_settings('velruse_url')
    auth_url = '%s/%s' %( vurl, query)
    req = urllib2.Request(auth_url, None, {'user-agent':'auth/apex'})
    configs = json.loads(urllib2.urlopen(req).read())
    return configs
示例#35
0
def login(request):
    """ login(request)
    No return value

    Function called from route_url('apex_login', request)
    """
    if request.user:
        if 'came_from' in request.params:
            return HTTPFound(location=request.params['came_from'])
    title = _('You need to login')
    came_from = get_came_from(request)
    velruse_forms = generate_velruse_forms(request, came_from)
    providers = get_providers()
    use_captcha = asbool(apex_settings('use_recaptcha_on_login'))
    if 'local' not in apex_settings('provider_exclude', []):
        if use_captcha:
            if apex_settings('recaptcha_public_key') and apex_settings(
                    'recaptcha_private_key'):
                LoginForm.captcha = RecaptchaField(
                    public_key=apex_settings('recaptcha_public_key'),
                    private_key=apex_settings('recaptcha_private_key'),
                )
        form = LoginForm(
            request.POST,
            captcha={'ip_address': request.environ['REMOTE_ADDR']})
    else:
        form = None

    for vform in velruse_forms:
        if getattr(vform, 'velruse_login', None):
            vform.action = vform.velruse_login

    # allow to include this as a portlet inside other pages
    if (request.method == 'POST'
            and (request.route_url('apex_login') in request.url)):
        local_status = form.validate()
        username = form.data.get('username')
        password = form.data.get('password')
        user = search_user(username)
        if local_status and user:
            if user.active == 'Y':
                headers = apex_remember(request, user.id, internal_user=True)
                return HTTPFound(location=came_from, headers=headers)
        else:
            stop = False
            if use_captcha:
                if 'captcha' in form.errors:
                    stop = True
                    form.came_from.data = came_from
                    form.data['came_from'] = came_from
            if not stop:
                end_point = '%s?%s' % (
                    request.route_url('apex_callback'),
                    urlencode(
                        dict(
                            csrf_token=request.session.get_csrf_token(),
                            came_from=came_from,
                        )))
                # try ldap auth if present on velruse
                # idea is to let the browser to the request with
                # an autosubmitted form
                if 'velruse.providers.ldapprovider' in providers:
                    response = AUTOSUBMITED_VELRUSE_LDAP_FORM % (
                        providers['velruse.providers.ldapprovider']['login'],
                        end_point, username, password)
                    return Response(response)

    if not came_from:
        came_from = request.url
    form.came_from.data = came_from

    return {
        'title': title,
        'form': form,
        'velruse_forms': velruse_forms,
        'form_url': request.route_url('apex_login'),
        'action': 'login'
    }
示例#36
0
 def validate_email(form, field):
     need_verif = apex_settings('need_mail_verification')
     if need_verif and not field.data:
         raise validators.ValidationError(_('Sorry but you need to input an email.'))