"""$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/ui/user/__init__.py $
$Id: __init__.py 23233 2003-11-24 21:08:27Z dbinger $
"""
from quixote import get_request, get_user
from quixote.errors import AccessError
from quixote.html import href
from dulcinea import local
from dulcinea.errors import NotLoggedInError
from dulcinea.ui.user.tiny_login import USERID_COOKIE_NAME
from dulcinea.ui.user.util import about_ssl, enabling_cookies, UserSearchForm, \
     ChangePasswordForm, ContactRegisterForm, profile, get_user_or_act_as
from dulcinea.ui.user.login import LoginForm, NewPasswordForm, \
     delete_user_session, act_as_another_user

_q_exports = ['login', 'logout', 'register', 'edit', 'change_password',
              'profile', 'about_ssl', 'enabling_cookies', 'newpass',
              'insecure_login', 'act_as', 'search']

def get_crumb():
    user = get_user_or_act_as(allow_none=True)
    if user:
        return 'User %s' % user
    return 'Sign in'

def login(request):
    # Only encourage users who we think will log in as admin to use SSL
    user = local.get_user_database().get_user(
        get_request().cookies.get(USERID_COOKIE_NAME))
    form = LoginForm(request, secure=user and user.is_admin())
    return form.handle(request)

def logout(request):
    return delete_user_session(request)

def newpass(request):
    form = NewPasswordForm()
    return form.handle(request)

def register(request, success_links=None):
    form = ContactRegisterForm(request, success_links=success_links)
    return form.handle(request)

edit = register

def insecure_login(request):
    form = LoginForm(request, secure=0)
    return form.handle(request)

def change_password(request):
    if request.session.user is None:
        raise NotLoggedInError(
            "You must be signed in to change your password.")
    form = ChangePasswordForm(request.session.user)
    return form.handle(request)

def search(request):
    user = get_user_or_act_as()
    if not user.is_admin():
        raise AccessError('Only admin users can search for users.')
    return UserSearchForm(
        request, local.get_user_database().get_users(sort=1)).handle(request)

def act_as(request):
    return act_as_another_user(request)

_q_index = login


