Example #1
0
    def __init__(self, *args, **kwargs):
        # If an specified login is passed in, retrieve it & remove it from kwargs dict
        tag = kwargs.get('tag', None)
        if 'tag' in kwargs:
            del kwargs['tag']

        logger.debug('tag is "{0}"'.format(tag))

        super(LoginForm, self).__init__(*args, **kwargs)
        choices = []
        nonStandard = []
        standard = []

        auths = Authenticator.getByTag(tag)

        for a in auths:
            if a.getType() is None:
                continue
            if a.getType().isCustom() and tag == 'disabled':
                continue
            choices.append((a.uuid, a.name))
            if a.getType().isCustom():
                nonStandard.append(a.uuid)
            else:
                standard.append(a.uuid)

        self.fields['authenticator'].choices = choices
        self.fields['nonStandard'].initial = ','.join(nonStandard)
        self.fields['standard'].initial = ','.join(standard)
Example #2
0
    def __init__(self, *args, **kwargs):
        # If an specified login is passed in, retrieve it & remove it from kwargs dict
        tag = kwargs.get('tag', None)
        if 'tag' in kwargs:
            del kwargs['tag']

        # Parent init
        super(LoginForm, self).__init__(*args, **kwargs)

        choices = []

        for a in Authenticator.getByTag(tag):
            if not a.getType():  # Not existing manager for the auth?
                continue
            if a.getType().isCustom() and tag == 'disabled':
                continue
            choices.append((a.uuid, a.name))

        self.fields['authenticator'].choices = choices
Example #3
0
def login(request, tag=None):
    """
    View responsible of logging in an user
    :param request:  http request
    :param tag: tag of login auth
    """
    # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt())
    response = None

    # Default empty form
    form = LoginForm(tag=tag)

    if request.method == 'POST':
        form = LoginForm(request.POST, tag=tag)
        user, data = checkLogin(request, form, tag)
        if user:
            response = HttpResponseRedirect(reverse('uds.web.views.index'))
            webLogin(request, response, user, data)  # data is user password here
        else:  # error, data = error
            if isinstance(data, int):
                return errors.errorView(request, data)
            # Error to notify
            form.add_error(None, data)

    if response is None:
        response = render(request,
            theme.template('login.html'),
            {
                'form': form,
                'authenticators': Authenticator.getByTag(tag),
                'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True),
                'version': VERSION

            }
        )

    getUDSCookie(request, response)

    return response
Example #4
0
def login(request, tag=None):
    """
    View responsible of logging in an user
    :param request:  http request
    :param tag: tag of login auth
    """
    # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt())

    host = request.META.get('HTTP_HOST') or request.META.get('SERVER_NAME') or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    # Get Authenticators limitation
    logger.debug('Host: {0}'.format(host))
    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(False) is True:
        if tag is None:
            try:
                Authenticator.objects.get(small_name=host)
                tag = host
            except Exception:
                try:
                    tag = Authenticator.objects.order_by('priority')[0].small_name
                except Exception:  # There is no authenticators yet, simply allow global login to nowhere.. :-)
                    tag = None

    logger.debug('Tag: {0}'.format(tag))

    if request.method == 'POST':
        if 'uds' not in request.COOKIES:
            logger.debug('Request does not have uds cookie')
            return errors.errorView(request, errors.COOKIES_NEEDED)  # We need cookies to keep session data
        request.session.cycle_key()

        # Get data from form
        form = LoginForm(request.POST, tag=tag)
        if form.is_valid():
            os = request.os
            try:
                authenticator = Authenticator.objects.get(uuid=processUuid(form.cleaned_data['authenticator']))
            except Exception:
                authenticator = Authenticator()
            userName = form.cleaned_data['user']
            if GlobalConfig.LOWERCASE_USERNAME.getBool(True) is True:
                userName = userName.lower()

            cache = Cache('auth')
            cacheKey = str(authenticator.id) + userName
            tries = cache.get(cacheKey)
            if tries is None:
                tries = 0
            if authenticator.getInstance().blockUserOnLoginFailures is True and tries >= GlobalConfig.MAX_LOGIN_TRIES.getInt():
                form.add_error(None, 'Too many authentication errors. User temporarily  blocked.')
                authLogLogin(request, authenticator, userName, 'Temporarily blocked')
            else:
                password = form.cleaned_data['password']
                user = None
                if password == '':
                    password = '******'
                user = authenticate(userName, password, authenticator)
                logger.debug('User: {}'.format(user))

                if user is None:
                    logger.debug("Invalid credentials for user {0}".format(userName))
                    tries += 1
                    cache.put(cacheKey, tries, GlobalConfig.LOGIN_BLOCK.getInt())
                    form.add_error(None, ugettext('Invalid credentials'))
                    authLogLogin(request, authenticator, userName, 'Invalid credentials')
                else:
                    logger.debug('User {} has logged in'.format(userName))
                    cache.remove(cacheKey)  # Valid login, remove cached tries
                    response = HttpResponseRedirect(reverse('uds.web.views.index'))
                    webLogin(request, response, user, form.cleaned_data['password'])
                    # Add the "java supported" flag to session
                    request.session['OS'] = os
                    if form.cleaned_data['logouturl'] != '':
                        logger.debug('The logoout url will be {}'.format(form.cleaned_data['logouturl']))
                        request.session['logouturl'] = form.cleaned_data['logouturl']
                    authLogLogin(request, authenticator, user.name)
                    return response
        else:
            logger.info('Invalid form received')
    else:
        form = LoginForm(tag=tag)

    response = render(request,
        theme.template('login.html'),
        {
            'form': form,
            'authenticators': Authenticator.getByTag(tag),
            'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True),
            'version': VERSION

        }
    )

    getUDSCookie(request, response)

    return response
