示例#1
0
    def process(self, db, user, username, password):
        if not user.isAnonymous():
            if user.name == username:
                return OperationResult()
            else:
                return OperationResult(message="Already signed as '%s'!" % user.name)

        try:
            auth.checkPassword(db, username, password)
        except auth.NoSuchUser:
            return OperationResult(message="No such user!")
        except auth.WrongPassword:
            return OperationResult(message="Wrong password!")

        sid = base64.b64encode(hashlib.sha1(os.urandom(20)).digest())

        cursor = db.cursor()
        cursor.execute(
            """INSERT INTO usersessions (key, uid)
                               SELECT %s, id
                                 FROM users
                                WHERE name=%s""",
            (sid, username),
        )

        db.commit()

        return OperationResult().setCookie("sid", sid)
示例#2
0
    def process(self, db, user, username, password):
        if not user.isAnonymous():
            if user.name == username:
                return OperationResult()
            else:
                return OperationResult(message="Already signed as '%s'!" % user.name)

        try: auth.checkPassword(db, username, password)
        except auth.NoSuchUser: return OperationResult(message="No such user!")
        except auth.WrongPassword: return OperationResult(message="Wrong password!")

        sid = base64.b64encode(hashlib.sha1(os.urandom(20)).digest())

        cursor = db.cursor()
        cursor.execute("""INSERT INTO usersessions (key, uid)
                               SELECT %s, id
                                 FROM users
                                WHERE name=%s""",
                       (sid, username))

        db.commit()

        # Set 'sid' and 'has_sid' cookies.
        #
        # The 'has_sid' cookie is significant if the system is accessible over
        # both HTTP and HTTPS.  In that case, the 'sid' cookie is set with the
        # "secure" flag, so is only sent over HTTPS.  The 'has_sid' cookie is
        # then used to detect that an HTTP client would have sent a 'sid' cookie
        # if the request instead had been made over HTTPS, in which case we
        # redirect the client to HTTPS automatically.

        result = OperationResult()
        result.setCookie("sid", sid, secure=True)
        result.setCookie("has_sid", "1")
        return result
示例#3
0
    def process(self, db, user, user_id, new_pw, current_pw=None):
        import auth

        if (user.id != user_id or current_pw is None) and not user.hasRole(db, "administrator"):
            raise OperationFailure(code="notallowed",
                                   title="Not allowed!",
                                   message="Operation not permitted.")

        subject = dbutils.User.fromId(db, user_id)

        if current_pw is not None:
            try: auth.checkPassword(db, subject.name, current_pw)
            except auth.WrongPassword:
                raise OperationFailure(code="wrongpassword",
                                       title="Wrong password!",
                                       message="The provided current password is not correct.")

        if not new_pw:
            raise OperationFailure(code="emptypassword",
                                   title="Empty password!",
                                   message="Setting an empty password is not allowed.")

        cursor = db.cursor()
        cursor.execute("UPDATE users SET password=%s WHERE id=%s", (auth.hashPassword(new_pw), user_id))

        db.commit()

        return OperationResult()
示例#4
0
    def process(self, db, user, new_pw, subject=None, current_pw=None):
        import auth

        if subject is None:
            user_id = user.id
        elif isinstance(subject, basestring):
            user_id = dbutils.User.fromName(db, subject).id
        else:
            user_id = subject

        if user.id != user_id or current_pw is None:
            Operation.requireRole(db, "administrator", user)

        subject = dbutils.User.fromId(db, user_id)

        if current_pw is not None:
            try: auth.checkPassword(db, subject.name, current_pw)
            except auth.WrongPassword:
                raise OperationFailure(code="wrongpassword",
                                       title="Wrong password!",
                                       message="The provided current password is not correct.")

        if not new_pw:
            raise OperationFailure(code="emptypassword",
                                   title="Empty password!",
                                   message="Setting an empty password is not allowed.")

        cursor = db.cursor()
        cursor.execute("UPDATE users SET password=%s WHERE id=%s", (auth.hashPassword(new_pw), user_id))

        db.commit()

        return OperationResult()
