Exemplo n.º 1
0
def signup(request):
    """ The signup page """
    signup_form = None
    if request.method == "POST":
        signup_form = SignupForm(request.POST)
        if signup_form.is_valid():
            try:
                try:
                    LDAPUser.objects.get(
                        username=signup_form.cleaned_data['username'])
                except LDAPUser.DoesNotExist:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
                else:
                    raise OkupyError('Username already exists')
                try:
                    LDAPUser.objects.get(
                        email__contains=signup_form.cleaned_data['email'])
                except LDAPUser.DoesNotExist:
                    pass
                else:
                    raise OkupyError('Email already exists')
                queued_user = Queue(
                    username=signup_form.cleaned_data['username'],
                    first_name=signup_form.cleaned_data['first_name'],
                    last_name=signup_form.cleaned_data['last_name'],
                    email=signup_form.cleaned_data['email'],
                    password=signup_form.cleaned_data['password_origin'],
                )
                try:
                    queued_user.save()
                except IntegrityError:
                    raise OkupyError('Account is already pending activation')
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact the database")
                send_mail(
                    '%sAccount Activation' % settings.EMAIL_SUBJECT_PREFIX,
                    'To confirm your email address, please click the \
                    following link:\n%s' % queued_user.encrypted_id,
                    '%s' % settings.SERVER_EMAIL,
                    [signup_form.cleaned_data['email']]
                )
                messages.info(
                    request, "You will shortly receive an activation mail")
                return redirect(login)
            except OkupyError as error:
                messages.error(request, str(error))
    else:
        signup_form = SignupForm()
    return render(request, 'signup.html', {
        'signup_form': signup_form,
    })
Exemplo n.º 2
0
def signup(request):
    """ The signup page """
    signup_form = None
    if request.method == "POST":
        signup_form = SignupForm(request.POST)
        if signup_form.is_valid():
            try:
                try:
                    LDAPUser.objects.get(
                        username=signup_form.cleaned_data['username'])
                except LDAPUser.DoesNotExist:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
                else:
                    raise OkupyError('Username already exists')
                try:
                    LDAPUser.objects.get(
                        email__contains=signup_form.cleaned_data['email'])
                except LDAPUser.DoesNotExist:
                    pass
                else:
                    raise OkupyError('Email already exists')
                queued_user = Queue(
                    username=signup_form.cleaned_data['username'],
                    first_name=signup_form.cleaned_data['first_name'],
                    last_name=signup_form.cleaned_data['last_name'],
                    email=signup_form.cleaned_data['email'],
                    password=signup_form.cleaned_data['password_origin'],
                )
                try:
                    queued_user.save()
                except IntegrityError:
                    raise OkupyError('Account is already pending activation')
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact the database")
                send_mail(
                    '%sAccount Activation' % settings.EMAIL_SUBJECT_PREFIX,
                    'To confirm your email address, please click the \
                    following link:\n%s' % queued_user.encrypted_id,
                    '%s' % settings.SERVER_EMAIL,
                    [signup_form.cleaned_data['email']])
                messages.info(request,
                              "You will shortly receive an activation mail")
                return redirect(login)
            except OkupyError as error:
                messages.error(request, str(error))
    else:
        signup_form = SignupForm()
    return render(request, 'signup.html', {
        'signup_form': signup_form,
    })
