Example #1
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())
Example #2
0
        _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()
Example #3
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())
Example #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())
Example #5
0
def profile():
    errors = []

    if env.request.method == 'POST':
        if env.user.check_password_set():
            try:
                if not env.user.check_password(env.request.args(
                        'password', '')):
                    errors.append('password')
            except KeyError:
                errors.append('password')

        if env.request.args('remove-avatar'):
            old = env.user.get_info('avatar')
            if old:
                old = old.rsplit('?')[0]
                remove_avatar(old)
                env.user.set_info('avatar', None)
        else:
            if env.request.args('avatar'):
                if not errors:
                    avatar = env.request.args('avatar', '')
                    if isinstance(avatar, (list, tuple)):
                        avatar = avatar[0]
                    ext = avatar.split('.').pop().lower()
                    if ext not in ['jpeg', 'jpg', 'gif', 'png']:
                        errors.append('filetype')
                    else:
                        filename = ('%s.%s' % (env.user.login, ext)).lower()

                        old = env.user.get_info('avatar')
                        if old:
                            old = old.rsplit('?')[0]

                        avatar_file = env.request.files('avatar')
                        if isinstance(avatar_file, (list, tuple)):
                            avatar_file = avatar_file[0]
                        make_avatar(avatar_file,
                                    filename,
                                    remove=True,
                                    old=old)

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

        #try:
        #    bday = int(env.request.args('birthdate-day'))
        #    bmon = int(env.request.args('birthdate-month'))
        #    byear = int(env.request.args('birthdate-year'))
        #    env.user.set_info('birthdate', datetime(byear, bmon, bday))
        #except (KeyError, ValueError):
        #    pass

        #try:
        #    env.user.set_info('gender',
        #        {'1':True, '0':False, '':None}[env.request.args('gender')])
        #except KeyError:
            pass

        for name, field in _info_form.iteritems():
            v = env.request.args(name, '').decode('utf-8')
            if v is None:
                continue
            if 'type' in field:
                try:
                    v = field['type'](v)
                except:
                    errors.append(name)
            if 'check' in field and not field['check'](v):
                errors.append(name)
                continue
            env.user.set_info(name, v)

        for name, field in _profile_form.iteritems():
            v = env.request.args(name, '').decode('utf-8')
            if v is None:
                continue
            if 'type' in field:
                try:
                    if field['type'] in (int, long, float) and v == '':
                        continue
                    v = field['type'](v)
                except (TypeError, ValueError):
                    errors.append(name)
                    continue
            if 'check' in field and not field['check'](v):
                errors.append(name)
                continue
            env.user.set_profile(name, v)

        new_password = env.request.args('new-password')
        confirm = env.request.args('confirm')
        if new_password:
            if new_password != confirm:
                errors.append('confirm')
            else:
                env.user.set_password(new_password)

        if not errors:
            blogcss = env.request.args('www.blogcss', '').strip()
            env.user.set_profile('www.usercss', blogcss)
            #if blogcss:
            #    try:
            #        fd = open(os.path.join(settings.blogcss_path,
            #                  '%s.css' % env.user.login), 'w')
            #        fd.write(blogcss)
            #        fd.close()
            #        env.user.set_profile('www.blogcss',
            #                             '%s.css?r=%d' % \
            #                             (env.user.login, randint(1000, 9999)))
            #    except IOError:
            #        pass
            #else:
            #    try:
            #        os.unlink(os.path.join(settings.blogcss_path,
            #                  '%s.css' % env.user.login))
            #    except OSError:
            #        pass
            #    env.user.set_profile('www.blogcss', None)

            usercss = env.request.args('www.usercss', '').strip()
            env.user.set_profile('www.usercss', usercss)
            #if usercss:
            #    try:
            #        fd = open(os.path.join(settings.usercss_path,
            #                  '%s.css' % env.user.login), 'w')
            #        fd.write(usercss)
            #        fd.close()
            #        env.user.set_profile('www.usercss',
            #                             '%s.css?r=%d' % \
            #                             (env.user.login, randint(1000, 9999)))
            #    except IOError:
            #        pass
            #else:
            #    try:
            #        os.unlink(os.path.join(settings.blogcss_path,
            #                  '%s.css' % env.user.login))
            #    except OSError:
            #        pass
            #    env.user.set_profile('www.usercss', None)

        if not errors:
            new_login = env.request.args('login', '').strip()
            if env.user.login != new_login:
                sess = Session()
                add_session(env.user, sess.sessid)
                try:
                    users.rename(new_login)
                except (UserLoginError, UserExists):
                    errors.append('invalid-login')
                except RenameError:
                    #errors.append('rename-timeout')
                    pass

        if not errors:
            env.user.save()
            return Response(redirect='%s://%s.%s/profile?saved=1' % \
                       (env.request.protocol, env.user.login, settings.domain))

    saved = bool(env.request.args('saved'))

    info = env.user.get_info()

    profile = {}
    for k in _profile_form:
        val = env.user.get_profile(k)
        if k.find('.') > -1:
            t, k = k.split('.', 1)
            #t = 'profile_%s' % t
            if not t in profile:
                profile[t] = {}
            profile[t][k] = val
        else:
            profile[k] = val
    #_profile = { k:env.user.get_profile(k) for k in keys }

    #if env.request.method == 'GET':
    #if profile['www']['blogcss']:
    #    try:
    #        with open(os.path.join(settings.blogcss_path,
    #                               '%s.css' % env.user.login)) as fd:
    #            profile['www']['blogcss'] = fd.read()
    #    except IOError:
    #        profile['www']['blogcss'] = ''
    #
    #if profile['www']['usercss']:
    #    try:
    #        with open(os.path.join(settings.usercss_path,
    #                               '%s.css' % env.user.login)) as fd:
    #            profile['www']['usercss'] = fd.read()
    #    except IOError:
    #        profile['www']['usercss'] = ''

    return render('/profile/index.html',
                  saved=saved,
                  errors=errors,
                  info=info,
                  profile=profile,
                  tzlist=tzlist())
