Exemplo n.º 1
0
def ulogin():
    if env.user.id:
        raise AlreadyAuthorized

    sess = Session()

    if env.request.method == "POST":
        url = "http://ulogin.ru/token.php?token=%s&host=%s" % (env.request.args("token"), settings.domain)
        try:
            resp = urllib2.urlopen(url)
            data = dict.fromkeys(ULOGIN_FIELDS)
            data.update(json.loads(resp.read()))
            resp.close()
        except urllib2.URLError:
            return render("/auth/login.html", fields=ULOGIN_FIELDS, errors=["ulogin-fail"])

        try:
            env.user.authenticate_ulogin(data["network"], data["uid"])
            if env.user.id:
                return Response(redirect=referer())
        except NotAuthorized:
            pass

        login = data["nickname"].strip(u" -+.")
        if login:
            login = re.sub(r"[\._\-\+]+", "-", login)

        info = {
            "login": login,
            "network": data["network"],
            "uid": data["uid"],
            "name": ("%s %s" % (data["first_name"], data["last_name"])).strip(),
            "email": data["email"],
            "avatar": data["photo_big"],
            "birthdate": data["bdate"],
            "gender": True if data["sex"] == "2" else False if data["sex"] == "1" else None,
            "location": "%s, %s" % (data["city"], data["country"])
            if data["city"] and data["country"]
            else data["city"] or data["country"],
            "_nickname": data["nickname"],
            "_name": ("%s %s" % (data["first_name"], data["last_name"])).strip(),
            "_profile": data["profile"],
        }

        sess["reg_info"] = info
        sess.save()

    else:
        info = sess["reg_info"]

        if not info or not "network" in info or not "uid" in info:
            return Response(redirect="%s://%s/register" % (env.request.protocol, settings.domain))

    info["birthdate"] = parse_date(info["birthdate"]) or datetime.now() - timedelta(days=365 * 16 + 4)

    return render("/auth/register_ulogin.html", info=info)
Exemplo n.º 2
0
def register_get():
    if env.user.id:
        raise AlreadyAuthorized

    sess = Session()
    info = sess["reg_info"] or {}

    try:
        del info["network"]
        del info["uid"]
    except (KeyError, TypeError):
        pass

    try:
        info["birthdate"] = parse_date(info["birthdate"]) or datetime.now() - timedelta(days=365 * 16 + 4)
    except (KeyError, TypeError):
        info["birthdate"] = None

    return render("/auth/register.html", fields=ULOGIN_FIELDS, info=info)
Exemplo n.º 3
0
def ulogin():
    if env.user.id:
        raise AlreadyAuthorized

    sess = Session()

    if env.request.method == 'POST':
        url = "http://ulogin.ru/token.php?token=%s&host=%s" % \
                (env.request.args('token'), settings.domain)
        try:
            resp = urllib2.urlopen(url)
            data = dict.fromkeys(ULOGIN_FIELDS)
            data.update(json.loads(resp.read()))
            resp.close()
        except urllib2.URLError:
            return render('/auth/login.html',
                          fields=ULOGIN_FIELDS,
                          errors=['ulogin-fail'])

        try:
            env.user.authenticate_ulogin(data['network'], data['uid'])
            if env.user.id:
                return Response(redirect=referer())
        except NotAuthorized:
            pass

        login = data['nickname'].strip(u' -+.')
        if login:
            login = re.sub(r'[\._\-\+]+', '-', login)

        info = {
            'login': login,
            'network': data['network'],
            'uid': data['uid'],
            'name': ('%s %s' % (data['first_name'], data['last_name'])).strip(),
            'email': data['email'],
            'avatar': data['photo_big'],
            'birthdate': data['bdate'],
            'gender': True if data['sex'] == '2' else False if data['sex'] == '1' else None,
            'location': "%s, %s" % (data['city'], data['country']) \
                        if data['city'] and data['country'] else \
                        data['city'] or data['country'],

            '_nickname': data['nickname'],
            '_name': ('%s %s' % (data['first_name'], data['last_name'])).strip(),
            '_profile': data['profile'],
        }

        sess['reg_info'] = info
        sess.save()

    else:
        info = sess['reg_info']

        if not info or not 'network' in info or not 'uid' in info:
            return Response(redirect='%s://%s/register' % \
                    (env.request.protocol, settings.domain))

    info['birthdate'] = parse_date(info['birthdate']) \
                        or datetime.now() - timedelta(days=365*16+4)

    return render('/auth/register_ulogin.html', info=info)
