Exemple #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 not apex_settings('exclude_local'):
        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()

        headers = apex_remember(request, user)
        return HTTPFound(location=came_from, headers=headers)

    return {'title': title, 'form': form, 'velruse_forms': velruse_forms, \
            'action': 'register'}
Exemple #2
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'}
Exemple #3
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'}
Exemple #4
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'}
Exemple #5
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)
Exemple #6
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)
Exemple #7
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 not apex_settings('exclude_local'):
        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():
        if not asbool(apex_settings('email_validate')):
            user = form.save()
            headers = apex_remember(request, user.id)
            return HTTPFound(location=came_from, headers=headers)

        # email activation required.
        user = form.save()
        timestamp = time.time()+3600
        key = '%s:%s:%d' % (str(user.id), \
                                apex_settings('auth_secret'), timestamp)
        hmac_key = hmac.new(key, 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)
        flash(_('Account activation email sent.'))
        return HTTPFound(location=route_url('apex_login', request))

    return {'title': title, 'form': form, 'velruse_forms': velruse_forms, \
            'action': 'register'}
Exemple #8
0
def login(request):
    """ login(request)
    No return value

    Function called from route_url('apex_login', request)
    """
    title = _('You need to login')
    came_from = get_came_from(request)

    if apex_settings('login_form_class'):
        LoginForm = get_module(apex_settings('login_form_class'))
    else:
        from apex.forms import LoginForm

    if not apex_settings('exclude_local'):
        if asbool(apex_settings('use_recaptcha_on_login')):
            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 = LoginForm(request.POST)
    else:
        form = None

    velruse_forms = generate_velruse_forms(request, came_from)

    if request.method == 'POST' and form.validate():
        user = AuthUser.get_by_login(form.data.get('login'))
        if user:
            headers = apex_remember(request, user,
                    max_age=apex_settings('max_cookie_age', None))
            return HTTPFound(location=came_from, headers=headers)

    return {'title': title, 'form': form,
            'velruse_forms': velruse_forms,
            'form_url': request.route_url('apex_login'),
            'action': 'login',
            'came_from': came_from if came_from else None,
           }
Exemple #9
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'
    }
Exemple #10
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():
        """
            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'}
Exemple #11
0
def callback(request):
    user = None
    profile = request.context.profile
    if 'id' not in request.session:
        user = AuthUser.get_by_login(profile['preferredUsername'])
    if not user:
        if 'id' in request.session:
            auth_id = AuthID.get_by_id(request.session['id'])
        else:
            auth_id = AuthID()
            DBSession.add(auth_id)
        user = AuthUser(
            login=profile['preferredUsername'],
            provider=request.context.provider_name,
        )
        if 'verifiedEmail' in profile:
            user.email = profile['verifiedEmail']
        if 'displayName' in profile:
            user.display_name = profile['displayName']
            # TODO: This may not be unique, handle the error here.
        auth_id.users.append(user)
        DBSession.add(user)
        DBSession.flush()
        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()
                auth_id.groups.append(group)
        if apex_settings('create_openid_after'):
            openid_after = get_module(apex_settings('create_openid_after'))
            openid_after().after_signup(request=request, user=user)
        DBSession.flush()
    headers = apex_remember(request, user)
    redir = request.GET.get(
        'came_from',
        request.route_path(
            apex_settings('came_from_route')
        )
    )
    flash(_('Successfully Logged in, welcome!'), 'success')
    return HTTPFound(location=redir, headers=headers)
Exemple #12
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 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'}
Exemple #13
0
def login(request):
    """ login(request)
    No return value

    Function called from route_url('apex_login', request)
    """
    title = _('You need to login')
    came_from = get_came_from(request)

    if apex_settings('login_form_class'):
        LoginForm = get_module(apex_settings('login_form_class'))
    else:
        from apex.forms import LoginForm

    if not apex_settings('exclude_local'):
        if asbool(apex_settings('use_recaptcha_on_login')):
            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 = LoginForm(request.POST)
    else:
        form = None

    velruse_forms = generate_velruse_forms(request, came_from)

    if request.method == 'POST' and form.validate():
        user = AuthUser.get_by_login(form.data.get('login'))
        if user:
            headers = apex_remember(request, user, \
                max_age=apex_settings('max_cookie_age', None))
            return HTTPFound(location=came_from, headers=headers)

    return {'title': title, 'form': form, 'velruse_forms': velruse_forms, \
            'form_url': request.route_url('apex_login'),
            'action': 'login'}
Exemple #14
0
def add_auth(request):
    title = _('Add another Authentication method')
    came_from = request.params.get('came_from', \
                    route_url(apex_settings('came_from_route'), request))
    auth_id = authenticated_userid(request)
    request.session['id'] = auth_id
    auth_providers = apex_id_providers(auth_id)
    exclude = set([])
    if not apex_settings('allow_duplicate_providers'):
        exclude = set([x.split('.')[0] for x in auth_providers])

    velruse_forms = generate_velruse_forms(request, came_from, exclude)

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

    form = None
    if not apex_settings('exclude_local') and 'local' not in exclude:
        if not asbool(apex_settings('use_recaptcha_on_auth')):
            if apex_settings('recaptcha_public_key') and \
                apex_settings('recaptcha_private_key'):
                AddAuthForm.captcha = RecaptchaField(
                    public_key=apex_settings('recaptcha_public_key'),
                    private_key=apex_settings('recaptcha_private_key'),
                )

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

    if request.method == 'POST' and form.validate():
        form.save(auth_id)

        return HTTPFound(location=came_from)

    return {'title': title, 'form': form, 'velruse_forms': velruse_forms, \
            'action': 'add_auth'}
Exemple #15
0
def add_auth(request):
    title = _('Add another Authentication method')
    came_from = request.params.get('came_from', \
                    route_url(apex_settings('came_from_route'), request))
    auth_id = authenticated_userid(request)
    request.session['id'] = auth_id
    auth_providers = apex_id_providers(auth_id)
    exclude = set([])
    if not apex_settings('allow_duplicate_providers'):
        exclude = set([x.split('.')[0] for x in auth_providers])

    velruse_forms = generate_velruse_forms(request, came_from, exclude)

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

    form = None
    if not apex_settings('exclude_local') and 'local' not in exclude:
        if not asbool(apex_settings('use_recaptcha_on_auth')):
            if apex_settings('recaptcha_public_key') and \
                apex_settings('recaptcha_private_key'):
                AddAuthForm.captcha = RecaptchaField(
                    public_key=apex_settings('recaptcha_public_key'),
                    private_key=apex_settings('recaptcha_private_key'),
                )

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

    if request.method == 'POST' and form.validate():
        form.save(auth_id)

        return HTTPFound(location=came_from)

    return {'title': title, 'form': form, 'velruse_forms': velruse_forms, \
            'action': 'add_auth'}
Exemple #16
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()

        headers = apex_remember(request, user.id)
        return HTTPFound(location=came_from, headers=headers)

    return {'title': title, 'form': form, 'velruse_forms': velruse_forms, \
            'action': 'register'}
Exemple #17
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'}
Exemple #18
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)
Exemple #19
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'
    }
Exemple #20
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)