Exemplo n.º 1
0
def _handle_third_party_auto_signup(request, provider, provider_info,
                                    identifier, user_info):
    """Create AstakosUser for third party user without requiring signup form.

    Handle third party signup by automatically creating an AstakosUser. This
    is performed when the user's profile is automatically set by the provider.

    """
    try:
        email = user_info['email']
        first_name = user_info['first_name']
        last_name = user_info['last_name']
    except KeyError as e:
        raise Exception("Invalid user info. Missing '%s'", str(e))

    has_signed_terms = not get_latest_terms()
    user = auth.make_user(email=email,
                          first_name=first_name, last_name=last_name,
                          has_signed_terms=has_signed_terms)

    provider_data = {
        'affiliation': user_info.get('affiliation', provider),
        'info': provider_info
    }
    provider = auth_providers.get_provider(module=provider, user_obj=user,
                                           identifier=identifier,
                                           **provider_data)
    provider.add_to_user()

    # Handle user activation
    activation_backend = activation_backends.get_backend()
    result = activation_backend.handle_registration(user)
    activation_backend.send_result_notifications(result, user)

    return user
Exemplo n.º 2
0
def send_activation(request,
                    user_id,
                    template_name='im/login.html',
                    extra_context=None):

    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('index'))

    extra_context = extra_context or {}
    try:
        u = AstakosUser.objects.get(id=user_id)
    except AstakosUser.DoesNotExist:
        messages.error(request, _(astakos_messages.ACCOUNT_UNKNOWN))
    else:
        if u.email_verified:
            logger.warning("[resend activation] Account already verified: %s",
                           u.log_display)

            messages.error(request,
                           _(astakos_messages.ACCOUNT_ALREADY_VERIFIED))
        else:
            activation_backend = activation_backends.get_backend()
            activation_backend.send_user_verification_email(u)
            messages.success(request, astakos_messages.ACTIVATION_SENT)

    return HttpResponseRedirect(reverse('index'))
Exemplo n.º 3
0
def new_user():
    email = random_email()
    backend = activation_backends.get_backend()
    try:
        AstakosUser.objects.get(email=email)
        return None
    except AstakosUser.DoesNotExist:
        u = auth.make_local_user(email, first_name=random_name(),
                                 last_name=random_name())
        backend.verify_user(u, u.verification_code)
        backend.accept_user(u)
        return u
Exemplo n.º 4
0
def new_user():
    email = random_email()
    backend = activation_backends.get_backend()
    try:
        AstakosUser.objects.get(email=email)
        return None
    except AstakosUser.DoesNotExist:
        u = auth.make_local_user(email, first_name=random_name(),
                                 last_name=random_name())
        backend.verify_user(u, u.verification_code)
        backend.accept_user(u)
        return u
Exemplo n.º 5
0
def activate(request,
             greeting_email_template_name='im/welcome_email.txt',
             helpdesk_email_template_name='im/helpdesk_notification.txt'):
    """
    Activates the user identified by the ``auth`` request parameter, sends a
    welcome email and renews the user token.

    The view uses commit_manually decorator in order to ensure the user state
    will be updated only if the email will be send successfully.
    """
    token = request.GET.get('auth')
    next = request.GET.get('next')

    if request.user.is_authenticated():
        message = _(astakos_messages.LOGGED_IN_WARNING)
        messages.error(request, message)
        transaction.rollback()
        return HttpResponseRedirect(reverse('index'))

    try:
        user = AstakosUser.objects.get(verification_code=token)
    except AstakosUser.DoesNotExist:
        transaction.rollback()
        raise Http404

    if user.email_verified:
        message = _(astakos_messages.ACCOUNT_ALREADY_VERIFIED)
        messages.error(request, message)
        return HttpResponseRedirect(reverse('index'))

    try:
        backend = activation_backends.get_backend()
        result = backend.handle_verification(user, token)
        backend.send_result_notifications(result, user)
        next = settings.ACTIVATION_REDIRECT_URL or next
        response = HttpResponseRedirect(reverse('index'))
        if user.is_active:
            response = prepare_response(request, user, next, renew=True)
            messages.success(request, _(result.message))
        else:
            messages.warning(request, _(result.message))
    except Exception:
        transaction.rollback()
        raise
    else:
        transaction.commit()
        return response