示例#5
0
    def process(self, db, user, user_id, new_pw, current_pw=None):
        import auth

        if (user.id != user_id or current_pw is None) and not user.hasRole(db, "administrator"):
            raise OperationFailure(code="notallowed",
                                   title="Not allowed!",
                                   message="Operation not permitted.")

        subject = dbutils.User.fromId(db, user_id)

        if current_pw is not None:
            try: auth.checkPassword(db, subject.name, current_pw)
            except auth.WrongPassword:
                raise OperationFailure(code="wrongpassword",
                                       title="Wrong password!",
                                       message="The provided current password is not correct.")

        if not new_pw:
            raise OperationFailure(code="emptypassword",
                                   title="Empty password!",
                                   message="Setting an empty password is not allowed.")

        cursor = db.cursor()
        cursor.execute("UPDATE users SET password=%s WHERE id=%s", (auth.hashPassword(new_pw), user_id))

        db.commit()

        return OperationResult()
示例#6
0
    def changePassword(self, db, user, current_pw, new_pw):
        # If |current_pw| is True, then this is an administrator changing
        # another user's password. The usual rules do not apply.
        if current_pw is not True:
            cursor = db.readonly_cursor()
            cursor.execute("SELECT password FROM users WHERE id=%s", (user.id,))

            hashed_pw, = cursor.fetchone()

            if current_pw is not None:
                auth.checkPassword(db, user.name, current_pw)
            elif hashed_pw is not None:
                # This is mostly a sanity check; the only way to trigger this is
                # if the user has no password when he loads /home, sets a
                # password in another tab or using another browser, and then
                # tries to set (rather than change) the password using the old
                # stale /home.
                raise auth.WrongPassword

        with db.updating_cursor("users") as cursor:
            cursor.execute("UPDATE users SET password=%s WHERE id=%s",
                           (auth.hashPassword(new_pw), user.id))
示例#7
0
    def process(self, db, user, new_pw, subject=None, current_pw=None):
        if subject is None:
            subject = user

        cursor = db.cursor()

        if user != subject:
            Operation.requireRole(db, "administrator", user)
        elif current_pw is None:
            cursor.execute("SELECT password FROM users WHERE id=%s", (subject.id,))
            if cursor.fetchone()[0] is not None:
                # This is mostly a sanity check; the only way to trigger this is
                # if the user has no password when he loads /home, sets a
                # password in another tab or using another browser, and then
                # tries to set (rather than change) the password using the old
                # stale /home.
                raise OperationFailure(code="wrongpassword",
                                       title="Wrong password!",
                                       message="No current password provided.")

        if current_pw is not None:
            try: auth.checkPassword(db, subject.name, current_pw)
            except auth.WrongPassword:
                raise OperationFailure(code="wrongpassword",
                                       title="Wrong password!",
                                       message="The provided current password is not correct.")

        if not new_pw:
            raise OperationFailure(code="emptypassword",
                                   title="Empty password!",
                                   message="Setting an empty password is not allowed.")

        cursor.execute("UPDATE users SET password=%s WHERE id=%s",
                       (auth.hashPassword(new_pw), subject.id))

        db.commit()

        return OperationResult()
示例#8
0
    def authenticate(self, db, values):
        username = values["username"].strip()
        if not username:
            raise auth.database.AuthenticationFailed("Empty username")
        password = values["password"]
        if not password:
            raise auth.database.AuthenticationFailed("Empty password")

        try:
            db.setUser(auth.checkPassword(db, username, password))
        except auth.NoSuchUser:
            raise auth.AuthenticationFailed("Invalid username")
        except auth.WrongPassword:
            raise auth.AuthenticationFailed("Wrong password")
示例#9
0
    def process(self, db, user, req, username, password):
        if not user.isAnonymous():
            if user.name == username:
                return OperationResult()
            else:
                return OperationResult(message="Already signed as '%s'!" % user.name)

        try:
            user = auth.checkPassword(db, username, password)
        except auth.NoSuchUser:
            return OperationResult(message="No such user!")
        except auth.WrongPassword:
            return OperationResult(message="Wrong password!")

        auth.startSession(db, req, user)

        db.commit()

        return OperationResult()
示例#10
0
    def process(self, db, user, req, username, password):
        if not user.isAnonymous():
            if user.name == username:
                return OperationResult()
            else:
                return OperationResult(message="Already signed as '%s'!" %
                                       user.name)

        try:
            user = auth.checkPassword(db, username, password)
        except auth.NoSuchUser:
            return OperationResult(message="No such user!")
        except auth.WrongPassword:
            return OperationResult(message="Wrong password!")

        auth.startSession(db, req, user)

        db.commit()

        return OperationResult()
