Пример #1
0
def run(environ):
    status = '200 OK'
    headers = []
    responseBody = html.getHead(title='Se connecter')
    path = environ['module_path']
    if path == '':
        responseBody += u"""
<form action="submit.htm" method="POST">
<table>
<tr>
<td><label for="name">Nom :</label></td>
<td><input type="text" id="name" name="name" /></td>
</tr>
<tr>
<td><label for="passwd">Mot de passe :</label></td>
<td>
<input type="password" id="passwd" name="passwd" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Se connecter" />
</td>
</tr>
</table>
</form>"""
    elif path == 'submit.htm':
        data = parsers.http_query(environ, 'POST')
        assert all((key in data) for key in ('name', 'passwd'))
        currentUser = user.User(data['name'],
                                hashlib.md5(data['passwd']).hexdigest())
        def getCookie(name, value):
            return cookie.Cookie(name=name,
                                 value=value,
                                 expires=2592000,
                                 path='/')
        nameCookie = getCookie('name', currentUser.name)
        passwdCookie = getCookie('passwdhash', currentUser.passwdhash)
        headers.append(('Set-Cookie', str(nameCookie)))
        headers.append(('Set-Cookie', str(passwdCookie)))
        headers.append(('Location', '/'))
        status = '302 Found'
        responseBody += 'Bienvenue %s !' % str(nameCookie.value)
    else:
        raise exceptions.Error404()
    responseBody += html.getFoot()
    return status, headers, responseBody
Пример #2
0
def run(environ):
    status = '200 OK'
    headers = []
    responseBody = html.getHead(title=u'Créer un compte')
    path = environ['module_path']
    if path == '':
        responseBody += u"""
<form action="submit.htm" method="POST">
<table>
<tr>
<td><label for="name">Nom :</label></td>
<td><input type="text" id="name" name="name" /></td>
</tr>
<tr>
<td><label for="passwd1">Mot de passe :</label></td>
<td>
<input type="password" id="passwd1" name="passwd1" />
</td>
</tr>
<tr>
<td><label for="passwd2">
Mot de passe (confirmation) :
</label></td>
<td>
<input type="password" id="passwd2" name="passwd2" />
</td>
</tr>
<tr>
<td><label for="email">Adresse de courriel :</label></td>
<td><input type="text" id="email" name="email" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="S'inscrire" />
</td>
</tr>
</table>
</form>"""
    elif path == 'submit.htm':
        data = parsers.http_query(environ, 'POST')
        assert all((key in data) for key in
                   ('name', 'passwd1', 'passwd2', 'email'))
        cursor = db.conn.cursor()
        cursor.execute("SELECT name FROM users WHERE name=?",
                       (data['name'],))
        row = cursor.fetchone()
        anyError = False
        if row is not None:
            responseBody += u"""<p>Il y a déjà un utilisateur ayant ce nom.
Veuillez en choisir un autre.</p>"""
            anyError = True
        if data['passwd1'] != data['passwd2']:
            responseBody += u"""<p>Le mot de passe et sa confirmation ne sont
pas identiques.</p>"""
            anyError = True
        if not testName.match(data['name']):
            responseBody += u"""<p>Le nom d'utilisateur est incorrect.
Taille : de 2 à 36, et ne peux contenir que
des caractères alphanumériques, des
underscores et des tirets.</p>"""
            anyError = True
        if '@' not in data['email']:
            responseBody += u"""<p>L'adresse de courriel est invalide.</p>"""
            anyError = True

        if not anyError:
            ##DB#users
            cursor.execute("""INSERT INTO users VALUES ('',?,?,?)""", (
                            data['name'],
                            hashlib.md5(data['passwd1']).hexdigest(),
                            data['email']))
            db.conn.commit()
            responseBody += u"""Votre compte a été créé."""
    else:
        raise exceptions.Error404()

    responseBody += html.getFoot()
    return status, headers, responseBody