Exemplo n.º 6
0
def get_local_user(username, **kwargs):
    try:
        return AstakosUser.objects.get(email=username)
    except:
        user = auth_functions.make_local_user(email=username,
                                              has_signed_terms=True)
        user.set_password(kwargs.pop('password', 'password'))

        for key, value in kwargs.iteritems():
            setattr(user, key, value)
        user.save()

        if kwargs.get("is_active", True):
            backend = activation_backends.get_backend()
            backend.verify_user(user, user.verification_code)
            backend.accept_user(user)

        return user
Exemplo n.º 7
0
def get_local_user(username, **kwargs):
    try:
        return AstakosUser.objects.get(email=username)
    except:
        user = auth_functions.make_local_user(email=username,
                                              has_signed_terms=True)
        user.set_password(kwargs.pop('password', 'password'))

        for key, value in kwargs.iteritems():
            setattr(user, key, value)
        user.save()

        if kwargs.get("is_active", True):
            backend = activation_backends.get_backend()
            backend.verify_user(user, user.verification_code)
            backend.accept_user(user)

        return user
Exemplo n.º 8
0
def activate(request, greeting_email_template_name='im/welcome_email.txt',
             helpdesk_email_template_name='im/helpdesk_notification.txt'):
    """
    Activates the user identified by the ``auth`` request parameter, sends a
    welcome email and renews the user token.

    The user state will be updated only if the email will be send successfully.
    """
    token = request.GET.get('auth', None)
    next = request.GET.get('next', None)

    if not token:
        raise PermissionDenied

    if request.user.is_authenticated():
        message = _(astakos_messages.LOGGED_IN_WARNING)
        messages.error(request, message)
        return HttpResponseRedirect(reverse('index'))

    try:
        user = AstakosUser.objects.select_for_update().\
            get(verification_code=token)
    except AstakosUser.DoesNotExist:
        messages.error(request, astakos_messages.INVALID_ACTIVATION_KEY)
        return HttpResponseRedirect(reverse('index'))

    if user.email_verified:
        message = _(astakos_messages.ACCOUNT_ALREADY_VERIFIED)
        messages.error(request, message)
        return HttpResponseRedirect(reverse('index'))

    backend = activation_backends.get_backend()
    result = backend.handle_verification(user, token)
    backend.send_result_notifications(result, user)
    next = settings.ACTIVATION_REDIRECT_URL or next or reverse('index')
    if user.is_active:
        response = prepare_response(request, user, next, renew=True)
        messages.success(request, _(result.message))
    else:
        response = HttpResponseRedirect(reverse('index'))
        messages.warning(request, _(result.message))

    return response
Exemplo n.º 9
0
def send_activation(request, user_id, template_name='im/login.html',
                    extra_context=None):

    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('index'))

    extra_context = extra_context or {}
    try:
        u = AstakosUser.objects.select_for_update().get(id=user_id)
    except AstakosUser.DoesNotExist:
        messages.error(request, _(astakos_messages.ACCOUNT_UNKNOWN))
    else:
        if u.email_verified:
            logger.warning("[resend activation] Account already verified: %s",
                           u.log_display)

            messages.error(request,
                           _(astakos_messages.ACCOUNT_ALREADY_VERIFIED))
        else:
            activation_backend = activation_backends.get_backend()
            activation_backend.send_user_verification_email(u)
            messages.success(request, astakos_messages.ACTIVATION_SENT)

    return HttpResponseRedirect(reverse('index'))
Exemplo n.º 10
0
        get_verified = AstakosUserAuthProvider.objects.verified
        verified = get_verified(pending.provider,
                                identifier=pending.third_party_identifier)
        if verified:
            # an existing verified user already exists for the third party
            # identifier
            pending.delete()
            raise Http404

        if unverified and request.method == 'GET':
            messages.warning(request, unverified.get_pending_registration_msg)

    # prepare activation backend based on current request
    if not activation_backend:
        activation_backend = activation_backends.get_backend()

    form_kwargs = {'instance': instance, 'request': request}
    if third_party_token:
        form_kwargs['third_party_token'] = third_party_token

    if pending:
        form_kwargs['initial'] = {
            'first_name': pending.first_name,
            'last_name': pending.last_name,
            'email': pending.email
        }

    form = activation_backend.get_signup_form(provider, None, **form_kwargs)

    if request.method == 'POST':
Exemplo n.º 11
0
from snf_django.lib.api import faults

from .util import (
    get_uuid_displayname_catalogs as get_uuid_displayname_catalogs_util,
    send_feedback as send_feedback_util,
    user_from_token)