Exemplo n.º 4
0
def register():
    #raise Forbidden
    if env.user.id:
        raise AlreadyAuthorized

    sess = Session()
    info = sess['reg_info'] or {}

    print 'INFO', info

    if env.request.method == 'GET':
        try:
            del info['network']
            del info['uid']
        except (KeyError, TypeError):
            pass
        sess['reg_info'] = info
        sess.save()

        try:
            info['birthdate'] = parse_date(info['birthdate']) \
                                or datetime.now() - timedelta(days=365*16+4)
        except (KeyError, TypeError):
            info['birthdate'] = None

        return render('/auth/register.html', fields=ULOGIN_FIELDS, info=info)

    try:
        network = info['network'] if 'network' in info else None
        uid = info['uid'] if 'uid' in info else None
    except TypeError:
        network = None
        uid = None

    errors = []

    for p in [
            'login', 'name', 'email', 'birthdate', 'location', 'about',
            'homepage'
    ]:
        info[p] = env.request.args(p, '').decode('utf-8')

    info['gender'] = _gender(env.request.args('gender'))

    login = env.request.args('login', '').strip()
    if login and validate_nickname(login):
        try:
            u = User('login', login)
            if u.id:
                errors.append('login-in-use')
        except UserNotFound:
            pass
    elif login:
        errors.append('login-invalid')
    else:
        errors.append('login-empty')

    password = env.request.args('password')
    confirm = env.request.args('confirm')
    if not (network and uid):
        if not password:
            errors.append('password')
        elif password != confirm:
            errors.append('confirm')

    info['birthdate'] = parse_date(info['birthdate']) \
                            or datetime.now() - timedelta(days=365*16+4)

    if not network and not errors:
        try:
            text = env.request.args('recaptcha_response_field')
            challenge = env.request.args('recaptcha_challenge_field')

            resp = captcha.submit(challenge, text,
                                  settings.recaptcha_private_key,
                                  env.request.remote_host)

            if not resp.is_valid:
                errors.append('captcha')

        except urllib2.URLError:
            errors.append('recaptcha-fail')
        except AddressNotFound:
            return Response(redirect='%s://%s/remember?fail=1' % \
                        (env.request.protocol, settings.domain))

    if errors:
        if network and uid:
            tmpl = '/auth/register_ulogin.html'
        else:
            tmpl = '/auth/register.html'

        return render(tmpl, fields=ULOGIN_FIELDS, info=info, errors=errors)

    users.register(login)

    for p in [
            'name', 'email', 'birthdate', 'gender', 'location', 'about',
            'homepage'
    ]:
        env.user.set_info(p, info[p])

    if password:
        env.user.set_password(password)

    if network and uid:
        _nickname = info['_nickname'] if '_nickname' in info else None
        _name = info['_name'] if '_name' in info else None
        _profile = info['_profile'] if '_profile' in info else None
        try:
            env.user.bind_ulogin(network, uid, _nickname, _name, _profile)
        except UserExists:
            raise Forbidden

    if env.request.args('avatar'):
        ext = env.request.args('avatar', '').split('.').pop().lower()
        if ext not in ['jpg', 'gif', 'png']:
            errors.append('filetype')
        else:
            filename = ('%s.%s' % (env.user.login, ext)).lower()

            make_avatar(env.request.files('avatar'), filename)

            env.user.set_info('avatar',
                              '%s?r=%d' % (filename, randint(1000, 9999)))

    elif 'avatar' in info and info['avatar']:
        filename = ('%s.%s' % (env.user.login, 'jpg')).lower()

        make_avatar(info['avatar'], filename)

        env.user.set_info('avatar',
                          '%s?r=%d' % (filename, randint(1000, 9999)))

    env.user.save()

    env.user.authenticate()

    return Response(redirect=get_referer())