Exemplo n.º 3
0
def activate(request, token):
    """
    The page that users get to activate their accounts
    It is in the form /activate/$TOKEN
    """
    try:
        try:
            queued = Queue.objects.get(encrypted_id=token)
        except (Queue.DoesNotExist, OverflowError, TypeError, ValueError):
            raise OkupyError('Invalid URL')
        except Exception as error:
            logger.critical(error, extra=log_extra_data(request))
            logger_mail.exception(error)
            raise OkupyError("Can't contact the database")
        # get max uidNumber
        try:
            uidnumber = LDAPUser.objects.latest('uid').uid + 1
        except LDAPUser.DoesNotExist:
            uidnumber = 1
        except Exception as error:
            logger.critical(error, extra=log_extra_data(request))
            logger_mail.exception(error)
            raise OkupyError("Can't contact LDAP server")
        # add account to ldap
        new_user = LDAPUser(
            object_class=settings.AUTH_LDAP_USER_OBJECTCLASS,
            last_name=queued.last_name,
            full_name='%s %s' % (queued.first_name, queued.last_name),
            password=[ldap_md5_crypt.encrypt(queued.password)],
            first_name=queued.first_name,
            email=[queued.email],
            username=queued.username,
            uid=uidnumber,
            gid=100,
            gecos='%s %s' % (queued.first_name, queued.last_name),
            home_directory='/home/%s' % queued.username,
            ACL=['user.group'],
        )
        new_user.save()
        # remove queued account from DB
        queued.delete()
        messages.success(request,
                         "Your account has been activated successfully")
    except OkupyError as error:
        messages.error(request, str(error))
    return redirect(login)
Exemplo n.º 4
0
def activate(request, token):
    """
    The page that users get to activate their accounts
    It is in the form /activate/$TOKEN
    """
    try:
        try:
            queued = Queue.objects.get(encrypted_id=token)
        except (Queue.DoesNotExist, OverflowError, TypeError, ValueError):
            raise OkupyError('Invalid URL')
        except Exception as error:
            logger.critical(error, extra=log_extra_data(request))
            logger_mail.exception(error)
            raise OkupyError("Can't contact the database")
        # get max uidNumber
        try:
            uidnumber = LDAPUser.objects.latest('uid').uid + 1
        except LDAPUser.DoesNotExist:
            uidnumber = 1
        except Exception as error:
            logger.critical(error, extra=log_extra_data(request))
            logger_mail.exception(error)
            raise OkupyError("Can't contact LDAP server")
        # add account to ldap
        new_user = LDAPUser(
            object_class=settings.AUTH_LDAP_USER_OBJECTCLASS,
            last_name=queued.last_name,
            full_name='%s %s' % (queued.first_name, queued.last_name),
            password=[ldap_md5_crypt.encrypt(queued.password)],
            first_name=queued.first_name,
            email=[queued.email],
            username=queued.username,
            uid=uidnumber,
            gid=100,
            gecos='%s %s' % (queued.first_name, queued.last_name),
            home_directory='/home/%s' % queued.username,
            ACL=['user.group'],
        )
        new_user.save()
        # remove queued account from DB
        queued.delete()
        messages.success(
            request, "Your account has been activated successfully")
    except OkupyError as error:
        messages.error(request, str(error))
    return redirect(login)
Exemplo n.º 5
0
def contact_settings(request):
    """ Contact details """
    with get_bound_ldapuser(request) as user_info:
        contact_settings = None
        if request.method == "POST":
            contact_settings = ContactSettingsForm(request.POST)
            if contact_settings.is_valid():
                try:
                    gpg_fingerprint = contact_settings.cleaned_data[
                        'gpg_fingerprint']
                    im = contact_settings.cleaned_data['im']
                    latitude = contact_settings.cleaned_data['latitude']
                    location = contact_settings.cleaned_data['location']
                    longitude = contact_settings.cleaned_data['longitude']
                    phone = contact_settings.cleaned_data['phone']
                    website = contact_settings.cleaned_data['website']

                    if user_info.location != location:
                        user_info.location = location

                    if user_info.phone != phone:
                        user_info.phone = phone

                    if user_info.website != website:
                        user_info.website.pop()
                        user_info.website.append(website)

                    if user_info.im != im:
                        user_info.im.pop()
                        user_info.im.append(im)

                    if user_info.longitude != longitude:
                        user_info.longitude = longitude

                    if user_info.latitude != latitude:
                        user_info.latitude = latitude

                    if user_info.gpg_fingerprint != gpg_fingerprint:
                        user_info.gpg_fingerprint.pop()
                        user_info.gpg_fingerprint.append(gpg_fingerprint)

                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            contact_settings = ContactSettingsForm()

        return render(request, 'settings-contact.html', {
            'contact_settings': contact_settings,
            'user_info': user_info,
        })