from astakos.im import settings
from astakos.admin import stats
from astakos.im.models import AstakosUser, get_latest_terms
from astakos.im.auth import make_local_user
from astakos.im import activation_backends

ADMIN_GROUPS = settings.ADMIN_API_PERMITTED_GROUPS

activation_backend = activation_backends.get_backend()

logger = logging.getLogger(__name__)

@csrf_exempt
@api.api_method(http_method="POST", token_required=True, user_required=False,
                logger=logger)
@user_from_token  # Authenticate user!!
def get_uuid_displayname_catalogs(request):
    # Normal Response Codes: 200
    # Error Response Codes: internalServerError (500)
    #                       badRequest (400)
    #                       unauthorised (401)

    return get_uuid_displayname_catalogs_util(request)
Exemplo n.º 12
0
def signup(request,
           template_name='im/signup.html',
           on_success='index',
           extra_context=None,
           activation_backend=None):
    """
    Allows a user to create a local account.

    In case of GET request renders a form for entering the user information.
    In case of POST handles the signup.

    The user activation will be delegated to the backend specified by the
    ``activation_backend`` keyword argument if present, otherwise to the
    ``astakos.im.activation_backends.InvitationBackend`` if
    settings.ASTAKOS_INVITATIONS_ENABLED is True or
    ``astakos.im.activation_backends.SimpleBackend`` if not (see
    activation_backends);

    Upon successful user creation, if ``next`` url parameter is present the
    user is redirected there otherwise renders the same page with a success
    message.

    On unsuccessful creation, renders ``template_name`` with an error message.

    **Arguments**

    ``template_name``
        A custom template to render. This is optional;
        if not specified, this will default to ``im/signup.html``.

    ``extra_context``
        An dictionary of variables to add to the template context.

    ``on_success``
        Resolvable view name to redirect on registration success.

    **Template:**

    im/signup.html or ``template_name`` keyword argument.
    """
    extra_context = extra_context or {}
    if request.user.is_authenticated():
        logger.info("%s already signed in, redirect to index",
                    request.user.log_display)
        transaction.rollback()
        return HttpResponseRedirect(reverse('index'))

    provider = get_query(request).get('provider', 'local')
    if not auth.get_provider(provider).get_create_policy:
        logger.error("%s provider not available for signup", provider)
        transaction.rollback()
        raise PermissionDenied

    instance = None

    # user registered using third party provider
    third_party_token = request.REQUEST.get('third_party_token', None)
    unverified = None
    if third_party_token:
        # retreive third party entry. This was created right after the initial
        # third party provider handshake.
        pending = get_object_or_404(PendingThirdPartyUser,
                                    token=third_party_token)

        provider = pending.provider

        # clone third party instance into the corresponding AstakosUser
        instance = pending.get_user_instance()
        get_unverified = AstakosUserAuthProvider.objects.unverified

        # check existing unverified entries
        unverified = get_unverified(pending.provider,
                                    identifier=pending.third_party_identifier)

        if unverified and request.method == 'GET':
            messages.warning(request, unverified.get_pending_registration_msg)
            if unverified.user.moderated:
                messages.warning(request,
                                 unverified.get_pending_resend_activation_msg)
            else:
                messages.warning(request,
                                 unverified.get_pending_moderation_msg)

    # prepare activation backend based on current request
    if not activation_backend:
        activation_backend = activation_backends.get_backend()

    form_kwargs = {'instance': instance, 'request': request}
    if third_party_token:
        form_kwargs['third_party_token'] = third_party_token

    form = activation_backend.get_signup_form(provider, None, **form_kwargs)

    if request.method == 'POST':
        form = activation_backend.get_signup_form(provider, request.POST,
                                                  **form_kwargs)

        if form.is_valid():
            commited = False
            try:
                user = form.save(commit=False)

                # delete previously unverified accounts
                if AstakosUser.objects.user_exists(user.email):
                    AstakosUser.objects.get_by_identifier(user.email).delete()

                # store_user so that user auth providers get initialized
                form.store_user(user, request)
                result = activation_backend.handle_registration(user)
                if result.status == \
                        activation_backend.Result.PENDING_MODERATION:
                    # user should be warned that his account is not active yet
                    status = messages.WARNING
                else:
                    status = messages.SUCCESS
                message = result.message
                activation_backend.send_result_notifications(result, user)

                # commit user entry
                transaction.commit()
                # commited flag
                # in case an exception get raised from this point
                commited = True

                if user and user.is_active:
                    # activation backend directly activated the user
                    # log him in
                    next = request.POST.get('next', '')
                    response = prepare_response(request, user, next=next)
                    return response

                messages.add_message(request, status, message)
                return HttpResponseRedirect(reverse(on_success))
            except Exception, e:
                if not commited:
                    transaction.rollback()
                raise
