Example #1
0
def read_address_link(idAddress):
    """Checks if the link between addresses exists, if it does, returns the
    details of the link

    :param int idAddress: idAddress of the user that is being logged in
    :returns: dict if the link can be read
    :rtype: dict
    """
    admin_token = utils.get_admin_session().get_token()
    response = api.membership.address_link.read(pk=None, idAddress=idAddress,
                                                token=admin_token)
    if response.status_code == 200:
        return response.json()['content']
    return
Example #2
0
    def form_valid(self, form):
        email = form.cleaned_data['email']

        # get list of all persons with specified email
        api_token = get_admin_session().get_token()
        # FIXME(lb): change fields to partial member/language/address when
        # service starts supporting it
        params = {
            'username__iexact': email,
            'fields': '(*,member,language,address)'
        }
        response = api.membership.user.list(token=api_token, params=params)
        if response.status_code != 200 or \
                not response.json()['_metadata']['totalRecords']:
            messages.error(self.request, _("Sorry, user with this email "
                                           "address does not exist."))
            return self.form_invalid(form)

        users = response.json()['content']
        reset_token = PasswordResetToken(
            pk=uuid4().hex,
            data=json.dumps(users, cls=utils.ExtendedJSONEncoder))
        while True:
            try:
                reset_token.validate_unique()
                reset_token.save()
                break
            except ValidationError:
                reset_token.pk = uuid4().hex
        # Get language of the first person
        email_msg = render_to_string('auth/email/reset_password.txt', {
            'reset_token': reset_token.pk,
            'user': users[0],
            'request': self.request
        })
        subject = _('Reset password request.')
        try:
            send_mail(subject, email_msg, settings.DEFAULT_FROM_EMAIL, [email])
        except:
            messages.error(self.request,
                           _("Sorry, email with instructions how to reset "
                             "your password could not be sent."))
            return self.form_invalid(form)

        messages.info(self.request, _("Email with instructions on how to "
                                      "reset your password has been sent."))
        return super(ResetPassword, self).form_valid(form)
Example #3
0
    def form_valid(self, form):
        try:
            token_data = PasswordResetToken.objects.get(
                pk=self.kwargs['reset_token'])
        except PasswordResetToken.DoesNotExist:
            messages.error(self.request,
                           _("The reset password token is either expired or "
                             "has been already used once. Please use reset "
                             "password again."))
            return HttpResponseRedirect(reverse('reset_password'))
        user = token_data.get_user(form.cleaned_data['idUser'])
        if not user:
            messages.error(self.request, _("Could not identify the Person. "
                                           "Please try to use reset password "
                                           "again."))
            return HttpResponseRedirect(reverse('reset_password'))

        # read the person, confirm username matches
        token = get_admin_session().get_token()
        response = api.membership.user.read(
            pk=user['idUser'],
            token=token)
        if response.status_code != 200 or \
                response.json()['content']['username'] != user['username']:
            messages.error(self.request, _("Could not read User details from "
                                           "the Service. Please try to use "
                                           "reset password again."))
            return HttpResponseRedirect(reverse('reset_password'))

        # update the person with new password
        response = api.membership.user.partial_update(
            pk=user['idUser'],
            token=token,
            data={'password': form.cleaned_data['password']})
        if response.status_code != 204:
            messages.error(self.request,
                           _("Password could not be reset, contact staff."))
            return HttpResponseRedirect(reverse('reset_password'))
        messages.success(self.request, _("Your password has been changed."))
        token_data.delete()
        return super(ResetPasswordConfirm, self).form_valid(form)
Example #4
0
# python
from __future__ import unicode_literals
from collections import OrderedDict
import math
# libs
from cloudcix import api, utils
from cloudcix.utils import get_admin_session
from hashlib import sha224
from django.core.cache import cache
# local

admin_session = get_admin_session()


def memoize(seconds=0):
    """Allows to cache a method call for specific args/kwargs combination."""
    def inner_cache(method):

        def x(*args, **kwargs):
            key = sha224(str(method.__module__) + str(method.__name__) +
                         str(args) + str(kwargs)).hexdigest()
            result = cache.get(key)
            if result is None:
                # all caches failed, call the actual method
                result = method(*args, **kwargs)
                # save to memcache and class attr
                if seconds and isinstance(seconds, int):
                    cache.set(key, result, seconds)
            return result
        return x
