예제 #1
0
파일: users.py 프로젝트: radjah/point-xmpp
def reg_invite_set_login(value):
    sess = env.user.session()
    if not sess.data():
        env.user.session(reg_invite_set_login, key=value)
        return 'Please enter your nickname'

    if not sess['key']:
        env.user.session_destroy()
        return 'Fail'


    env.user.session_destroy()

    if value.startswith('@'):
        value = value[1:]
    if not validate_nickname(value):
        return xmpp_template('reg_invalid')

    try:
        users.register(login=value, accounts=[('xmpp', env.jid)])
        redis = RedisPool(settings.storage_socket)
        redis.delete('invite:%s' % sess['key'])
        return xmpp_template('reg_ok', login=value)
    except UserExists:
        return 'User @%s already exists.' % value

    except UserError, e:
        log.error('%s: %s' % (e.__class__.__name__, e.message))
        return e.message
예제 #2
0
def reg_invite_set_login(value):
    sess = env.user.session()
    if not sess.data():
        env.user.session(reg_invite_set_login, key=value)
        return 'Please enter your nickname'

    if not sess['key']:
        env.user.session_destroy()
        return 'Fail'

    env.user.session_destroy()

    if value.startswith('@'):
        value = value[1:]
    if not validate_nickname(value):
        return xmpp_template('reg_invalid')

    try:
        users.register(login=value, accounts=[('xmpp', env.jid)])
        redis = RedisPool(settings.storage_socket)
        redis.delete('invite:%s' % sess['key'])
        return xmpp_template('reg_ok', login=value)
    except UserExists:
        return 'User @%s already exists.' % value

    except UserError, e:
        log.error('%s: %s' % (e.__class__.__name__, e.message))
        return e.message
예제 #3
0
파일: users.py 프로젝트: radjah/point-xmpp
def register(login, password=None):
    """Register a new user
    """

    return 'Registration is temporarily available on the web site only. Please follow: https://point.im.register .'

    if env.user.id:
        return xmpp_template('reg_already', login=env.user.login)

    if not validate_nickname(login):
        return xmpp_template('reg_invalid')

    sess = env.user.session()
    if not sess.data():
        return reg_steps(login, password)
예제 #4
0
def register(login, password=None):
    """Register a new user
    """

    return 'Registration is temporarily available on the web site only. Please follow: https://point.im.register .'

    if env.user.id:
        return xmpp_template('reg_already', login=env.user.login)

    if not validate_nickname(login):
        return xmpp_template('reg_invalid')

    sess = env.user.session()
    if not sess.data():
        return reg_steps(login, password)
예제 #5
0
    def rename(self, login):
        if not self.id:
            raise NotAuthorized
        if cache_get('renamed:%s' % self.id):
            raise RenameError

        if not validate_nickname(login):
            raise UserLoginError

        old_login = self.login
        self.login = login

        try:
            db.perform("UPDATE users.logins SET login=%s WHERE id=%s;",
                       [login, self.id])
        except IntegrityError:
            raise UserExists

        cache_store('renamed:%s' % self.id, 1, settings.user_rename_timeout)
        cache_del('id_login:%s' % old_login.lower())

        for t in ACCOUNT_TYPES:
            for addr in self.get_accounts(t):
                cache_del("addr_id_login:%s" % addr)
예제 #6
0
    def rename(self, login):
        if not self.id:
            raise NotAuthorized
        if cache_get('renamed:%s' % self.id):
            raise RenameError

        if not validate_nickname(login):
            raise UserLoginError

        old_login = self.login
        self.login = login

        try:
            db.perform("UPDATE users.logins SET login=%s WHERE id=%s;",
                       [login, self.id])
        except IntegrityError:
            raise UserExists

        cache_store('renamed:%s' % self.id, 1, settings.user_rename_timeout)
        cache_del('id_login:%s' % old_login.lower())

        for t in ACCOUNT_TYPES:
            for addr in self.get_accounts(t):
                cache_del("addr_id_login:%s" % addr)