Exemplo n.º 5
0
def ulogin():
    if env.user.id:
        raise AlreadyAuthorized

    sess = Session()

    if env.request.method == 'POST':
        url = "http://ulogin.ru/token.php?token=%s&host=%s" % \
                (env.request.args('token'), settings.domain)
        try:
            resp = urllib2.urlopen(url)
            data = dict.fromkeys(ULOGIN_FIELDS)
            data.update(json.loads(resp.read()))
            resp.close()
        except urllib2.URLError:
            return render('/auth/login.html', fields=ULOGIN_FIELDS,
                          errors=['ulogin-fail'])

        try:
            env.user.authenticate_ulogin(data['network'], data['uid'])
            if env.user.id:
                return Response(redirect=get_referer())
        except NotAuthorized:
            pass

        login = data['nickname'].strip(u' -+.')
        if login:
            login = re.sub(r'[\._\-\+]+', '-', login)

        info = {
            'login': login,
            'network': data['network'],
            'uid': data['uid'],
            'name': ('%s %s' % (data['first_name'], data['last_name'])).strip(),
            'email': data['email'],
            'avatar': data['photo_big'],
            'birthdate': data['bdate'],
            'gender': True if data['sex'] == '2' else False if data['sex'] == '1' else None,
            'location': "%s, %s" % (data['city'], data['country']) \
                        if data['city'] and data['country'] else \
                        data['city'] or data['country'],

            '_nickname': data['nickname'],
            '_name': ('%s %s' % (data['first_name'], data['last_name'])).strip(),
            '_profile': data['profile'],
        }

        sess['reg_info'] = info
        sess.save()

    else:
        info = sess['reg_info']

        if not info or not 'network' in info or not 'uid' in info:
            return Response(redirect='%s://%s/register' % \
                    (env.request.protocol, settings.domain))

    info['birthdate'] = parse_date(info['birthdate']) \
                        or datetime.now() - timedelta(days=365*16+4)

    return render('/auth/register_ulogin.html', info=info)
Exemplo n.º 6
0
def register():
    #raise Forbidden
    if env.user.id:
        raise AlreadyAuthorized

    sess = Session()
    info = sess['reg_info'] or {}

    print 'INFO', info

    if env.request.method == 'GET':
        try:
            del info['network']
            del info['uid']
        except (KeyError, TypeError):
            pass
        sess['reg_info'] = info
        sess.save()

        try:
            info['birthdate'] = parse_date(info['birthdate']) \
                                or datetime.now() - timedelta(days=365*16+4)
        except (KeyError, TypeError):
            info['birthdate'] = None

        return render('/auth/register.html', fields=ULOGIN_FIELDS, info=info)

    try:
        network = info['network'] if 'network' in info else None
        uid = info['uid'] if 'uid' in info else None
    except TypeError:
        network = None
        uid = None

    errors = []

    for p in ['login', 'name', 'email', 'birthdate', 'location', 'about', 'homepage']:
        info[p] = env.request.args(p, '').decode('utf-8')

    info['gender'] = _gender(env.request.args('gender'))

    login = env.request.args('login', '').strip()
    if login and validate_nickname(login):
        try:
            u = User('login', login)
            if u.id:
                errors.append('login-in-use')
        except UserNotFound:
            pass
    elif login:
        errors.append('login-invalid')
    else:
        errors.append('login-empty')

    password = env.request.args('password')
    confirm = env.request.args('confirm')
    if not (network and uid):
        if not password:
            errors.append('password')
        elif password != confirm:
            errors.append('confirm')

    info['birthdate'] = parse_date(info['birthdate']) \
                            or datetime.now() - timedelta(days=365*16+4)

    if not network and not errors:
        try:
            text = env.request.args('recaptcha_response_field')
            challenge = env.request.args('recaptcha_challenge_field')

            resp = captcha.submit(challenge, text,
                                  settings.recaptcha_private_key,
                                  env.request.remote_host)

            if not resp.is_valid:
                errors.append('captcha')

        except urllib2.URLError, e:
            log.error('recaptcha fail: %s' % e)
            #errors.append('recaptcha-fail')
        except AddressNotFound:
            return Response(redirect='%s://%s/remember?fail=1' % \
                        (env.request.protocol, settings.domain))
