Ejemplo n.º 1
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))
Ejemplo n.º 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'}
Ejemplo n.º 3
0
def managegroups(request):
    params = {'action': 'manage_groups', 'form': None}
    form, session = None, DBSession
    is_a_post = request.method == 'POST'
    adding = 'groupname' in request.POST
    deleting = request.params.get('group_action', '') == 'delete'
    settings = request.registry.settings
    default_groups_names = [a[0] for a in get_default_groups(settings)]
    if is_a_post and deleting:
        items = [a[1] for a in request.POST.items() if a[0] == 'delete']

        todelete = session.query(AuthGroup).filter(
            se.and_(AuthGroup.id.in_(items),
                    se.not_(AuthGroup.name.in_(default_groups_names)))).all()
        noecho = [session.delete(i) for i in todelete]
        request.session.flash(
            _('Groups %s have been deleted') %
            (', '.join([a.name for a in todelete])), 'info')
    add_form = GroupForm(request.POST)
    if is_a_post and adding:
        if add_form.validate():
            try:
                group = add_form.save()
                add_form = GroupForm()
                flash(_('Added group : %s' % group.name, 'info'))
            except Exception, e:
                flash(_('Problem adding group : %s' % e, 'error'))
Ejemplo n.º 4
0
class DomainForm(ExtendedForm):
    profile_id = SelectField(_('Profile'), coerce=int)
    ip_id = SelectField(_('IP Addresses'), coerce=int)
    domain = TextField(_('Domain'), [validators.Required(), \
                         validators.Length(min=4, max=64), \
                         validators.Regexp(domain_re, \
                         message=_('invalid domain'))])
Ejemplo n.º 5
0
class ForgotForm(ExtendedForm):
    login = TextField(_('Username'), [validators.Optional()])
    label = HiddenField(label='Or')
    email = TextField(_('Email Address'), [validators.Optional(), \
                                           validators.Email()])
    label = HiddenField(label='')
    label = HiddenField(label=_('If your username and email weren\'t found, ' \
                              'you may have logged in with a login ' \
                              'provider and didn\'t set your email ' \
                              'address.'))
    """ I realize the potential issue here, someone could continuously
        hit the page to find valid username/email combinations and leak
        information, however, that is an enhancement that will be added
        at a later point.
    """
    def validate_login(form, field):
        if AuthUser.get_by_login(field.data) is None:
            raise validators.ValidationError(
                _('Sorry that username doesn\'t exist.'))

    def validate_email(form, field):
        if AuthUser.get_by_email(field.data) is None:
            raise validators.ValidationError(
                _('Sorry that email doesn\'t exist.'))

    def clean(self):
        errors = []
        if not self.data.get('login') and not self.data.get('email'):
            errors.append(_('You need to specify either a Username or ' \
                            'Email address'))
        return errors
Ejemplo n.º 6
0
class RegistrarForm(ExtendedForm):
    """ Registrar Form
    """
    registrar = TextField(_('Registrar'), [validators.Required(), \
                         validators.Length(min=4, max=25)])
    url = TextField(_('URL'), [validators.Required(), \
                         validators.Length(min=4, max=80)])
Ejemplo n.º 7
0
class GroupForm(ExtendedForm):
    """ Registration Form
    """
    groupname = TextField(_('Group name'), [
        validators.Required(),
        GroupValidator(),
        validators.Length(min=4, max=25)
    ])
    description = TextField(
        _('Description'),
        [validators.Required(),
         validators.Length(min=4, max=2500)])

    def save(self):
        infos = {
            'description': self.data.get('description', ''),
            'name': self.data.get('groupname', ''),
        }
        new_group = create_group(**infos)
        self.after_signup(new_group)
        return new_group

    def after_signup(self, user, **kwargs):
        """ Function to be overloaded and called after form submission
        to allow you the ability to save additional form data or perform
        extra actions after the form submission.
        """
        pass
