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))
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'}
def csrf_validation(event): """ CSRF token validation Subscriber As of Pyramid 1.2a3, passing messages through HTTPForbidden broke, and don't appear to be exposed to exception handlers. It appears that we cannot decorate a view and have it affect an event until after the event has fired, so, temporarily we're going to have to use a value in the config to specify a list of paths that should not have CSRF validation. Ideally, we'll be able to do :: @no_csrf @view_config(route_name='test') def test(request): which would prevent CSRF tracking on that view. With the event hooks, our decorator is not read until AFTER the event, which makes this method fail at this point. Temporarily, we'll use a field in the development.ini: apex.no_csrf = routename1:routename2 """ if event.request.method == 'POST': token = event.request.POST.get('csrf_token') or event.request.GET.get('csrf_token') no_csrf = apex_settings('no_csrf', '').split(',') if (token is None or token != event.request.session.get_csrf_token()): if event.request.matched_route and event.request.matched_route.name not in no_csrf \ and not event.request.matched_route.name.startswith('debugtoolbar.'): raise HTTPForbidden(_('CSRF token is missing or invalid'))
def csrf_validation(event): """ CSRF token validation Subscriber As of Pyramid 1.2a3, passing messages through HTTPForbidden broke, and don't appear to be exposed to exception handlers. It appears that we cannot decorate a view and have it affect an event until after the event has fired, so, temporarily we're going to have to use a value in the config to specify a list of paths that should not have CSRF validation. Ideally, we'll be able to do :: @no_csrf @view_config(route_name='test') def test(request): which would prevent CSRF tracking on that view. With the event hooks, our decorator is not read until AFTER the event, which makes this method fail at this point. Temporarily, we'll use a field in the development.ini: apex.no_csrf = routename1:routename2 """ if event.request.method == 'POST': token = event.request.POST.get('csrf_token') or event.request.GET.get('csrf_token') no_csrf = apex_settings('no_csrf', '').split(':') if (token is None or token != event.request.session.get_csrf_token()): if event.request.matched_route and event.request.matched_route.name not in no_csrf: raise HTTPForbidden(_('CSRF token is missing or invalid'))
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'}
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)
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)
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 = int(time.time()) + 3600 hmac_key = get_hmac_key(user, timestamp) time_key = base64.urlsafe_b64encode( ('%d' % timestamp).encode("ascii")) email_hash = '%s%s' % (hmac_key, time_key.decode("ascii")) 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', "velruse_forms": None}
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'}
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)
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'}
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}
def check(self, DBSession, request, user, password): salted_passwd = user.password prefix_salt = apex_settings('fallback_prefix_salt', None) if prefix_salt: salted_passwd = '%s%s' % (prefix_salt, salted_passwd) salt_field = apex_settings('fallback_salt_field', None) if salt_field: prefix_salt = getattr(user, salt_field) salted_passwd = '%s%s' % (prefix_salt, salted_passwd) if salted_passwd is not None: if len(salted_passwd) == 32: # md5 m = hashlib.md5() # password='···· breaks when type=unicode m.update(password) if m.hexdigest() == salted_passwd: user.password = password DBSession.merge(user) DBSession.flush() return True if len(salted_passwd) == 40: # sha1 m = hashlib.sha1() m.update(password) if m.hexdigest() == salted_passwd: user.password = password DBSession.merge(user) DBSession.flush() return True if salted_passwd == password: # plaintext user.password = password DBSession.merge(user) DBSession.flush() return True return False
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'}
def check(self, DBSession, request, user, password): salted_passwd = user.password prefix_salt = apex_settings('fallback_prefix_salt', None) if prefix_salt: salted_passwd = '%s%s' % (prefix_salt, salted_passwd) salt_field = apex_settings('fallback_salt_field', None) if salt_field: prefix_salt = getattr(user, salt_field) salted_passwd = '%s%s' % (prefix_salt, salted_passwd) if salted_passwd is not None: if len(salted_passwd) == 32: # md5 m = hashlib.md5() # password= breaks when type=unicode m.update(password) if m.hexdigest() == salted_passwd: user.password = password DBSession.merge(user) DBSession.flush() return True if len(salted_passwd) == 40: # sha1 m = hashlib.sha1() m.update(password) if m.hexdigest() == salted_passwd: user.password = password DBSession.merge(user) DBSession.flush() return True if salted_passwd == password: # plaintext user.password = password DBSession.merge(user) DBSession.flush() return True return False
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'}
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))
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'}
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'}
def csrf_validation(event): """ CSRF token validation Subscriber As of Pyramid 1.2a3, passing messages through HTTPForbidden broke, and don't appear to be exposed to exception handlers. It appears that we cannot decorate a view and have it affect an event until after the event has fired, so, temporarily we're going to have to use a value in the config to specify a list of paths that should not have CSRF validation. Ideally, we'll be able to do :: @no_csrf @view_config(route_name='test') def test(request): which would prevent CSRF tracking on that view. With the event hooks, our decorator is not read until AFTER the event, which makes this method fail at this point. Temporarily, we'll use a field in the development.ini: apex.no_csrf = routename1:routename2 Disabled apex CSRF (20121118) - CSRF token not being passed through new Velruse """ #import pdb; pdb.set_trace() if event.request.method == 'POST': # will never hit GET token = event.request.POST.get('csrf_token') \ or event.request.GET.get('csrf_token') \ or event.request.headers.get('X-CSRF-Token') # or event.request.json_body.get('csrf_token') \ no_csrf = apex_settings('no_csrf', '').split(',') if (token is None or token != event.request.session.get_csrf_token()): if event.request.matched_route and \ event.request.matched_route.name not in no_csrf \ and not event.request.matched_route.name.startswith('debugtoolbar.') \ and not event.request.matched_route.name.startswith('apex_'): log.debug('apex: CSRF token received %s didn\'t match %s' % \ (token, event.request.session.get_csrf_token())) raise HTTPForbidden(_('CSRF token is missing or invalid'))
def csrf_validation(event): """ CSRF token validation Subscriber As of Pyramid 1.2a3, passing messages through HTTPForbidden broke, and don't appear to be exposed to exception handlers. It appears that we cannot decorate a view and have it affect an event until after the event has fired, so, temporarily we're going to have to use a value in the config to specify a list of paths that should not have CSRF validation. Ideally, we'll be able to do :: @no_csrf @view_config(route_name='test') def test(request): which would prevent CSRF tracking on that view. With the event hooks, our decorator is not read until AFTER the event, which makes this method fail at this point. Temporarily, we'll use a field in the development.ini: apex.no_csrf = routename1:routename2 Disabled apex CSRF (20121118) - CSRF token not being passed through new Velruse """ if event.request.method == 'POST': # will never hit GET token = event.request.POST.get('csrf_token') \ or event.request.GET.get('csrf_token') \ or event.request.json_body.get('csrf_token') \ or event.request.headers.get('X-CSRF-Token') no_csrf = apex_settings('no_csrf', '').split(',') if (token is None or token != event.request.session.get_csrf_token()): if event.request.matched_route and \ event.request.matched_route.name not in no_csrf \ and not event.request.matched_route.name.startswith('debugtoolbar.') \ and not event.request.matched_route.name.startswith('apex_'): log.debug('apex: CSRF token received %s didn\'t match %s' % \ (token, event.request.session.get_csrf_token())) raise HTTPForbidden(_('CSRF token is missing or invalid'))
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'}
def landing(request): form = [] action = 'index' if request.session.get('id'): action = 'social' else: form = LandingForm(request.POST) if request.method == 'POST' and form.validate(): group = apex_settings('default_user_group') user = create_user(email = request.POST['email'], \ group = group) flash(_('Thanks')) request.session['id'] = user.id if request.matchdict.get('refer_id'): referrer_update(user, request.matchdict['refer_id']) return HTTPFound(location='/thanks') return {'form': form, 'action': action}
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))
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'}
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'}
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'}
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'}
def get_came_from(request): return request.GET.get( 'came_from', request.POST.get('came_from', route_url(apex_settings('came_from_route'), request)))
def get_came_from(request): return request.GET.get('came_from', request.POST.get( 'came_from', route_url(apex_settings('came_from_route'), request)) )
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'}