What is a common approach to scope records by those that an user can “read”?

后端 未结 5 766
太阳男子
太阳男子 2020-12-21 13:11

I am using Ruby on Rails 3.2.2 and I would like to know what is a common approach when it must be checked if an user has proper authorizations to \"read\" records present in

5条回答
  •  情歌与酒
    2020-12-21 13:40

    It depends on your readable_by_user function. If it is easy to translate into an SQL, than it is the way forward. If it is more complicated than that then you most probably have to do the check manually.

    UPDATE: To clarify the point of creating an SQL query for the readable list I present an example. Assume, that a readability of an article to a given user is dependent of the following:

    • The user's own article (SELECT a.user == ? FROM Articles a WHERE a.id = ?)
    • The article is open to everyone (SELECT a.state == 0 FROM Articles a WHERE a.user = ?)
    • The user is member of a group with access to articles

    sql:

    SELECT max(g.rights) > 64
    FROM Groups g 
    JOIN Groups_users gu on g.id = ug.group_id
    WHERE gu.id = ?
    
    • The user is assigned to the given article

    sql:

    SELECT 1
    FROM Articles_users au
    WHERE au.article_id = ? AND au.user_id = ?
    

    These can be summarized in the following query:

    def articles_for_user(user) 
      Articles.find_by_sql(["
        SELECT a.*
        FROM Articles a
        LEFT OUTER JOIN Articles_users au on au.article_id = a.id and au.user_id = ?
        WHERE a.user_id = ? 
           OR au.user_id = ?
           OR 64 <= (SELECT max(g.rights) 
                     FROM Groups g 
                     JOIN Groups_users gu on g.id = ug.group_id
                     WHERE gu.id = ?)
      ", user.id, user.id, user.id, user.id])
    end
    

    This is sure a complicated query, but the most efficient solution. The database should do database stuff, if you only use SQL queries and some logic to evaluate your readable_bu_user then you can translate it into one pure SQL query.

提交回复
热议问题