Ejemplo n.º 8
0
def managegroups(request):
    params = {'action': 'manage_groups', 'form': None}
    form, session = None, DBSession
    is_a_post = request.method == 'POST'
    adding = 'groupname' in request.POST
    deleting = request.params.get('group_action', '') == 'delete'
    settings = request.registry.settings
    default_groups_names = [a[0] 
                            for a in get_default_groups(settings)] 
    if is_a_post and deleting:
        items = [a[1]
                 for a in request.POST.items()
                 if a[0] == 'delete']

        todelete = session.query( AuthGroup).filter(
            se.and_(
                AuthGroup.id.in_(items),
                se.not_(AuthGroup.name.in_(default_groups_names))
            )).all()
        noecho = [session.delete(i) for i in todelete]
        request.session.flash(_('Groups %s have been deleted') % (
            ', '.join([a.name for a in todelete])), 'info')
    add_form = GroupForm(request.POST)
    if is_a_post and adding:
        if add_form.validate():
            try:
                group = add_form.save()
                add_form = GroupForm()
                flash(_('Added group : %s' % group.name, 'info'))
            except Exception, e:
                flash(_('Problem adding group : %s' % e, 'error'))
Ejemplo n.º 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'}
Ejemplo n.º 10
0
class IPForm(ExtendedForm):
    """ Registrar Form
    """
    ip_address = TextField(_('IP Address'), [validators.Required(), \
        validators.Length(min=4, max=60)])
    provider_id = SelectField(_('Web Host'), [validators.Required()], \
        coerce=int)
    note = TextField(_('Note'))
Ejemplo n.º 11
0
class ProviderForm(ExtendedForm):
    """ Registrar Form
    """
    name = TextField(_('Web Host'), [validators.Required(), \
                         validators.Length(min=4, max=25)])
    url = TextField(_('URL'), [validators.Required(), \
                         validators.Length(min=4, max=80)])
    os = SelectField(_('Operating System'), [validators.Required()],
                     choices=[('1', 'Debian')])
Ejemplo n.º 12
0
class ProfileRecordForm(ExtendedForm):
    """ Profile Record Form
    """
    record_type = SelectField(_('Record Type'), [validators.Required()],
                              choices=[('A', 'A'), ('MX', 'MX'),
                                       ('SPF', 'SPF'), ('TXT', 'TXT')])
    name = TextField(_('Hostname'))
    contents = TextField(_('Contents'), [validators.Required(), \
                         validators.Length(min=4, max=25)])
Ejemplo n.º 13
0
class LoginForm(ExtendedForm):
    login = TextField(_('Username'), validators=[validators.Required()])
    password = PasswordField(_('Password'), validators=[validators.Required()])

    def clean(self):
        errors = []
        if not AuthUser.check_password(login=self.data.get('login'), \
                                       password=self.data.get('password')):
            errors.append(_('Login Error -- please try again'))
        return errors
Ejemplo n.º 14
0
class DNS_A_Form(ExtendedForm):
    """ 
    """
    name = TextField(_('Name'))
    type = SelectField(_('Record Type'), [validators.Required()],
                       choices=[('A', 'A - IPv4 Address')])
    alias = RadioField(_('Alias'), [validators.Required()],
                       choices=[('Y', 'Yes'), ('N', 'No')])
    ttl = TextField(_('TTL'))
    value = SelectMultipleField(_('IP Addresses'))
Ejemplo n.º 15
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'}
Ejemplo n.º 16
0
class ChangePasswordForm(ExtendedForm):
    """ Change Password Form
    """
    old_password = PasswordField(_('Old Password'), [validators.Required()])
    password = PasswordField(_('New Password'), [validators.Required(), \
                             validators.EqualTo('password2', \
                             message=_('Passwords must match'))])
    password2 = PasswordField(_('Repeat New Password'), [validators.Required()])

    def validate_old_password(form, field):
        request = get_current_request()
        if not AuthUser.check_password(id=authenticated_userid(request), \
                                       password=field.data):
            raise validators.ValidationError(_('Your old password doesn\'t match'))