示例#11
0
文件: request.py 项目: KurSh/critic
    def __setUser(self, db, environ):
        if configuration.base.AUTHENTICATION_MODE == "host":
            self.user = environ.get("REMOTE_USER")
        elif configuration.base.AUTHENTICATION_MODE == "critic":
            import auth
            import base64

            self.user = None

            authorization = self.getRequestHeader("Authorization")
            if not authorization: return

            authtype, base64_credentials = authorization.split()
            if authtype != "Basic": return

            credentials = base64.b64decode(base64_credentials).split(":")
            if len(credentials) < 2: return

            for index in range(1, len(credentials)):
                username = "******".join(credentials[:index])
                password = "******".join(credentials[index:])
                if auth.checkPassword(db, username, password):
                    self.user = username
                    return
示例#12
0
    def setUser(self, db):
        if configuration.base.AUTHENTICATION_MODE == "host":
            try:
                self.user = self.__environ["REMOTE_USER"]
            except KeyError:
                if configuration.base.ALLOW_ANONYMOUS_USER:
                    return
                raise MissingWSGIRemoteUser
        else:
            session_type = configuration.base.SESSION_TYPE

            authorization_header = self.getRequestHeader("Authorization")

            if authorization_header is not None and not self.cookies:
                session_type = "httpauth"

            if session_type == "cookie":
                sid = self.cookies.get("sid")

                if not sid:
                    return

                cursor = db.cursor()
                cursor.execute("""SELECT name, EXTRACT('epoch' FROM NOW() - atime) AS age
                                    FROM usersessions
                                    JOIN users ON (id=uid)
                                   WHERE key=%s""",
                               (sid,))

                row = cursor.fetchone()

                if not row:
                    if self.path != "validatelogin":
                        cookie = "sid=invalid; Expires=Thursday 01-Jan-1970 00:00:00 GMT"
                        self.addResponseHeader("Set-Cookie", cookie)
                    if self.path in INSECURE_PATHS:
                        return
                    raise NeedLogin(self, optional=True)

                user, session_age = row

                if configuration.base.SESSION_MAX_AGE == 0 \
                        or session_age < configuration.base.SESSION_MAX_AGE:
                    self.user = user

                    cursor.execute("""UPDATE usersessions
                                         SET atime=NOW()
                                       WHERE key=%s""",
                                   (sid,))
                    db.commit()
            else:
                import auth
                import base64

                self.user = None

                if not authorization_header: return

                authtype, base64_credentials = authorization_header.split()
                if authtype != "Basic": return

                credentials = base64.b64decode(base64_credentials).split(":")
                if len(credentials) < 2: return

                for index in range(1, len(credentials)):
                    username = "******".join(credentials[:index])
                    password = "******".join(credentials[index:])
                    try:
                        auth.checkPassword(db, username, password)
                        self.user = username
                        return
                    except auth.CheckFailed: pass
示例#13
0
    def setUser(self, db):
        if configuration.base.AUTHENTICATION_MODE == "host":
            try:
                self.user = self.__environ["REMOTE_USER"]
            except KeyError:
                if configuration.base.ALLOW_ANONYMOUS_USER:
                    return
                raise MissingWSGIRemoteUser
        else:
            session_type = configuration.base.SESSION_TYPE

            authorization_header = self.getRequestHeader("Authorization")

            if authorization_header is not None and not self.cookies:
                session_type = "httpauth"

            if session_type == "cookie":
                sid = self.cookies.get("sid")

                if not sid:
                    return

                cursor = db.cursor()
                cursor.execute(
                    """SELECT name, EXTRACT('epoch' FROM NOW() - atime) AS age
                                    FROM usersessions
                                    JOIN users ON (id=uid)
                                   WHERE key=%s""", (sid, ))

                row = cursor.fetchone()

                if not row:
                    if self.path != "validatelogin":
                        cookie = "sid=invalid; Expires=Thursday 01-Jan-1970 00:00:00 GMT"
                        self.addResponseHeader("Set-Cookie", cookie)
                    if self.path in INSECURE_PATHS:
                        return
                    raise NeedLogin(self, optional=True)

                user, session_age = row

                if configuration.base.SESSION_MAX_AGE == 0 \
                        or session_age < configuration.base.SESSION_MAX_AGE:
                    self.user = user

                    cursor.execute(
                        """UPDATE usersessions
                                         SET atime=NOW()
                                       WHERE key=%s""", (sid, ))
                    db.commit()
            else:
                import auth
                import base64

                self.user = None

                if not authorization_header: return

                authtype, base64_credentials = authorization_header.split()
                if authtype != "Basic": return

                credentials = base64.b64decode(base64_credentials).split(":")
                if len(credentials) < 2: return

                for index in range(1, len(credentials)):
                    username = "******".join(credentials[:index])
                    password = "******".join(credentials[index:])
                    try:
                        auth.checkPassword(db, username, password)
                        self.user = username
                        return
                    except auth.CheckFailed:
                        pass