Example #5
0
    def form_valid(self, form):
        token = get_admin_session().get_token()
        cd = form.cleaned_data
        member_data = {
            'groupName': cd['companyName'],
            'idCurrency': 1
        }
        response = api.membership.member.create(token=token, data=member_data)
        if response.status_code != 201:
            for field, err in response.json()['errors'].items():
                if field in form.fields:
                    form.add_error(field, err[0]['message'])

        addr_data = {
            'companyName': cd['companyName'],
            'idCurrency': 1,
            'idLanguage': 1,
            'idCountry': cd['idCountry'],
            'city': cd['city'],
            'address1': cd['address1'],
            'address2': cd['address2'],
            'address3': cd['address3'],
            'idMember': response.json().get('content', dict()).get(
                'idMember', None)
        }
        response = api.membership.address.create(token=token, data=addr_data)
        if response.status_code != 201:
            for field, err in response.json()['errors'].items():
                if field in form.fields:
                    form.add_error(field, err[0]['message'])

        user_data = {
            'username': cd['username'],
            'password': cd['password'],
            'idAddress': response.json().get('content', dict()).get(
                'idAddress', None),
            'idLanguage': 1,
            'firstName': cd['firstName'],
            'surname': cd['surname'],
            'timezone': 'UTC',
            'startDate': datetime.utcnow().date().isoformat(),
            'expiryDate': (datetime.utcnow() +
                           relativedelta(years=1)).date().isoformat()
        }
        response = api.membership.user.create(token=token, data=user_data)
        if response.status_code != 201:
            for field, err in response.json()['errors'].items():
                if field in form.fields:
                    form.add_error(field, err[0]['message'])

        if form.errors:
            return self.form_invalid(form)

        api.membership.member.partial_update(
            pk=addr_data['idMember'],
            token=token,
            data={'selfManaged': True})
        messages.success(self.request, _('Your account has been successfully '
                                         'created. You can now login.'))

        return super(Register, self).form_valid(form)
    def authenticate(self, request=None, username=None, password=None,
                     user_domain_name=None, auth_url=None, idMember=None,
                     token_id=None, scope=None):
        """Authenticates user against CIX Session Service

        :param username: CIX username
        :type username: str | unicode
        :param password: CIX password
        :type password: str | unicode
        :param idMember: in case of multi-account users - idMember, optional
        :type idMember: int | str | unicode | None
        :returns: User object
        :rtype: cix.django_plugin.models.django_auth.User | None
        """
        LOG.debug('Beginning user authentication for user "%s".' % username)

        if auth_url is None:
            auth_url = settings.OPENSTACK_KEYSTONE_URL
        kw = {
            'username': username,
            'password': password,
            'token_id': token_id,
            'idMember': idMember,
            'scope': scope
        }
        kw = dict(filter(lambda o: o if o[1] else None, kw.items()))
        if 'token_id' in kw.keys():
            kw.pop('username', '')
            kw.pop('password', '')
        else:
            kw.pop('token_id', '')
        # Create the session for a user.
        auth = utils.CloudCIXAuth(auth_url=auth_url, **kw)
        session = utils.KeystoneSession(auth=auth)
        try:
            unscoped_auth_ref = auth.get_access(session)
        except keystone_exceptions.Unauthorized as exc:
            if getattr(session.auth, 'additional_auth_required', None):
                raise AdditionalAuthRequired(session)
            msg = _('Invalid credentials.')
            LOG.debug(str(exc))
            raise exceptions.KeystoneAuthException(msg)
        except (keystone_exceptions.Forbidden,
                keystone_exceptions.NotFound) as exc:
            msg = _('Invalid credentials.')
            LOG.debug(str(exc))
            raise exceptions.KeystoneAuthException(msg)
        except (keystone_exceptions.ClientException,
                keystone_exceptions.AuthorizationFailure) as exc:
            msg = _("An error occurred authenticating. "
                    "Please try again later.")
            LOG.debug(str(exc))
            raise exceptions.KeystoneAuthException(msg)

        # Create a trust from the user to the api user for the session time
        # (max 24hrs) and issue a new token based on the issued trust
        admin_session = utils.get_admin_session()
        admin_token = admin_session.auth.get_access(admin_session)
        keystone = keystone_v3.Client(session=session,
                                      auth_url=auth_url,
                                      endpoint_override=auth_url)
        trust = keystone.trusts.create(
            trustee_user=admin_token['user']['id'],
            trustor_user=unscoped_auth_ref['user']['id'],
            impersonation=True,
            allow_redelegation=True,
            expires_at=datetime.utcnow() + relativedelta(
                hours=getattr(settings, 'HORIZON_SESSION_LENGTH', 24)))
        admin_session = utils.get_admin_session(
            private_session=True,
            scope={"OS-TRUST:trust": {"id": trust.id}})
        unscoped_auth_ref = admin_session.auth.get_access(session)
        return self._process_auth_ref(request, unscoped_auth_ref, auth_url)