Exemplo n.º 6
0
def logout(request):
    """ The logout page """
    try:
        remove_secondary_password(request)
    except Exception as error:
        logger.critical(error, extra=log_extra_data(request))
        logger_mail.exception(error)
    finally:
        _logout(request)
    return redirect(login)
Exemplo n.º 7
0
def logout(request):
    """ The logout page """
    try:
        remove_secondary_password(request)
    except Exception as error:
        logger.critical(error, extra=log_extra_data(request))
        logger_mail.exception(error)
    finally:
        _logout(request)
    return redirect(login)
Exemplo n.º 8
0
def gentoo_dev_settings(request):
    """ Gentoo related information """
    with get_bound_ldapuser(request) as user_info:
        gentoo_account_settings = None
        if request.method == "POST":
            gentoo_account_settings = GentooAccountSettingsForm(request.POST)
            if gentoo_account_settings.is_valid():
                try:
                    devbug = gentoo_account_settings.cleaned_data[
                        'developer_bug']
                    gentoo_join_date = gentoo_account_settings.cleaned_data[
                        'gentoo_join_date']
                    gentoo_mentor = gentoo_account_settings.cleaned_data[
                        'mentor']
                    ssh_pubkey = gentoo_account_settings.cleaned_data[
                        'ssh_key']

                    if user_info.developer_bug != devbug:
                        user_info.developer_bug.append(devbug)

                    if user_info.gentoo_join_date != gentoo_join_date:
                        user_info.gentoo_join_date.append(gentoo_join_date)

                    if user_info.mentor != gentoo_mentor:
                        user_info.mentor.append(gentoo_mentor)

                    if ssh_pubkey:
                        user_info.ssh_key.append(ssh_pubkey)

                    if user_info.is_retired or user_info.gentoo_retire_date:
                        gentoo_retire_date = gentoo_account_settings.cleaned_data[
                            'gentoo_retire_date']
                        if user_info.gentoo_retire_date != gentoo_retire_date:
                            user_info.gentoo_retire_date.append(
                                gentoo_retire_date)

                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            gentoo_account_settings = GentooAccountSettingsForm()

        return render(request, 'settings-gentoo.html', {
            'gentoo_account_settings': gentoo_account_settings,
            'user_info': user_info,
        })
Exemplo n.º 9
0
def password_settings(request):
    """ Password settings """
    with get_bound_ldapuser(request) as user_info:
        password_settings = None
        if request.method == "POST":
            password_settings = PasswordSettingsForm(request.POST)
            if password_settings.is_valid():
                try:
                    new_password = password_settings.cleaned_data[
                        'new_password']
                    new_password_verify = password_settings.cleaned_data[
                        'new_password_verify']
                    old_password = password_settings.cleaned_data[
                        'old_password']

                    if old_password and (new_password == new_password_verify):
                        for hash in list(user_info.password):
                            print hash
                            try:
                                if ldap_md5_crypt.verify(old_password, hash):
                                    user_info.password.append(
                                        ldap_md5_crypt.encrypt(
                                            new_password_verify))
                                    user_info.password.remove(hash)
                                    break
                            except ValueError:
                                # ignore unknown hashes
                                pass
                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            password_settings = PasswordSettingsForm()

        return render(request, 'settings-password.html', {
            'password_settings': password_settings,
            'user_info': user_info,
        })
Exemplo n.º 10
0
def password_settings(request):
    """ Password settings """
    with get_bound_ldapuser(request) as user_info:
        password_settings = None
        if request.method == "POST":
            password_settings = PasswordSettingsForm(request.POST)
            if password_settings.is_valid():
                try:
                    new_password = password_settings.cleaned_data[
                        'new_password']
                    new_password_verify = password_settings.cleaned_data[
                        'new_password_verify']
                    old_password = password_settings.cleaned_data[
                        'old_password']

                    if old_password and (new_password == new_password_verify):
                        for hash in list(user_info.password):
                            print hash
                            try:
                                if ldap_md5_crypt.verify(old_password, hash):
                                    user_info.password.append(
                                        ldap_md5_crypt.encrypt(
                                            new_password_verify))
                                    user_info.password.remove(hash)
                                    break
                            except ValueError:
                                # ignore unknown hashes
                                pass
                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            password_settings = PasswordSettingsForm()

        return render(request, 'settings-password.html', {
            'password_settings': password_settings,
            'user_info': user_info,
        })