Example #6
0
def profile():
    errors = []

    if env.request.method == 'POST':
        if env.user.check_password_set():
            try:
                if not env.user.check_password(env.request.args('password', '')):
                    errors.append('password')
            except KeyError:
                errors.append('password')

        if env.request.args('remove-avatar'):
            old = env.user.get_info('avatar')
            if old:
                old = old.rsplit('?')[0]
                remove_avatar(old)
                env.user.set_info('avatar', None)
        else:
            if env.request.args('avatar'):
                if not errors:
                    avatar = env.request.args('avatar', '')
                    if isinstance(avatar, (list, tuple)):
                        avatar = avatar[0]
                    ext = avatar.split('.').pop().lower()
                    if ext not in ['jpeg', 'jpg', 'gif', 'png']:
                        errors.append('filetype')
                    else:
                        filename = ('%s.%s' % (env.user.login, ext)).lower()

                        old = env.user.get_info('avatar')
                        if old:
                            old = old.rsplit('?')[0]

                        avatar_file = env.request.files('avatar')
                        if isinstance(avatar_file, (list, tuple)):
                            avatar_file = avatar_file[0]
                        make_avatar(avatar_file, filename, remove=True, old=old)

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

        #try:
        #    bday = int(env.request.args('birthdate-day'))
        #    bmon = int(env.request.args('birthdate-month'))
        #    byear = int(env.request.args('birthdate-year'))
        #    env.user.set_info('birthdate', datetime(byear, bmon, bday))
        #except (KeyError, ValueError):
        #    pass

        #try:
        #    env.user.set_info('gender',
        #        {'1':True, '0':False, '':None}[env.request.args('gender')])
        #except KeyError:
            pass

        for name, field in _info_form.iteritems():
            v = env.request.args(name, '').decode('utf-8')
            if v is None:
                continue
            if 'type' in field:
                try:
                    v = field['type'](v)
                except:
                    errors.append(name)
            if 'check' in field and not field['check'](v):
                errors.append(name)
                continue
            env.user.set_info(name, v)

        for name, field in _profile_form.iteritems():
            v = env.request.args(name, '').decode('utf-8')
            if v is None:
                continue
            if 'type' in field:
                try:
                    if field['type'] in (int, long, float) and v == '':
                        continue
                    v = field['type'](v)
                except (TypeError, ValueError):
                    errors.append(name)
                    continue
            if 'check' in field and not field['check'](v):
                errors.append(name)
                continue
            env.user.set_profile(name, v)

        new_password = env.request.args('new-password')
        confirm = env.request.args('confirm')
        if new_password:
            if new_password != confirm:
                errors.append('confirm')
            else:
                env.user.set_password(new_password)

        if not errors:
            blogcss = env.request.args('www.blogcss', '').strip()
            env.user.set_profile('www.usercss', blogcss)
            #if blogcss:
            #    try:
            #        fd = open(os.path.join(settings.blogcss_path,
            #                  '%s.css' % env.user.login), 'w')
            #        fd.write(blogcss)
            #        fd.close()
            #        env.user.set_profile('www.blogcss',
            #                             '%s.css?r=%d' % \
            #                             (env.user.login, randint(1000, 9999)))
            #    except IOError:
            #        pass
            #else:
            #    try:
            #        os.unlink(os.path.join(settings.blogcss_path,
            #                  '%s.css' % env.user.login))
            #    except OSError:
            #        pass
            #    env.user.set_profile('www.blogcss', None)

            usercss = env.request.args('www.usercss', '').strip()
            env.user.set_profile('www.usercss', usercss)
            #if usercss:
            #    try:
            #        fd = open(os.path.join(settings.usercss_path,
            #                  '%s.css' % env.user.login), 'w')
            #        fd.write(usercss)
            #        fd.close()
            #        env.user.set_profile('www.usercss',
            #                             '%s.css?r=%d' % \
            #                             (env.user.login, randint(1000, 9999)))
            #    except IOError:
            #        pass
            #else:
            #    try:
            #        os.unlink(os.path.join(settings.blogcss_path,
            #                  '%s.css' % env.user.login))
            #    except OSError:
            #        pass
            #    env.user.set_profile('www.usercss', None)

        if not errors:
            new_login = env.request.args('login', '').strip()
            if env.user.login != new_login:
                sess = Session()
                add_session(env.user, sess.sessid)
                try:
                    users.rename(new_login)
                except UserLoginError:
                    errors.append('invalid-login')
                except RenameError:
                    #errors.append('rename-timeout')
                    pass

        if not errors:
            env.user.save()
            return Response(redirect='%s://%s.%s/profile?saved=1' % \
                       (env.request.protocol, env.user.login, settings.domain))

    saved = bool(env.request.args('saved'))

    info = env.user.get_info()

    profile = {}
    for k in _profile_form:
        val = env.user.get_profile(k)
        if k.find('.') > -1:
            t, k = k.split('.', 1)
            #t = 'profile_%s' % t
            if not t in profile:
                profile[t] = {}
            profile[t][k] = val
        else:
            profile[k] = val
    #_profile = { k:env.user.get_profile(k) for k in keys }

    #if env.request.method == 'GET':
        #if profile['www']['blogcss']:
        #    try:
        #        with open(os.path.join(settings.blogcss_path,
        #                               '%s.css' % env.user.login)) as fd:
        #            profile['www']['blogcss'] = fd.read()
        #    except IOError:
        #        profile['www']['blogcss'] = ''
        #
        #if profile['www']['usercss']:
        #    try:
        #        with open(os.path.join(settings.usercss_path,
        #                               '%s.css' % env.user.login)) as fd:
        #            profile['www']['usercss'] = fd.read()
        #    except IOError:
        #        profile['www']['usercss'] = ''

    return render('/profile/index.html', saved=saved,
                  errors=errors, info=info, profile=profile, tzlist=tzlist())