Example #5
0
def login(request, tag=None):
    """
    View responsible of logging in an user
    :param request:  http request
    :param tag: tag of login auth
    """
    # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt())

    host = request.META.get('HTTP_HOST') or request.META.get('SERVER_NAME') or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    # Get Authenticators limitation
    logger.debug('Host: {0}'.format(host))
    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(False) is True:
        if tag is None:
            try:
                Authenticator.objects.get(small_name=host)
                tag = host
            except Exception:
                try:
                    tag = Authenticator.objects.order_by('priority')[0].small_name
                except Exception:  # There is no authenticators yet, simply allow global login to nowhere.. :-)
                    tag = None

    logger.debug('Tag: {0}'.format(tag))

    logger.debug(request.method)
    if request.method == 'POST':
        if 'uds' not in request.COOKIES:
            logger.debug('Request does not have uds cookie')
            return errors.errorView(request, errors.COOKIES_NEEDED)  # We need cookies to keep session data
        form = LoginForm(request.POST, tag=tag)
        if form.is_valid():
            os = request.os
            try:
                authenticator = Authenticator.objects.get(uuid=processUuid(form.cleaned_data['authenticator']))
            except Exception:
                authenticator = Authenticator()
            userName = form.cleaned_data['user']
            if GlobalConfig.LOWERCASE_USERNAME.getBool(True) is True:
                userName = userName.lower()

            cache = Cache('auth')
            cacheKey = str(authenticator.id) + userName
            tries = cache.get(cacheKey)
            if tries is None:
                tries = 0
            if authenticator.getInstance().blockUserOnLoginFailures is True and tries >= GlobalConfig.MAX_LOGIN_TRIES.getInt():
                form.add_error(None, 'Too many authentication errors. User temporarily  blocked.')
                authLogLogin(request, authenticator, userName, 'Temporarily blocked')
            else:
                password = form.cleaned_data['password']
                user = None
                if password == '':
                    password = '******'
                user = authenticate(userName, password, authenticator)
                logger.debug('User: {}'.format(user))

                if user is None:
                    logger.debug("Invalid user {0} (access denied)".format(userName))
                    tries += 1
                    cache.put(cacheKey, tries, GlobalConfig.LOGIN_BLOCK.getInt())
                    form.add_error(None, ugettext('Access denied'))
                    authLogLogin(request, authenticator, userName, 'Access denied (user not allowed by UDS)')
                else:
                    request.session.cycle_key()

                    logger.debug('User {} has logged in'.format(userName))
                    cache.remove(cacheKey)  # Valid login, remove cached tries
                    response = HttpResponseRedirect(reverse('uds.web.views.index'))
                    webLogin(request, response, user, form.cleaned_data['password'])
                    # Add the "java supported" flag to session
                    request.session['OS'] = os
                    if form.cleaned_data['logouturl'] != '':
                        logger.debug('The logoout url will be {}'.format(form.cleaned_data['logouturl']))
                        request.session['logouturl'] = form.cleaned_data['logouturl']
                    authLogLogin(request, authenticator, user.name)
                    return response
        else:
            logger.info('Invalid form received')
    else:
        form = LoginForm(tag=tag)

    response = render(request,
        theme.template('login.html'),
        {
            'form': form,
            'authenticators': Authenticator.getByTag(tag),
            'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True),
            'version': VERSION

        }
    )

    getUDSCookie(request, response)

    return response