Exemplo n.º 11
0
def profile_settings(request):
    """ Primary account settings, """
    with get_bound_ldapuser(request) as user_info:
        profile_settings = None
        if request.method == "POST":
            profile_settings = ProfileSettingsForm(request.POST)
            if profile_settings.is_valid():
                try:
                    #birthday = profile_settings.cleaned_data['birthday']
                    first_name = profile_settings.cleaned_data['first_name']
                    last_name = profile_settings.cleaned_data['last_name']

                    if user_info.first_name != first_name:
                        user_info.first_name = first_name

                    if user_info.last_name != last_name:
                        user_info.last_name = last_name

                    user_info.full_name = '%s %s' % (first_name, last_name)
                    user_info.gecos = '%s %s' % (first_name, last_name)

                    """
                    if user_info.birthday != birthday:
                        user_info.birthday = birthday
                    """
                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            profile_settings = ProfileSettingsForm()

        return render(request, 'settings-profile.html', {
            'profile_settings': profile_settings,
            'user_info': user_info,
        })
Exemplo n.º 12
0
def profile_settings(request):
    """ Primary account settings, """
    with get_bound_ldapuser(request) as user_info:
        profile_settings = None
        if request.method == "POST":
            profile_settings = ProfileSettingsForm(request.POST)
            if profile_settings.is_valid():
                try:
                    #birthday = profile_settings.cleaned_data['birthday']
                    first_name = profile_settings.cleaned_data['first_name']
                    last_name = profile_settings.cleaned_data['last_name']

                    if user_info.first_name != first_name:
                        user_info.first_name = first_name

                    if user_info.last_name != last_name:
                        user_info.last_name = last_name

                    user_info.full_name = '%s %s' % (first_name, last_name)
                    user_info.gecos = '%s %s' % (first_name, last_name)
                    """
                    if user_info.birthday != birthday:
                        user_info.birthday = birthday
                    """
                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            profile_settings = ProfileSettingsForm()

        return render(request, 'settings-profile.html', {
            'profile_settings': profile_settings,
            'user_info': user_info,
        })
Exemplo n.º 13
0
def email_settings(request):
    """ Email Settings """
    with get_bound_ldapuser(request) as user_info:
        email_settings = None
        if request.method == "POST":
            email_settings = EmailSettingsForm(request.POST)
            if email_settings.is_valid():
                try:
                    email = email_settings.cleaned_data['email']
                    gravatar_mail = email_settings.cleaned_data['gravatar']

                    if request.POST.get('delete'):
                        user_info.email.remove(email)
                    else:
                        user_info.email.append(email)

                    if gravatar_mail:
                        gravatar_hash = hashlib.md5(gravatar_mail).hexdigest()
                        user_info.gravatar = gravatar_hash

                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            email_settings = EmailSettingsForm()

        return render(request, 'settings-email.html', {
            'email_settings': email_settings,
            'user_info': user_info,
        })
Exemplo n.º 14
0
def email_settings(request):
    """ Email Settings """
    with get_bound_ldapuser(request) as user_info:
        email_settings = None
        if request.method == "POST":
            email_settings = EmailSettingsForm(request.POST)
            if email_settings.is_valid():
                try:
                    email = email_settings.cleaned_data['email']
                    gravatar_mail = email_settings.cleaned_data['gravatar']

                    if request.POST.get('delete'):
                        user_info.email.remove(email)
                    else:
                        user_info.email.append(email)

                    if gravatar_mail:
                        gravatar_hash = hashlib.md5(gravatar_mail).hexdigest()
                        user_info.gravatar = gravatar_hash

                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            email_settings = EmailSettingsForm()

        return render(request, 'settings-email.html', {
            'email_settings': email_settings,
            'user_info': user_info,
        })
