'''
SAGATOR's web service registration

(c) 2005-2016 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.
    
'''

__pychecker__ = 'unusednames=_ \
                 maxreturns=20 maxlines=300 \
                 no-local no-argsused no-stringiter no-abstract no-isliteral \
                 no-stdlib no-callinit'

import sys, os, crypt, html
from avlib import *
from avlib import _
from index import WEBQ,DB,_header,LOCALE_DIR,SMTP_SERVER

__access__=True

AUTH_REQ=_('''\
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
''')

REG_FORM=_('''\
<p>You can make a new account, if you have at least one quarantined email.
<form action="reg" method="GET">
Your email address: <input type="text" name="user" value="">
<input type="submit" value="Send request" class="submit">
</form></p>
''')

REG_MAIL=_('''\
From: SAGATOR
To: %s
Subject: SAGATOR's web access password

You (%s) are requested your password to access SAGATOR's web services.

Your new passowrd is: "%s"

Regards
		SAGATOR's mail system
''')

def index(req,user=None):
    ''' Registration form and it's handler. '''
    # query language
    try:
      LANG=req.headers_in['Accept-Language'].split(',')[0]
    except:
      LANG="en"
    _.set_lang(LANG,LOCALE_DIR)
    pg=html.page(_header(req,'Anonymous'))
    if user:
      if not 'reg' in WEBQ.PERMS:
        return html.page(_header(req,user)+_(AUTH_REQ))
    else:
      pg.write(_(AUTH_REQ))
      if 'reg' in WEBQ.PERMS:
        pg.write(_(REG_FORM))
      return pg.getvalue()
    # check, if there are quarantined meesages for this user
    usermail=re.compile(WEBQ.USERCONV[0]).sub(WEBQ.USERCONV[1],user)
    q=DB.query("SELECT recipients FROM sagator WHERE recipients LIKE '%%%s%%'" % DB.quote(usermail))
    reg_user=re.compile('^(.+,|)%s(,.+|)$' % usermail,re.I)
    count=0
    for (recipients,) in q:
      if reg_user.search(recipients):
        count+=1
    if count>0:
      # check for last password generation
      # generate new password
      newpass=randomchars()
      cryptpass=crypt.crypt(newpass,'$1$'+randomchars(8))
      try:
        # email this passowrd
        m=smtpc()
        m.SMTP_SERVER=SMTP_SERVER
        m.sendmail('root@localhost',[usermail],_(REG_MAIL) % (user,req.get_remote_host(2),newpass))
        pg.write(_("You have %d quarantined messages.<br/>\nYour password has been sent to your email (%s).") % (count,user))
        # store new password in database
        DB.execute("DELETE FROM webaccess WHERE email='%s'" % DB.quote(user))
        DB.execute("INSERT INTO webaccess VALUES ('%s','%s','',CURRENT_TIMESTAMP,'%s',50)" \
                   % (DB.quote(user),DB.quote(cryptpass),DB.quote(LANG)))
      except SmtpcError as err:
        pg.write(_("Error sending message to %s: %s") % (user,err[1]))
    else:
      pg.write(_("You don't have quarantined messages. You can't log in."))
    return pg.getvalue()
