Beispiel #1
0
def create(request):
    try:
        form = forms.CreateForm(request.POST)

        data = common.validate_form(
            form, ('username', 'email', 'openid', 'password'))

        try:
            user = models.User.objects.create_user(data['username'],
                                                   data['email'],
                                                   data['password'])
        except db.IntegrityError:
            raise common.DuplicateUserError(username=data['username'])

        models.Auth.objects.create(openid_url=data['openid'], user=user)

        try:
            send_mail(CREATE_SUBJECT,
                      '',
                      settings.ADMIN_EMAIL, [user.email],
                      html_message=CREATE_MESSAGE.format(
                          login_url=settings.LOGIN_URL,
                          admin_email=settings.ADMIN_EMAIL))
        except Exception:
            logger.exception('Error sending confirmation email')

            pass
    except WPSError as e:
        logger.exception('Error creating account')

        return common.failed(str(e))
    else:
        return common.success('Successfully created account for "{}"'.format(
            data['username']))
Beispiel #2
0
def login_oauth2(request):
    try:
        common.authentication_required(request)

        logger.info('Authenticating OAuth2 for {}'.format(
            request.user.auth.openid_url))

        auth_service, cert_service = openid.services(
            request.user.auth.openid_url, (URN_AUTHORIZE, URN_RESOURCE))

        redirect_url, state = oauth2.get_authorization_url(
            auth_service.server_url, cert_service.server_url)

        logger.info('Retrieved authorization url for OpenID {}'.format(
            request.user.auth.openid_url))

        request.session.update({
            'oauth_state': state,
            'openid': request.user.auth.openid_url
        })
    except WPSError as e:
        logger.exception('Error authenticating OAuth2')

        return common.failed(str(e))
    else:
        return common.success({'redirect': redirect_url})
Beispiel #3
0
def forgot_username(request):
    try:
        try:
            email = request.GET['email']
        except KeyError as e:
            raise common.MissingParameterError(name=str(e))

        logger.info('Recovering username for "{}"'.format(email))

        try:
            user = models.User.objects.get(email=email)
        except models.User.DoesNotExist:
            raise common.UserEmailDoesNotExistError(email=email)

        try:
            send_mail(
                FORGOT_USERNAME_SUBJECT,
                FORGOT_USERNAME_MESSAGE.format(username=user.username,
                                               login_url=settings.LOGIN_URL),
                settings.ADMIN_EMAIL, [user.email])
        except:
            raise common.MailError(email=user.email)
    except WPSError as e:
        logger.exception('Error recovering username')

        return common.failed(str(e))
    else:
        return common.success({'redirect': settings.LOGIN_URL})
Beispiel #4
0
def user_login(request):
    try:
        form = forms.LoginForm(request.POST)

        data = common.validate_form(form, ('username', 'password'))

        logger.info('Attempting to login user {}'.format(data['username']))

        user = authenticate(request,
                            username=data['username'],
                            password=data['password'])

        if user is None:
            raise common.AuthenticationError(user=data['username'])

        login(request, user)
    except WPSError as e:
        logger.exception('Error logging user in')

        return common.failed(str(e))
    else:
        data = common.user_to_json(user)

        data['expires'] = request.session.get_expiry_date()

        return common.success(data)
Beispiel #5
0
def reset_password(request):
    try:
        try:
            token = str(request.GET['token'])

            username = str(request.GET['username'])

            password = str(request.GET['password'])
        except KeyError as e:
            raise common.MissingParameterError(name=str(e))

        logger.info('Resetting password for "{}"'.format(username))

        try:
            user = models.User.objects.get(username=username)
        except models.User.DoesNotExist:
            raise common.UserDoesNotExistError(username=username)

        try:
            extra = json.loads(user.auth.extra)
        except Exception:
            extra = {}

        try:
            reset_token = extra['reset_token']

            reset_expire = extra['reset_expire']
        except KeyError as e:
            raise ResetPasswordInvalidStateError()
        else:
            del extra['reset_token']

            del extra['reset_expire']

        expires = datetime.datetime.strptime(reset_expire, '%x %X')

        if datetime.datetime.now() > expires:
            raise ResetPasswordTokenExpiredError()

        if reset_token != token:
            raise ResetPasswordTokenMismatchError()

        user.auth.extra = json.dumps(extra)

        user.auth.save()

        user.set_password(password)

        user.save()

        logger.info('Successfully reset password for "{}"'.format(username))
    except WPSError as e:
        return common.failed(str(e))
    else:
        return common.success({'redirect': settings.LOGIN_URL})