Exemplo n.º 15
0
def gentoo_dev_settings(request):
    """ Gentoo related information """
    with get_bound_ldapuser(request) as user_info:
        gentoo_account_settings = None
        if request.method == "POST":
            gentoo_account_settings = GentooAccountSettingsForm(request.POST)
            if gentoo_account_settings.is_valid():
                try:
                    devbug = gentoo_account_settings.cleaned_data[
                        'developer_bug']
                    gentoo_join_date = gentoo_account_settings.cleaned_data[
                        'gentoo_join_date']
                    gentoo_mentor = gentoo_account_settings.cleaned_data[
                        'mentor']
                    gentoo_retire_date = gentoo_account_settings.cleaned_data[
                        'gentoo_retire_date']
                    gentoo_mentor = gentoo_account_settings.cleaned_data[
                        'mentor']
                    planet_feed = gentoo_account_settings.cleaned_data[
                        'planet_feed']
                    universe_feed = gentoo_account_settings.cleaned_data[
                        'universe_feed']

                    if request.POST.get('delete_devbug'):
                        user_info.devbug.remove(devbug)
                    elif devbug and (not devbug in user_info.developer_bug):
                        user_info.developer_bug.append(devbug)

                    if request.POST.get('delete_gjd'):
                        user_info.gentoo_join_date.remove(gentoo_join_date)
                    elif gentoo_join_date and (not gentoo_join_date
                                               in user_info.gentoo_join_date):
                        user_info.gentoo_join_date.append(gentoo_join_date)

                    if request.POST.get('delete_mentor'):
                        user_info.mentor.remove(gentoo_mentor)
                    elif gentoo_mentor and \
                            (not gentoo_mentor in user_info.mentor):
                        user_info.mentor.append(gentoo_mentor)

                    if user_info.gentoo_retire_date:
                        if request.POST.get('delete_grd'):
                            user_info.gentoo_retire_date.remove(
                                gentoo_retire_date)
                        elif gentoo_retire_date and (
                                not gentoo_retire_date
                                in user_info.gentoo_retire_date):
                            user_info.gentoo_retire_date.append(
                                gentoo_retire_date)

                    if user_info.planet_feed != planet_feed:
                        user_info.planet_feed = planet_feed

                    if user_info.universe_feed != universe_feed:
                        user_info.universe_feed = universe_feed

                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            gentoo_account_settings = GentooAccountSettingsForm()

        return render(
            request, 'settings-gentoo.html', {
                'gentoo_account_settings': gentoo_account_settings,
                'user_info': user_info,
            })
Exemplo n.º 16
0
def contact_settings(request):
    """ Contact details """
    with get_bound_ldapuser(request) as user_info:
        contact_settings = None
        if request.method == "POST":
            contact_settings = ContactSettingsForm(request.POST)
            if contact_settings.is_valid():
                try:
                    gpg_fingerprint = contact_settings.cleaned_data[
                        'gpg_fingerprint']
                    im = contact_settings.cleaned_data['im']
                    latitude = contact_settings.cleaned_data['latitude']
                    location = contact_settings.cleaned_data['location']
                    longitude = contact_settings.cleaned_data['longitude']
                    phone = contact_settings.cleaned_data['phone']
                    website = contact_settings.cleaned_data['website']

                    if location and user_info.location != location:
                        user_info.location = location

                    if user_info.phone != phone:
                        user_info.phone = phone

                    if request.POST.get('delete_web'):
                        user_info.website.remove(website)
                    elif website and (not website in user_info.website):
                        user_info.website.append(website)

                    if request.POST.get('delete_im'):
                        user_info.im.remove(im)
                    elif im and (not im in user_info.im):
                        user_info.im.append(im)

                    if user_info.longitude != longitude:
                        user_info.longitude = longitude

                    if user_info.latitude != latitude:
                        user_info.latitude = latitude

                    if request.POST.get('delete_gpg'):
                        user_info.gpg_fingerprint.remove(gpg_fingerprint)
                    elif gpg_fingerprint and \
                            (not gpg_fingerprint in user_info.gpg_fingerprint):
                        user_info.gpg_fingerprint.append(gpg_fingerprint)

                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            contact_settings = ContactSettingsForm()

        return render(request, 'settings-contact.html', {
            'contact_settings': contact_settings,
            'user_info': user_info,
        })