Exemplo n.º 7
0
def register_post():
    if env.user.id:
        raise AlreadyAuthorized

    sess = Session()
    info = sess["reg_info"] or {}

    try:
        del info["network"]
        del info["uid"]
    except (KeyError, TypeError):
        pass
    sess["reg_info"] = info
    sess.save()

    try:
        network = info["network"] if "network" in info else None
        uid = info["uid"] if "uid" in info else None
    except TypeError:
        network = None
        uid = None

    errors = []

    for p in ["login", "name", "email", "birthdate", "location", "about", "homepage"]:
        info[p] = env.request.args(p, "").decode("utf-8")

    info["gender"] = _gender(env.request.args("gender"))

    login = env.request.args("login", "").strip()
    if login and validate_nickname(login):
        try:
            u = User("login", login)
            if u.id:
                errors.append("login-in-use")
        except UserNotFound:
            pass
    elif login:
        errors.append("login-invalid")
    else:
        errors.append("login-empty")

    password = env.request.args("password")
    if not (network and uid):
        if not password:
            errors.append("password")

    info["birthdate"] = parse_date(info["birthdate"])

    if not network and not errors:
        try:
            resp = recaptcha2.verify(
                env.request.args("g-recaptcha-request", ""), settings.recaptcha_private_key, env.request.remote_host
            )

            if not resp.is_valid:
                errors.append("captcha")

        except urllib2.URLError:
            errors.append("recaptcha-fail")
        except AddressNotFound:
            return Response(redirect="%s://%s/remember?fail=1" % (env.request.protocol, settings.domain))

    if errors:
        if network and uid:
            tmpl = "/auth/register_ulogin.html"
        else:
            tmpl = "/auth/register.html"

        return Response(template=tmpl, fields=ULOGIN_FIELDS, info=info, errors=errors)

    users.register(login)

    for p in ["name", "email", "birthdate", "gender", "location", "about", "homepage"]:
        env.user.set_info(p, info[p])

    if password:
        env.user.set_password(password)

    if network and uid:
        _nickname = info["_nickname"] if "_nickname" in info else None
        _name = info["_name"] if "_name" in info else None
        _profile = info["_profile"] if "_profile" in info else None
        try:
            env.user.bind_ulogin(network, uid, _nickname, _name, _profile)
        except UserExists:
            raise Forbidden

    if env.request.args("avatar"):
        ext = env.request.args("avatar", "").split(".").pop().lower()
        if ext not in ["jpg", "gif", "png"]:
            errors.append("filetype")
        else:
            filename = ("%s.%s" % (env.user.login, ext)).lower()

            make_avatar(env.request.files("avatar"), filename)

            env.user.set_info("avatar", "%s?r=%d" % (filename, randint(1000, 9999)))

    elif "avatar" in info and info["avatar"]:
        filename = ("%s.%s" % (env.user.login, "jpg")).lower()

        make_avatar(info["avatar"], filename)

        env.user.set_info("avatar", "%s?r=%d" % (filename, randint(1000, 9999)))

    env.user.save()

    env.user.authenticate()

    return Response(redirect=get_referer())