示例#14
0
文件: request.py 项目: Tigge/critic
    def __setUser(self, db, environ):
        if configuration.base.AUTHENTICATION_MODE == "host":
            try:
                self.user = environ["REMOTE_USER"]
            except KeyError:
                raise MissingWSGIRemoteUser
        elif configuration.base.AUTHENTICATION_MODE == "critic":
            if configuration.base.SESSION_TYPE == "cookie":
                header = self.getRequestHeader("Cookie")
                if header:
                    cookies = map(str.strip, header.split(";"))
                    key = None

                    for cookie in cookies:
                        name, value = cookie.split("=", 1)
                        if name == "sid":
                            key = value
                            break

                    if key:
                        cursor = db.cursor()
                        cursor.execute("""SELECT name, EXTRACT('epoch' FROM NOW() - atime) AS age
                                            FROM usersessions
                                            JOIN users ON (id=uid)
                                           WHERE key=%s""",
                                       (key,))

                        try: user, session_age = cursor.fetchone()
                        except: return

                        if configuration.base.SESSION_MAX_AGE == 0 \
                                or session_age < configuration.base.SESSION_MAX_AGE:
                            self.user = user

                            cursor.execute("""UPDATE usersessions
                                                 SET atime=NOW()
                                               WHERE key=%s""",
                                           (key,))
                            db.commit()
            else:
                import auth
                import base64

                self.user = None

                authorization = self.getRequestHeader("Authorization")
                if not authorization: return

                authtype, base64_credentials = authorization.split()
                if authtype != "Basic": return

                credentials = base64.b64decode(base64_credentials).split(":")
                if len(credentials) < 2: return

                for index in range(1, len(credentials)):
                    username = "******".join(credentials[:index])
                    password = "******".join(credentials[index:])
                    try:
                        auth.checkPassword(db, username, password)
                        self.user = username
                        return
                    except auth.CheckFailed: pass
示例#15
0
    def __setUser(self, db, environ):
        if configuration.base.AUTHENTICATION_MODE == "host":
            try:
                self.user = environ["REMOTE_USER"]
            except KeyError:
                raise MissingWSGIRemoteUser
        elif configuration.base.AUTHENTICATION_MODE == "critic":
            if configuration.base.SESSION_TYPE == "cookie":
                header = self.getRequestHeader("Cookie")
                if header:
                    cookies = map(str.strip, header.split(";"))
                    key = None

                    for cookie in cookies:
                        name, value = cookie.split("=", 1)
                        if name == "sid":
                            key = value
                            break

                    if key:
                        cursor = db.cursor()
                        cursor.execute(
                            """SELECT name, EXTRACT('epoch' FROM NOW() - atime) AS age
                                            FROM usersessions
                                            JOIN users ON (id=uid)
                                           WHERE key=%s""", (key, ))

                        try:
                            user, session_age = cursor.fetchone()
                        except:
                            return

                        if configuration.base.SESSION_MAX_AGE == 0 \
                                or session_age < configuration.base.SESSION_MAX_AGE:
                            self.user = user

                            cursor.execute(
                                """UPDATE usersessions
                                                 SET atime=NOW()
                                               WHERE key=%s""", (key, ))
                            db.commit()
            else:
                import auth
                import base64

                self.user = None

                authorization = self.getRequestHeader("Authorization")
                if not authorization: return

                authtype, base64_credentials = authorization.split()
                if authtype != "Basic": return

                credentials = base64.b64decode(base64_credentials).split(":")
                if len(credentials) < 2: return

                for index in range(1, len(credentials)):
                    username = "******".join(credentials[:index])
                    password = "******".join(credentials[index:])
                    try:
                        auth.checkPassword(db, username, password)
                        self.user = username
                        return
                    except auth.CheckFailed:
                        pass