Exemplo n.º 17
0
def login(request):
    """ The login page """
    user = None
    oreq = request.session.get('openid_request', None)
    # this can be POST or GET, and can be null or empty
    next = request.REQUEST.get('next') or reverse(index)
    is_otp = False
    login_form = None
    strong_auth_req = 'strong_auth_requested' in request.session

    if oreq:
        login_form_class = OpenIDLoginForm
    elif ('strong_auth_requested' in request.session
            and request.user.is_authenticated()):
        login_form_class = StrongAuthForm
    else:
        login_form_class = LoginForm

    try:
        if request.method != 'POST':
            pass
        elif 'cancel' in request.POST:
            # note: this wipes request.session
            _logout(request)
            if oreq is not None:
                oresp = oreq.answer(False)
                return render_openid_response(request, oresp)
        elif 'otp_token' in request.POST:
            # if user's not authenticated, go back to square one
            if not request.user.is_authenticated():
                raise OkupyError('OTP verification timed out')

            is_otp = True
            otp_form = OTPForm(request.POST)
            if otp_form.is_valid():
                token = otp_form.cleaned_data['otp_token']
            else:
                raise OkupyError('OTP verification failed')

            # prevent replay attacks and race conditions
            if not RevokedToken.add(token, request.user):
                raise OkupyError('OTP verification failed')
            dev = django_otp.match_token(request.user, token)
            if not dev:
                raise OkupyError('OTP verification failed')
            django_otp.login(request, dev)
        else:
            login_form = login_form_class(request.POST)
            if login_form.is_valid():
                if login_form_class != StrongAuthForm:
                    username = login_form.cleaned_data['username']
                else:
                    username = request.user.username
                password = login_form.cleaned_data['password']
            else:
                raise OkupyError('Login failed')
            """
            Perform authentication, if it retrieves a user object then
            it was successful. If it retrieves None then it failed to login
            """
            try:
                user = authenticate(
                    request=request,
                    username=username,
                    password=password)
            except Exception as error:
                logger.critical(error, extra=log_extra_data(request))
                logger_mail.exception(error)
                raise OkupyError(
                    "Can't contact the LDAP server or the database")
            if not user:
                raise OkupyError('Login failed')

            if oreq:
                request.session['auto_logout'] = (
                    login_form.cleaned_data['auto_logout'])
    except OkupyError as error:
        messages.error(request, str(error))

    if user and user.is_active:
        _login(request, user)
        # prepare devices, and see if OTP is enabled
        init_otp(request)
        set_secondary_password(request=request, password=password)
    if request.user.is_authenticated():
        if (strong_auth_req
                and not 'secondary_password' in request.session):
            if request.method != 'POST':
                messages.info(request, 'You need to type in your password'
                              + ' again to perform this action')
        else:
            if request.user.is_verified():
                return redirect(next)
            login_form = OTPForm()
            is_otp = True
    if login_form is None:
        login_form = login_form_class()

    if is_otp or strong_auth_req:
        ssl_auth_form = None
        ssl_auth_uri = None
        ssh_auth_command = None
    else:
        encrypted_id = sessionrefcipher.encrypt(request.session)

        # TODO: it fails when:
        # 1. site is accessed via IP (auth.127.0.0.1),
        # 2. HTTP used on non-standard port (https://...:8000).
        ssl_auth_form = SSLCertLoginForm({
            'session': encrypted_id,
            'next': request.build_absolute_uri(next),
            'login_uri': request.build_absolute_uri(request.get_full_path()),
        })

        ssl_auth_host = 'auth.' + request.get_host()
        ssl_auth_path = reverse(ssl_auth)
        ssl_auth_uri = urljoin('https://' + ssl_auth_host, ssl_auth_path)

        if settings.SSH_BIND[1] == 22:
            ssh_port_opt = ''
        else:
            ssh_port_opt = '-p %d ' % settings.SSH_BIND[1]

        ssh_auth_command = 'ssh %sauth+%s@%s' % (
            ssh_port_opt,
            encrypted_id,
            request.get_host().split(':')[0])

    return render(request, 'login.html', {
        'login_form': login_form,
        'openid_request': oreq,
        'next': next,
        'ssl_auth_uri': ssl_auth_uri,
        'ssl_auth_form': ssl_auth_form,
        'ssh_auth_command': ssh_auth_command,
        'is_otp': is_otp,
    })