Пример #3
0
def run(environ):
    headers = []
    status = '200 OK'
    if environ['module_path'] == '':
        responseBody = html.getHead(title='Accueil')


        cursor = db.conn.cursor()
        cursor.execute("""SELECT `tiny`, `full` FROM `tiny2full`
                          WHERE `u_id`=?
                          ORDER BY `submit_time` DESC
                          LIMIT 0,20""", (user.currentUser.id,))
        older = time.time() - 60*60
        string = ''
        for tiny, full in cursor:
            string += '<li><a href="/%s">%s</a> ' % (tiny, full)
            string += '<a href="/stats/%s">Stats</a></li>' % tiny
        responseBody += rootTemplate % {'last_tiny': string}


        cursor = db.conn.cursor()
        cursor.execute('SELECT `full` FROM `tiny2full`')


        responseBody += html.getFoot()
        return status, headers, responseBody
    elif environ['module_path'] == 'submiturl.htm':
        errormsg = ''

        data = parsers.http_query(environ, 'POST')
        assert all((key in data) for key in ('longurl','size'))

        longurl, size = data['longurl'], data['size']

        if matchUrl1.match(longurl):
            longurl = 'http://' + longurl
        elif not matchUrl2.match(longurl):
            errormsg += u'<p>Votre URL longue ne correspond pas à notre ' + \
                        u'expression régulière.</p>'
        try:
            size = int(size)
            assert 2 <= size <= 7
        except:
            errormsg += u'<p>La taille ne peut être qu\'un entier ' + \
                        u'positif compris entre 2 et 7 (inclus)</pre>'
        if errormsg != '':
            responseBody = html.getHead(title='Nouvelle URL - Erreur')
            responseBody += errormsg
            responseBody += html.getFoot()
            return status, headers, responseBody

        hash_ = hashlib.md5(longurl)
        tiny = ''
        timeout = time.time() + 0.5
        cursor = db.conn.cursor()
        while tiny == '' and time.time() < timeout:
            digest = hash_.hexdigest()
            while len(digest) >= size:
                cursor.execute("""SELECT `full`, `expiry` FROM `tiny2full`
                                  WHERE `tiny`=?""", (digest[0:size],))
                result = cursor.fetchone()
                if result is None or (result[1]!=0 and result[1]<time.time()):
                    tiny=digest[0:size]
                    if result is not None:
                        cursor.execute("""DELETE FROM `tiny2full`
                                          WHERE `tiny`=?""", (tiny,))
                    cursor.execute('INSERT INTO `tiny2full` VALUES(?,?,?,?,?)',
                                   (tiny, user.currentUser.id, longurl,
                                    getExpiry(size), time.time()))
                    db.conn.commit()
                    break
                if result[0] == longurl:
                    tiny = digest[0:size]
                    break
                digest = digest[1:] # Strip the first character
            hash_.update(chr(random.randrange(255)))

        assert tiny != '', ('Impossible de calculer une URL raccourcie,'
                            'veuillez réessayer (un facteur aléatoire '
                            'intervient dans le calcul)')

        responseBody = u'<a href="/">Cliquez sur ce lien si vous n\'êtes ' + \
                       u'pas redirigé(e)</a>'
        headers.append(('Location', '/'))
        status = '302 Found'
    else:
        cursor = db.conn.cursor()
        cursor.execute('SELECT `full` FROM `tiny2full` WHERE `tiny`=?',
                       (environ['module_path'],))
        result = cursor.fetchone()
        if result is None:
            raise exceptions.Error404()

        cursor = db.conn.cursor()
        cursor.execute("""INSERT INTO `clicks` VALUES(?,?,?)""",
                       (environ['module_path'], user.currentUser.id, int(time.time())))
        db.conn.commit()
        cursor.execute('SELECT * FROM `clicks`')

        responseBody = (u'<a href="%s">Cliquez sur ce lien si vous n\'êtes '
                       u'pas redirigé(e)</a>') % result[0]
        headers.append(('Location', str(result[0])))
        status = '302 Found'


    return status, headers, responseBody