Add model for admins

This commit is contained in:
Trevor Vallender 2024-05-26 10:06:04 +01:00
parent ed01262d88
commit 72bee55d7e
7 changed files with 57 additions and 1 deletions

3
app/models/site_role.rb Normal file
View File

@ -0,0 +1,3 @@
class SiteRole < ApplicationRecord
validates :name, presence: true
end

View File

@ -1,4 +1,6 @@
class User < ApplicationRecord
has_and_belongs_to_many :site_roles
has_secure_password
generates_token_for :password_reset, expires_in: 4.hours do
password_salt.last(10) # Invalidates when password changed
@ -35,4 +37,8 @@ class User < ApplicationRecord
"#{first_name} #{last_name}"
end
def admin?
site_roles.include? SiteRole.find_by(name: "Admin")
end
end

View File

@ -0,0 +1,14 @@
class CreateUserRoles < ActiveRecord::Migration[7.1]
def change
create_table :site_roles do |t|
t.string :name, null: false
t.timestamps
end
create_table :site_roles_users do |t|
t.belongs_to :user
t.belongs_to :site_role
end
end
end

15
db/schema.rb generated
View File

@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.1].define(version: 2024_05_26_084840) do
ActiveRecord::Schema[7.1].define(version: 2024_05_26_085315) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
@ -20,6 +20,19 @@ ActiveRecord::Schema[7.1].define(version: 2024_05_26_084840) do
t.datetime "updated_at", null: false
end
create_table "site_roles", force: :cascade do |t|
t.string "name", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "site_roles_users", force: :cascade do |t|
t.bigint "user_id"
t.bigint "site_role_id"
t.index ["site_role_id"], name: "index_site_roles_users_on_site_role_id"
t.index ["user_id"], name: "index_site_roles_users_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "username", limit: 20, null: false
t.string "password_digest", limit: 200, null: false

2
test/fixtures/site_roles.yml vendored Normal file
View File

@ -0,0 +1,2 @@
admin:
name: Admin

View File

@ -0,0 +1,11 @@
require "test_helper"
class PermissionsTest < ActionDispatch::IntegrationTest
test "admin? returns true for users with an admin role" do
user = users(:trevor)
assert_not user.admin?
user.site_roles << site_roles(:admin)
assert user.admin?
end
end

View File

@ -0,0 +1,7 @@
require "test_helper"
class UserRoleTest < ActiveSupport::TestCase
test "name must exist" do
assert_must_exist(site_roles(:admin), :name)
end
end