Ejemplo n.º 17
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'}
Ejemplo n.º 18
0
class RegisterForm(ExtendedForm):
    """ Registration Form
    """
    login = TextField(_('Username'), [validators.Required(), \
                         validators.Length(min=4, max=25)])
    password = PasswordField(_('Password'), [validators.Required(), \
                             validators.EqualTo('password2', \
                             message=_('Passwords must match'))])
    password2 = PasswordField(_('Repeat Password'), [validators.Required()])
    email = TextField(_('Email Address'), [validators.Required(), \
                      validators.Email()])

    def validate_login(form, field):
        if AuthUser.get_by_login(field.data) is not None:
            raise validators.ValidationError(
                _('Sorry that username already exists.'))

    def create_user(self, login):
        id = AuthID()
        DBSession.add(id)
        user = AuthUser(
            login=login,
            password=self.data['password'],
            email=self.data['email'],
        )
        id.users.append(user)
        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()
            id.groups.append(group)
        DBSession.flush()

        return user

    def save(self):
        new_user = self.create_user(self.data['login'])
        self.after_signup(new_user)

        return new_user

    def after_signup(self, user, **kwargs):
        """ Function to be overloaded and called after form submission
        to allow you the ability to save additional form data or perform
        extra actions after the form submission.
        """
        pass
Ejemplo n.º 19
0
def forbidden(request):
    """ forbidden(request)
    No return value

    Called when user hits a resource that requires a permission and the
    user doesn't have the required permission. Will prompt for login.

    request.environ['repoze.bfg.message'] contains our forbidden error in case
    of a csrf problem. Proper solution is probably an error page that
    can be customized.

    bfg.routes.route and repoze.bfg.message are scheduled to be deprecated,
    however, corresponding objects are not present in the request to be able
    to determine why the Forbidden exception was called.

    **THIS WILL BREAK EVENTUALLY**
    **THIS DID BREAK WITH Pyramid 1.2a3**
    """
    if request.environ.has_key('bfg.routes.route'):
        flash(_('Not logged in, please log in'), 'error')
        return HTTPFound(
            location='%s?came_from=%s' %
            (route_url('apex_login', request), current_route_url(request)))
    else:
        return Response(request.environ.get('repoze.bfg.message', \
                        'Unknown error message'))
Ejemplo n.º 20
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 'local' not in apex_settings('provider_exclude', []):
        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_username(form.data.get('username'))
        if user:
            headers = apex_remember(request, user.id)
            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'}
Ejemplo n.º 21
0
def invite(request):
    form = InviteFriendForm(
        request.POST,
        captcha={'ip_address': request.environ['REMOTE_ADDR']}
    )

    if request.method == 'POST' and form.validate():
        new_invitation = InviteAddress(email=form.data['email_address'])
        body = form.data['email_body'] + """
_____
This message was sent to invite you to join piktio.com.
You will never receive email from this site again.
"""
        apex_email(request, recipients=form.data['email_address'],
                   subject=form.data['email_subject'], body=body)
        DBSession.add(new_invitation)
        flash(_('Invitation email sent.'))
        return HTTPFound(location=request.route_path('invite'))

    form.email_body.data = \
"""Hello,
    %s has invited you to join piktio.com. We hope to see you there!
""" % request.user.display_name

    return {'title': 'Invite someone to join piktio!',
            'user': request.user,
            'form': form}
Ejemplo n.º 22
0
def forbidden(request):
    """ forbidden(request)
    No return value

    Called when user hits a resource that requires a permission and the
    user doesn't have the required permission. Will prompt for login.

    request.environ['repoze.bfg.message'] contains our forbidden error in case
    of a csrf problem. Proper solution is probably an error page that
    can be customized.

    bfg.routes.route and repoze.bfg.message are scheduled to be deprecated,
    however, corresponding objects are not present in the request to be able
    to determine why the Forbidden exception was called.

    **THIS WILL BREAK EVENTUALLY**
    **THIS DID BREAK WITH Pyramid 1.2a3**
    """
    if request.environ.has_key('bfg.routes.route'):
        flash(_('Not logged in, please log in'), 'error')
        return HTTPFound(location='%s?came_from=%s' %
                        (route_url('apex_login', request),
                        current_route_url(request)))
    else:
        return Response(request.environ.get('repoze.bfg.message', \
                        'Unknown error message'))
Ejemplo n.º 23
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 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)
            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'}
Ejemplo n.º 24
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'}
Ejemplo n.º 25
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)
Ejemplo n.º 26
0
def apex_id_from_token(request):
    """ Returns the apex id from the OpenID Token
    """
    payload = {'format': 'json', 'token': request.POST['token']}
    velruse = requests.get(request.host_url + '/velruse/auth_info',
                           params=payload)
    if velruse.status_code == 200:
        try:
            auth = velruse.json()
        except:
            raise HTTPBadRequest(_('Velruse error while decoding json'))
        if 'profile' in auth:
            auth['id'] = auth['profile']['accounts'][0]['userid']
            auth['provider'] = auth['profile']['accounts'][0]['domain']
            return auth
        return None
    else:
        raise HTTPBadRequest(_('Velruse backing store unavailable'))