예제 #7
0
파일: auth.py 프로젝트: Raegdan/www-new
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())
예제 #8
0
파일: auth.py 프로젝트: ilyaguy/point-www
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))
예제 #9
0
파일: auth.py 프로젝트: artss/point-www-new
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())
예제 #10
0
    def save(self):
        if not self.login:
            raise UserError("Cannot save anonymous user")

        is_new = False

        # create user
        if not self.id:
            if not self.login or not validate_nickname(self.login):
                raise UserError('Invalid Login: "******"' % self.login)
            self.id = db.fetchone(
                "INSERT INTO users.logins (login, type) "
                "VALUES (%s, %s) RETURNING id;", [self.login, self.type])[0]
            db.perform("INSERT INTO users.info (id, name) VALUES (%s, %s);",
                       [self.id, self.login])
            db.perform(
                "INSERT INTO users.profile (id, private, lang) "
                "VALUES (%s, false, 'en');", [self.id])

            self.accounts_add = self.accounts
            is_new = True

        if not is_new:
            try:
                if self._private == True:
                    self._set_private()
                elif self._private == False:
                    self._set_public()
            except AttributeError:
                pass

        # save accounts
        for acc in self.accounts_add:
            try:
                if len(acc) == 3:
                    db.perform(
                        "INSERT INTO users.accounts_unconfirmed "
                        "(user_id, type, address, code) "
                        "VALUES (%s, %s, %s, %s);",
                        [self.id, acc[0], acc[1], acc[2]])
                else:
                    db.perform(
                        "INSERT INTO users.accounts "
                        "(user_id, type, address) "
                        "VALUES (%s, %s, %s);", [self.id, acc[0], acc[1]])

            except IntegrityError:
                log.error("%s %s already exists" % (acc[0], acc[1]))

        self.accounts_add = []

        for type, address in self.accounts_del:
            db.perform(
                "DELETE FROM users.accounts WHERE "
                "user_id=%s AND type=%s AND address=%s;",
                [self.id, type, address])

            db.perform(
                "DELETE FROM users.accounts_unconfirmed WHERE "
                "user_id=%s AND type=%s AND address=%s;",
                [self.id, type, address])

        self.accounts_del = []

        # save profile
        if self.profile_upd:
            for table in self.profile_upd:
                f = []
                for k in self.profile_upd[table]:
                    f.append("%s=%%(%s)s" % (k, k))
                try:
                    try:
                        db.perform("INSERT INTO %s (id) VALUES (%%s);" % \
                                   table, [self.id])
                    except IntegrityError:
                        pass
                    db.perform("UPDATE %s SET %s WHERE id=%s;" % \
                               (table, ','.join(f), self.id),
                               self.profile_upd[table])
                    cache_del('profile:%s:%s' % (table, self.id))
                except ProgrammingError:
                    raise KeyError
                except DataError:
                    raise ValueError
            self.profile_upd = {}

        if self.info_upd:
            f = []
            for k in self.info_upd:
                #if not self.info_upd[k]:
                #    self.info_upd[k] = None
                f.append("%s=%%(%s)s" % (k, k))
            db.perform("UPDATE users.info SET %s WHERE id=%s;" % \
                       (','.join(f), self.id),
                       self.info_upd)
            self.info_upd = {}
            cache_del('userinfo:%s' % self.id)

        if self.password:
            db.perform("UPDATE users.logins SET password=%s WHERE id=%s;",
                       (self.password, self.id))
예제 #11
0
    def save(self):
        if not self.login:
            raise UserError("Cannot save anonymous user")

        is_new = False

        # create user
        if not self.id:
            if not self.login or not validate_nickname(self.login):
                raise UserError('Invalid Login: "******"' % self.login)
            self.id = db.fetchone("INSERT INTO users.logins (login, type) "
                                 "VALUES (%s, %s) RETURNING id;",
                                 [self.login, self.type])[0]
            db.perform("INSERT INTO users.info (id, name) VALUES (%s, %s);",
                       [self.id, self.login])
            db.perform("INSERT INTO users.profile (id, private, lang) "
                       "VALUES (%s, false, 'en');", [self.id])

            self.accounts_add = self.accounts
            is_new = True

        if not is_new:
            try:
                if self._private == True:
                    self._set_private()
                elif self._private == False:
                    self._set_public()
            except AttributeError:
                pass

        # save accounts
        for acc in self.accounts_add:
            try:
                if len(acc) == 3:
                    db.perform("INSERT INTO users.accounts_unconfirmed "
                               "(user_id, type, address, code) "
                               "VALUES (%s, %s, %s, %s);",
                               [self.id, acc[0], acc[1], acc[2]])
                else:
                    db.perform("INSERT INTO users.accounts "
                               "(user_id, type, address) "
                               "VALUES (%s, %s, %s);",
                               [self.id, acc[0], acc[1]])


            except IntegrityError:
                log.error("%s %s already exists" % (acc[0], acc[1]))

        self.accounts_add = []

        for type, address in self.accounts_del:
            db.perform("DELETE FROM users.accounts WHERE "
                       "user_id=%s AND type=%s AND address=%s;",
                       [self.id, type, address])

            db.perform("DELETE FROM users.accounts_unconfirmed WHERE "
                       "user_id=%s AND type=%s AND address=%s;",
                       [self.id, type, address])

        self.accounts_del = []

        # save profile
        if self.profile_upd:
            for table in self.profile_upd:
                f = []
                for k in self.profile_upd[table]:
                    f.append("%s=%%(%s)s" % (k, k))
                try:
                    try:
                        db.perform("INSERT INTO %s (id) VALUES (%%s);" % \
                                   table, [self.id])
                    except IntegrityError:
                        pass
                    db.perform("UPDATE %s SET %s WHERE id=%s;" % \
                               (table, ','.join(f), self.id),
                               self.profile_upd[table])
                    cache_del('profile:%s:%s' % (table, self.id))
                except ProgrammingError:
                    raise KeyError
                except DataError:
                    raise ValueError
            self.profile_upd = {}

        if self.info_upd:
            f = []
            for k in self.info_upd:
                #if not self.info_upd[k]:
                #    self.info_upd[k] = None
                f.append("%s=%%(%s)s" % (k, k))
            db.perform("UPDATE users.info SET %s WHERE id=%s;" % \
                       (','.join(f), self.id),
                       self.info_upd)
            self.info_upd = {}
            cache_del('userinfo:%s' % self.id)

        if self.password:
            db.perform("UPDATE users.logins SET password=%s WHERE id=%s;",
                       (self.password, self.id))
예제 #12
0
파일: auth.py 프로젝트: Raegdan/www-new
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())