Exemplo n.º 18
0
def login(request):
    """ The login page """
    user = None
    oreq = request.session.get('openid_request', None)
    # this can be POST or GET, and can be null or empty
    next = request.REQUEST.get('next') or reverse(index)
    is_otp = False
    login_form = None
    strong_auth_req = 'strong_auth_requested' in request.session

    if oreq:
        login_form_class = OpenIDLoginForm
    elif ('strong_auth_requested' in request.session
          and request.user.is_authenticated()):
        login_form_class = StrongAuthForm
    else:
        login_form_class = LoginForm

    try:
        if request.method != 'POST':
            pass
        elif 'cancel' in request.POST:
            # note: this wipes request.session
            _logout(request)
            if oreq is not None:
                oresp = oreq.answer(False)
                return render_openid_response(request, oresp)
        elif 'otp_token' in request.POST:
            # if user's not authenticated, go back to square one
            if not request.user.is_authenticated():
                raise OkupyError('OTP verification timed out')

            is_otp = True
            otp_form = OTPForm(request.POST)
            if otp_form.is_valid():
                token = otp_form.cleaned_data['otp_token']
            else:
                raise OkupyError('OTP verification failed')

            # prevent replay attacks and race conditions
            if not RevokedToken.add(token, request.user):
                raise OkupyError('OTP verification failed')
            dev = django_otp.match_token(request.user, token)
            if not dev:
                raise OkupyError('OTP verification failed')
            django_otp.login(request, dev)
        else:
            login_form = login_form_class(request.POST)
            if login_form.is_valid():
                if login_form_class != StrongAuthForm:
                    username = login_form.cleaned_data['username']
                else:
                    username = request.user.username
                password = login_form.cleaned_data['password']
            else:
                raise OkupyError('Login failed')
            """
            Perform authentication, if it retrieves a user object then
            it was successful. If it retrieves None then it failed to login
            """
            try:
                user = authenticate(request=request,
                                    username=username,
                                    password=password)
            except Exception as error:
                logger.critical(error, extra=log_extra_data(request))
                logger_mail.exception(error)
                raise OkupyError(
                    "Can't contact the LDAP server or the database")
            if not user:
                raise OkupyError('Login failed')

            if oreq:
                request.session['auto_logout'] = (
                    login_form.cleaned_data['auto_logout'])
    except OkupyError as error:
        messages.error(request, str(error))

    if user and user.is_active:
        _login(request, user)
        # prepare devices, and see if OTP is enabled
        init_otp(request)
        set_secondary_password(request=request, password=password)
    if request.user.is_authenticated():
        if (strong_auth_req and not 'secondary_password' in request.session):
            if request.method != 'POST':
                messages.info(
                    request, 'You need to type in your password' +
                    ' again to perform this action')
        else:
            if request.user.is_verified():
                return redirect(next)
            login_form = OTPForm()
            is_otp = True
    if login_form is None:
        login_form = login_form_class()

    if is_otp or strong_auth_req:
        ssl_auth_form = None
        ssl_auth_uri = None
        ssh_auth_command = None
    else:
        encrypted_id = sessionrefcipher.encrypt(request.session)

        # TODO: it fails when:
        # 1. site is accessed via IP (auth.127.0.0.1),
        # 2. HTTP used on non-standard port (https://...:8000).
        ssl_auth_form = SSLCertLoginForm({
            'session':
            encrypted_id,
            'next':
            request.build_absolute_uri(next),
            'login_uri':
            request.build_absolute_uri(request.get_full_path()),
        })

        ssl_auth_host = 'auth.' + request.get_host()
        ssl_auth_path = reverse(ssl_auth)
        ssl_auth_uri = urljoin('https://' + ssl_auth_host, ssl_auth_path)

        if settings.SSH_BIND[1] == 22:
            ssh_port_opt = ''
        else:
            ssh_port_opt = '-p %d ' % settings.SSH_BIND[1]

        ssh_auth_command = 'ssh %sauth+%s@%s' % (
            ssh_port_opt, encrypted_id, request.get_host().split(':')[0])

    return render(
        request, 'login.html', {
            'login_form': login_form,
            'openid_request': oreq,
            'next': next,
            'ssl_auth_uri': ssl_auth_uri,
            'ssl_auth_form': ssl_auth_form,
            'ssh_auth_command': ssh_auth_command,
            'is_otp': is_otp,
        })