Ejemplo n.º 27
0
def apex_id_from_token(request):
    """ Returns the apex id from the OpenID Token
    """
    payload = {'format': 'json', 'token': request.POST['token']}
    velruse = requests.get(request.host_url + '/velruse/auth_info', \
        params=payload)
    if velruse.status_code == 200:
        try:
            auth = velruse.json()
        except:
            raise HTTPBadRequest(_('Velruse error while decoding json'))
        if 'profile' in auth:
            auth['id'] = auth['profile']['accounts'][0]['userid']
            auth['provider'] = auth['profile']['accounts'][0]['domain']
            return auth
        return None
    else:
        raise HTTPBadRequest(_('Velruse backing store unavailable'))
Ejemplo n.º 28
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'
    }
Ejemplo n.º 29
0
Archivo: views.py Proyecto: 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))
Ejemplo n.º 30
0
    def forgot(self):
        """
In the message body, %_url_% is replaced with:

::

    route_url('apex_reset', request, user_id=user_id, hmac=hmac))
        """
        return {
                'subject': _('Password reset request received'),
                'body': _("""
A request to reset your password has been received. Please go to
the following URL to change your password:

%_url_%

If you did not make this request, you can safely ignore it.
"""),
        }
Ejemplo n.º 31
0
    def activate(self):
        """
In the message body, %_url_% is replaced with:

::

    route_url('apex_activate', request, user_id=user_id, hmac=hmac))
        """
        return {
                'subject': _('Account activation. Please activate your account.'),
                'body': _("""
This site requires account validation. Please follow the link below to
activate your account:

%_url_%

If you did not make this request, you can safely ignore it.
"""),
        }
Ejemplo n.º 32
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.provider != 'local':
                provider_name = user.provider
                flash(_('You used %s as your login provider' % \
                     provider_name))
                return HTTPFound(location=route_url('apex_login', \
                                          request))
        if form.data['login']:
            user = AuthUser.get_by_login(form.data['login'])
        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'}
Ejemplo n.º 33
0
    def activate(self):
        """
In the message body, %_url_% is replaced with:

::

    route_url('apex_activate', request, user_id=user_id, hmac=hmac))
        """
        return {
                'subject': _('Account activation. Please activate your account.'),
                'body': _("""
This site requires account validation. Please follow the link below to
activate your account:

%_url_%

If you did not make this request, you can safely ignore it.
"""),
        }
Ejemplo n.º 34
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'}
Ejemplo n.º 35
0
    def forgot(self):
        """
In the message body, %_url_% is replaced with:

::

    route_url('apex_reset', request, user_id=user_id, hmac=hmac))
        """
        return {
                'subject': _('Password reset request received'),
                'body': _("""
A request to reset your password has been received. Please go to
the following URL to change your password:

%_url_%

If you did not make this request, you can safely ignore it.
"""),
        }
Ejemplo n.º 36
0
Archivo: views.py Proyecto: 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}
Ejemplo n.º 37
0
class RegisterForm(ExtendedForm):
    """ Registration Form
    """
    username = TextField(_('Username'), [validators.Required(), \
                         validators.Length(min=4, max=25)])
    password = PasswordField(_('Password'), [validators.Required(), \
                             validators.EqualTo('password2', \
                             message=_('Passwords must match'))])
    password2 = PasswordField(_('Repeat Password'), [validators.Required()])
    email = TextField(_('Email Address'), [validators.Required(), \
                      validators.Email()])

    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.'))

    def validate_username(form, field):
        if AuthUser.get_by_username(field.data) is not None:
            raise validators.ValidationError(
                _('Sorry that username already exists.'))

    def save(self):
        infos = {
            'password': self.data.get('password', ''),
            'email': self.data.get('email', ''),
            'username': self.data.get('username', ''),
            'login': self.data.get('username', ''),
        }
        new_user = create_user(**infos)
        self.after_signup(new_user)
        return new_user

    def after_signup(self, user, **kwargs):
        """ Function to be overloaded and called after form submission
        to allow you the ability to save additional form data or perform
        extra actions after the form submission.
        """
        pass
