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'))
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'))
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}
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 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 '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'}
def delete(request): form = YesNoForm(request.POST) amazon_aws = route53_connect() zone = amazon_aws.get_hosted_zone_by_id(request.matchdict['id']) if request.method == 'POST' and form.validate(): domain_name = zone.name zone.delete(force=True) flash('{0} deleted'.format(domain_name)) return HTTPFound(location= \ route_url('apex_route53_index', request)) return {'zone':zone, 'form':form}
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 delete_rs(request): form = YesNoForm(request.POST) amazon_aws = route53_connect() zone = amazon_aws.get_hosted_zone_by_id(request.matchdict['id']) for rs in zone.record_sets: if rs.uniq == request.matchdict['recordset_id']: record_set = rs break if request.method == 'POST' and form.validate(): record_set.delete() flash('Record Set in {0} deleted'.format(zone.name)) return HTTPFound(location=route_url('apex_route53_edit', request, id=zone.id)) return {'zone':zone, 'record_set':record_set, 'form':form}
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'}
def forbidden(req): """ 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. """ flash(_('Access denied to this section'), 'error') came_from = req.resource_url(req.root) if req.user is None: came_from = req.url return HTTPFound(location='%s?came_from=%s' % ( req.route_url('apex_login'), came_from ))
def ips(request): providers = get_providers() ips = get_ips() if not providers: flash('You have no providers defined, please add at least one') return HTTPFound(location=route_url('apex_route53_webhosts', request)) form = IPForm(request.POST, providers=providers) form.provider_id.choices = providers record = IP() if request.method == 'POST' and form.validate(): record = merge_session_with_post(record, request.POST.items()) DBSession.merge(record) DBSession.flush() return HTTPFound(location= \ route_url('apex_route53_ips', request)) return {'title':'IP Addresses', 'form':form, 'ips':ips}
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 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' }
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 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 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 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 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'}
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.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'}
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' }
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)
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 = None try: auth = apex_id_from_token(request) except: # TODO add logging pass if auth: user = None if not request.session.has_key('id'): user = AuthUser.get_by_login(auth['id']) if not user: id = None if request.session.has_key('id'): id = AuthID.get_by_id(request.session['id']) else: id = AuthID() DBSession.add(id) auth_info = auth['profile']['accounts'][0] 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(request=request, user=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 = [] 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)
def wrapper(request): result = wrapped(request) if not authenticated_userid(request): flash(_('Not logged in, please log in'), 'error') return HTTPFound(location=route_url('apex_login', request))