# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - create account action
        modified version for Cr@ns callback only (by creer_compte_wiki.py)
        

    @copyright: 2007 MoinMoin:JohannesBerg
    @license: GNU GPL, see COPYING for details.
"""

from MoinMoin import user, wikiutil
from MoinMoin.Page import Page
from MoinMoin.widget import html
from MoinMoin.auth import MoinAuth

def do_register(request):
    _ = request.getText
    form = request.form
    
    if request.method != 'POST':
        return 'missing data'

    # TODO : find a cleaner way to get this data
    authorized_ips = [
        '2a01:240:fe3d:4:224:8cff:fe44:3b70', #vo.v6
        '2a01:240:fe3d:4:219:bbff:fe3c:4f76', #zamok.v6
        '2a01:240:fe3d:4:0:6cff:fe69:6921', #o2.v6
    ]

    if request.remote_addr not in authorized_ips:
        return 'invalid ip %s' % request.remote_addr

    theuser = user.User(request, auth_method="new-user")
    try:
        theuser.name = form['name']
    except KeyError:
        return 'missing name'

    if not user.isValidName(request, theuser.name):
        return 'invalid name'

    if user.getUserId(request, theuser.name):
        return 'nonunique name'

    password = form.get('password', '')
    # Encode password
    if password and not password.startswith('{SHA}'):
        try:
            theuser.enc_password = user.encodePassword(password)
        except UnicodeError, err:
            # Should never happen
            return "invalid password %s" % str(err)

    # try to get the email, for new users it is required
    email = wikiutil.clean_input(form.get('email', ''))
    theuser.email = email.strip()
    if not theuser.email and 'email' not in request.cfg.user_form_remove:
        return 'invalid email'
              
    # Email should be unique - see also MoinMoin/script/accounts/moin_usercheck.py
    if theuser.email and request.cfg.user_email_unique:
        if user.get_by_email_address(request, theuser.email):
            return 'nonunique email'

    # save data
    try:
        theuser.save()
    except Exception as err:
        return 'error %s' % repr(err)

    return 'created'

def execute(pagename, request):
    request.write(do_register(request))