def login_mpc(request):
    try:
        common.authentication_required(request)

        form = forms.MPCForm(request.POST)

        data = common.validate_form(form, ('username', 'password'))

        logger.info('Authenticating MyProxyClient for {}'.format(
            data['username']))

        services = openid.services(request.user.auth.openid_url, (URN_MPC, ))

        g = re.match('socket://(.*):(.*)', services[0].server_url)

        if g is None or len(g.groups()) != 2:
            raise MPCEndpointParseError()

        host, port = g.groups()

        from OpenSSL import SSL

        MyProxyClient.SSL_METHOD = SSL.TLSv1_2_METHOD

        try:
            m = MyProxyClient(hostname=host, caCertDir=settings.WPS_CA_PATH)

            c = m.logon(data['username'], data['password'], bootstrap=True)
        except Exception as e:
            raise common.AuthenticationError(user=data['username'])

        logger.info(
            'Authenticated with MyProxyClient backend for user {}'.format(
                data['username']))

        request.user.auth.update('myproxyclient', c)
    except WPSError as e:
        logger.exception('Error authenticating MyProxyClient')

        return common.failed(str(e))
    else:
        metrics.track_login(metrics.WPS_MPC_LOGIN_SUCCESS,
                            request.user.auth.openid_url)

        return common.success({
            'type': request.user.auth.type,
            'api_key': request.user.auth.api_key
        })
    finally:
        if not request.user.is_anonymous:
            metrics.track_login(metrics.WPS_MPC_LOGIN,
                                request.user.auth.openid_url)
Beispiel #7
0
def user_logout(request):
    try:
        common.authentication_required(request)

        logger.info('Logging user {} out'.format(request.user.username))

        logout(request)
    except WPSError as e:
        logger.exception('Error logging user out')

        return common.failed(str(e))
    else:
        return common.success('Logged out')
Beispiel #8
0
def user_login_openid(request):
    try:
        form = forms.OpenIDForm(request.POST)

        data = common.validate_form(form, ('openid_url', ))

        url = openid.begin(request, data['openid_url'])
    except WPSError as e:
        logger.exception('Error logging user in with OpenID')

        return common.failed(str(e))
    else:
        return common.success({'redirect': url})
Beispiel #9
0
def processes(request):
    try:
        common.authentication_required(request)

        data = [
            dict(identifier=x.identifier, description=x.description)
            for x in models.Process.objects.all() if x.enabled
        ]
    except WPSError as e:
        logger.exception('Error retrieving processes')

        return common.failed(e.message)
    else:
        return common.success(data)
Beispiel #10
0
def forgot_password(request):
    try:
        try:
            username = request.GET['username']
        except KeyError as e:
            raise common.MissingParameterError(name=str(e))

        logger.info(
            'Starting password reset process for user "{}"'.format(username))

        try:
            user = models.User.objects.get(username=username)
        except models.User.DoesNotExist:
            raise common.UserDoesNotExistError(username=username)

        try:
            extra = json.loads(user.auth.extra)
        except Exception:
            extra = {}

        extra['reset_token'] = ''.join(
            random.choice(string.ascii_letters + string.digits)
            for _ in xrange(64))

        extra['reset_expire'] = datetime.datetime.now() + datetime.timedelta(1)

        user.auth.extra = json.dumps(extra,
                                     default=lambda x: x.strftime('%x %X'))

        user.auth.save()

        reset_url = '{}?token={}&username={}'.format(
            settings.PASSWORD_RESET_URL, extra['reset_token'], user.username)

        try:
            send_mail(FORGOT_PASSWORD_SUBJECT,
                      '',
                      settings.ADMIN_EMAIL, [user.email],
                      html_message=FORGOT_PASSWORD_MESSAGE.format(
                          username=user.username, reset_url=reset_url))
        except:
            raise common.MailError(email=user.email)
    except WPSError as e:
        return common.failed(str(e))
    else:
        return common.success({'redirect': settings.LOGIN_URL})
Beispiel #11
0
def user_login_openid(request):
    try:
        form = forms.OpenIDForm(request.POST)

        data = common.validate_form(form, ('openid_url', 'next'))

        url = openid.begin(request, **data)
    except WPSError as e:
        logger.exception('Error logging user in with OpenID')

        return common.failed(str(e))
    else:
        return common.success({'redirect': url})
    finally:
        if 'openid_url' in request.POST:
            metrics.track_login(metrics.WPS_OPENID_LOGIN,
                                request.POST['openid_url'])