Exemplo n.º 13
0
Arquivo: im.py Projeto: cstavr/synnefo
def signup(request, template_name='im/signup.html', on_success='index',
           extra_context=None, activation_backend=None):
    """
    Allows a user to create a local account.

    In case of GET request renders a form for entering the user information.
    In case of POST handles the signup.

    The user activation will be delegated to the backend specified by the
    ``activation_backend`` keyword argument if present, otherwise to the
    ``astakos.im.activation_backends.InvitationBackend`` if
    settings.ASTAKOS_INVITATIONS_ENABLED is True or
    ``astakos.im.activation_backends.SimpleBackend`` if not (see
    activation_backends);

    Upon successful user creation, if ``next`` url parameter is present the
    user is redirected there otherwise renders the same page with a success
    message.

    On unsuccessful creation, renders ``template_name`` with an error message.

    **Arguments**

    ``template_name``
        A custom template to render. This is optional;
        if not specified, this will default to ``im/signup.html``.

    ``extra_context``
        An dictionary of variables to add to the template context.

    ``on_success``
        Resolvable view name to redirect on registration success.

    **Template:**

    im/signup.html or ``template_name`` keyword argument.
    """
    extra_context = extra_context or {}
    if request.user.is_authenticated():
        logger.info("%s already signed in, redirect to index",
                    request.user.log_display)
        return HttpResponseRedirect(reverse('index'))

    provider = get_query(request).get('provider', 'local')
    if not auth.get_provider(provider).get_create_policy:
        logger.error("%s provider not available for signup", provider)
        raise PermissionDenied

    instance = None

    # user registered using third party provider
    third_party_token = request.REQUEST.get('third_party_token', None)
    unverified = None
    if third_party_token:
        # retreive third party entry. This was created right after the initial
        # third party provider handshake.
        pending = get_object_or_404(PendingThirdPartyUser,
                                    token=third_party_token)

        provider = pending.provider

        # clone third party instance into the corresponding AstakosUser
        instance = pending.get_user_instance()
        get_unverified = AstakosUserAuthProvider.objects.unverified

        # check existing unverified entries
        unverified = get_unverified(pending.provider,
                                    identifier=pending.third_party_identifier)

        if unverified and request.method == 'GET':
            messages.warning(request, unverified.get_pending_registration_msg)
            if unverified.user.moderated:
                messages.warning(request,
                                 unverified.get_pending_resend_activation_msg)
            else:
                messages.warning(request,
                                 unverified.get_pending_moderation_msg)

    # prepare activation backend based on current request
    if not activation_backend:
        activation_backend = activation_backends.get_backend()

    form_kwargs = {'instance': instance, 'request': request}
    if third_party_token:
        form_kwargs['third_party_token'] = third_party_token

    form = activation_backend.get_signup_form(
        provider, None, **form_kwargs)

    if request.method == 'POST':
        form = activation_backend.get_signup_form(
            provider,
            request.POST,
            **form_kwargs)

        if form.is_valid():
            user = form.save(commit=False)

            # delete previously unverified accounts
            if AstakosUser.objects.user_exists(user.email):
                AstakosUser.objects.get_by_identifier(user.email).delete()

            # store_user so that user auth providers get initialized
            form.store_user(user, request)
            result = activation_backend.handle_registration(user)
            if result.status == \
                    activation_backend.Result.PENDING_MODERATION:
                # user should be warned that his account is not active yet
                status = messages.WARNING
            else:
                status = messages.SUCCESS
            message = result.message
            activation_backend.send_result_notifications(result, user)

            # commit user entry
            transaction.commit()

            if user and user.is_active:
                # activation backend directly activated the user
                # log him in
                next = request.POST.get('next', '')
                response = prepare_response(request, user, next=next)
                return response

            messages.add_message(request, status, message)
            return HttpResponseRedirect(reverse(on_success))

    return render_response(template_name,
                           signup_form=form,
                           third_party_token=third_party_token,
                           provider=provider,
                           context_instance=get_context(request, extra_context))