Exemplo n.º 8
0
def register():
    #raise Forbidden
    if env.user.id:
        raise AlreadyAuthorized

    sess = Session()
    info = sess['reg_info'] or {}

    print 'INFO', info

    if env.request.method == 'GET':
        try:
            del info['network']
            del info['uid']
        except (KeyError, TypeError):
            pass
        sess['reg_info'] = info
        sess.save()

        try:
            info['birthdate'] = parse_date(info['birthdate']) \
                                or datetime.now() - timedelta(days=365*16+4)
        except (KeyError, TypeError):
            info['birthdate'] = None

        return render('/auth/register.html', fields=ULOGIN_FIELDS, info=info)

    try:
        network = info['network'] if 'network' in info else None
        uid = info['uid'] if 'uid' in info else None
    except TypeError:
        network = None
        uid = None

    errors = []

    for p in ['login', 'name', 'email', 'birthdate', 'location', 'about', 'homepage']:
        info[p] = env.request.args(p, '').decode('utf-8')

    info['gender'] = _gender(env.request.args('gender'))

    login = env.request.args('login', '').strip()
    if login and validate_nickname(login):
        try:
            u = User('login', login)
            if u.id:
                errors.append('login-in-use')
        except UserNotFound:
            pass
    elif login:
        errors.append('login-invalid')
    else:
        errors.append('login-empty')

    password = env.request.args('password')
    confirm = env.request.args('confirm')
    if not (network and uid):
        if not password:
            errors.append('password')
        elif password != confirm:
            errors.append('confirm')

    info['birthdate'] = parse_date(info['birthdate']) \
                            or datetime.now() - timedelta(days=365*16+4)

    if not network and not errors:
        try:
            text = env.request.args('recaptcha_response_field')
            challenge = env.request.args('recaptcha_challenge_field')

            resp = captcha.submit(challenge, text,
                                  settings.recaptcha_private_key,
                                  env.request.remote_host)

            if not resp.is_valid:
                errors.append('captcha')

        except urllib2.URLError:
            errors.append('recaptcha-fail')
        except AddressNotFound:
            return Response(redirect='%s://%s/remember?fail=1' % \
                        (env.request.protocol, settings.domain))

    if errors:
        if network and uid:
            tmpl = '/auth/register_ulogin.html'
        else:
            tmpl = '/auth/register.html'

        return render(tmpl, fields=ULOGIN_FIELDS, info=info, errors=errors)

    users.register(login)

    for p in ['name', 'email', 'birthdate', 'gender', 'location', 'about', 'homepage']:
        env.user.set_info(p, info[p])

    if password:
        env.user.set_password(password)

    if network and uid:
        _nickname = info['_nickname'] if '_nickname' in info else None
        _name = info['_name'] if '_name' in info else None
        _profile = info['_profile'] if '_profile' in info else None
        try:
            env.user.bind_ulogin(network, uid, _nickname, _name, _profile)
        except UserExists:
            raise Forbidden

    if env.request.args('avatar'):
        ext = env.request.args('avatar', '').split('.').pop().lower()
        if ext not in ['jpg', 'gif', 'png']:
            errors.append('filetype')
        else:
            filename = ('%s.%s' % (env.user.login, ext)).lower()

            make_avatar(env.request.files('avatar'), filename)

            env.user.set_info('avatar',
                        '%s?r=%d' % (filename, randint(1000, 9999)))

    elif 'avatar' in info and info['avatar']:
        filename = ('%s.%s' % (env.user.login, 'jpg')).lower()

        make_avatar(info['avatar'], filename)

        env.user.set_info('avatar', '%s?r=%d' % (filename, randint(1000, 9999)))

    env.user.save()

    env.user.authenticate()

    return Response(redirect=get_referer())