Ejemplo n.º 38
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)
Ejemplo n.º 39
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))
Ejemplo n.º 40
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)
Ejemplo n.º 41
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]:
                #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'}
Ejemplo n.º 42
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'}
Ejemplo n.º 43
0
class AddAuthForm(ExtendedForm):
    login = TextField(_('Username'), [validators.Required(), \
                         validators.Length(min=4, max=25)])
    password = PasswordField(_('Password'), [validators.Required(), \
                             validators.EqualTo('password2', \
                             message=_('Passwords must match'))])
    password2 = PasswordField(_('Repeat Password'), [validators.Required()])
    email = TextField(_('Email Address'), [validators.Required(), \
                      validators.Email()])

    def validate_login(form, field):
        if AuthUser.get_by_login(field.data) is not None:
            raise validators.ValidationError(
                _('Sorry that username already exists.'))

    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

    def save(self, auth_id):
        new_user = self.create_user(auth_id, self.data['login'])
        self.after_signup(user=new_user)

    def after_signup(self, **kwargs):
        """ Function to be overloaded and called after form submission
        to allow you the ability to save additional form data or perform
        extra actions after the form submission.
        """
        pass
Ejemplo n.º 44
0
class RegisterForm(ExtendedForm):
    """ Registration Form
    """
    login = TextField(_('Username'), [validators.Required(), \
                         validators.Length(min=4, max=25)])
    password = PasswordField(_('Password'), [validators.Required(), \
                             validators.EqualTo('password2', \
                             message=_('Passwords must match'))])
    password2 = PasswordField(_('Repeat Password'), [validators.Required()])
    email = TextField(_('Email Address'), [validators.Required(), \
                      validators.Email()])

    def validate_login(form, field):
        if AuthUser.get_by_login(field.data) is not None:
            raise validators.ValidationError(
                _('Sorry that username already exists.'))

    def create_user(self, login):
        group = self.request.registry.settings.get('apex.default_user_group',
                                                   None)
        user = apex.lib.libapex.create_user(username=login,
                                            password=self.data['password'],
                                            email=self.data['email'],
                                            group=group)
        return user

    def save(self):
        new_user = self.create_user(self.data['login'])
        self.after_signup(user=new_user)

        return new_user

    def after_signup(self, **kwargs):
        """ Function to be overloaded and called after form submission
        to allow you the ability to save additional form data or perform
        extra actions after the form submission.
        """
        pass
Ejemplo n.º 45
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'}
Ejemplo n.º 46
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'}
Ejemplo n.º 47
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'}
Ejemplo n.º 48
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'}
Ejemplo n.º 49
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'}
Ejemplo n.º 50
0
Archivo: views.py Proyecto: 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'}
Ejemplo n.º 51
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)
Ejemplo n.º 52
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'}
Ejemplo n.º 53
0
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'}
Ejemplo n.º 54
0
 def validate_login(form, field):
     if AuthUser.get_by_login(field.data) is None:
         raise validators.ValidationError(_('Sorry that username doesn\'t exist.'))
Ejemplo n.º 55
0
 def clean(self):
     errors = []
     if not AuthUser.check_password(login=self.data.get('login'), \
                                    password=self.data.get('password')):
         errors.append(_('Login Error -- please try again'))
     return errors
Ejemplo n.º 56
0
 def validate_old_password(form, field):
     request = get_current_request()
     if not AuthUser.check_password(id=authenticated_userid(request), \
                                    password=field.data):
         raise validators.ValidationError(_('Your old password doesn\'t match'))
Ejemplo n.º 57
0
 def validate_login(form, field):
     if AuthUser.get_by_login(field.data) is not None:
         raise validators.ValidationError(_('Sorry that username already exists.'))
Ejemplo n.º 58
0
 def clean(self):
     errors = []
     if not self.data.get('login') and not self.data.get('email'):
         errors.append(_('You need to specify either a Username or ' \
                         'Email address'))
     return errors
Ejemplo n.º 59
0
 def validate_email(form, field):
     if AuthUser.get_by_email(field.data) is None:
         raise validators.ValidationError(_('Sorry that email doesn\'t exist.'))
Ejemplo n.º 60
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)