Exemplo n.º 19
0
def gentoo_dev_settings(request):
    """ Gentoo related information """
    with get_bound_ldapuser(request) as user_info:
        gentoo_account_settings = None
        if request.method == "POST":
            gentoo_account_settings = GentooAccountSettingsForm(request.POST)
            if gentoo_account_settings.is_valid():
                try:
                    devbug = gentoo_account_settings.cleaned_data[
                        'developer_bug']
                    gentoo_join_date = gentoo_account_settings.cleaned_data[
                        'gentoo_join_date']
                    gentoo_mentor = gentoo_account_settings.cleaned_data[
                        'mentor']
                    gentoo_retire_date = gentoo_account_settings.cleaned_data[
                        'gentoo_retire_date']
                    gentoo_mentor = gentoo_account_settings.cleaned_data[
                        'mentor']
                    planet_feed = gentoo_account_settings.cleaned_data[
                        'planet_feed']
                    universe_feed = gentoo_account_settings.cleaned_data[
                        'universe_feed']

                    if request.POST.get('delete_devbug'):
                        user_info.devbug.remove(devbug)
                    elif devbug and (not devbug in user_info.developer_bug):
                        user_info.developer_bug.append(devbug)

                    if request.POST.get('delete_gjd'):
                        user_info.gentoo_join_date.remove(gentoo_join_date)
                    elif gentoo_join_date and (not gentoo_join_date in user_info.gentoo_join_date):
                        user_info.gentoo_join_date.append(gentoo_join_date)

                    if request.POST.get('delete_mentor'):
                        user_info.mentor.remove(gentoo_mentor)
                    elif gentoo_mentor and \
                            (not gentoo_mentor in user_info.mentor):
                        user_info.mentor.append(gentoo_mentor)

                    if user_info.gentoo_retire_date:
                        if request.POST.get('delete_grd'):
                            user_info.gentoo_retire_date.remove(gentoo_retire_date)
                        elif gentoo_retire_date and (not gentoo_retire_date in user_info.gentoo_retire_date):
                            user_info.gentoo_retire_date.append(gentoo_retire_date)

                    if user_info.planet_feed != planet_feed:
                        user_info.planet_feed = planet_feed

                    if user_info.universe_feed != universe_feed:
                        user_info.universe_feed = universe_feed

                    try:
                        user_info.save()
                    except IntegrityError:
                        pass
                except ldap.TYPE_OR_VALUE_EXISTS:
                    pass
                except Exception as error:
                    logger.critical(error, extra=log_extra_data(request))
                    logger_mail.exception(error)
                    raise OkupyError("Can't contact LDAP server")
        else:
            gentoo_account_settings = GentooAccountSettingsForm()

        return render(request, 'settings-gentoo.html', {
            'gentoo_account_settings': gentoo_account_settings,
            'user_info': user_info,
        })