mentorenwahl/docker/backend/src/backend/db/user.cr

79 lines
2.2 KiB
Crystal
Raw Normal View History

2022-02-10 07:43:47 +00:00
# Mentorenwahl: A fullstack application for assigning mentors to students based on their whishes.
# Copyright (C) 2022 Dominic Grimm
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
2022-01-23 08:12:57 +00:00
module Backend
2022-01-08 12:29:22 +00:00
module Db
2022-02-07 20:10:04 +00:00
# User model
2022-01-08 12:29:22 +00:00
class User < Granite::Base
table users
has_one :teacher
has_one :student
2022-02-07 20:10:04 +00:00
# User's ID
2022-01-08 12:29:22 +00:00
column id : Int64, primary: true
2022-02-07 20:10:04 +00:00
# User's LDAP username
2022-02-06 15:42:08 +00:00
column username : String
2022-02-07 20:10:04 +00:00
# User's role
2022-01-08 12:29:22 +00:00
column role : String
2022-02-07 20:10:04 +00:00
# User is admin
2022-02-06 15:42:08 +00:00
column admin : Bool = false
2022-02-07 20:10:04 +00:00
# User's first name
2022-02-06 15:42:08 +00:00
def firstname : String
Ldap.user(Ldap.uid(@username.not_nil!)).first["givenName"].first
end
2022-02-07 20:10:04 +00:00
# User's last name
2022-02-06 15:42:08 +00:00
def lastname : String
Ldap.user(Ldap.uid(@username.not_nil!)).first["sn"].first
end
2022-01-08 12:29:22 +00:00
2022-02-07 20:10:04 +00:00
# User's full name
2022-01-28 17:30:20 +00:00
def name : String
2022-02-06 15:42:08 +00:00
Ldap.user(Ldap.uid(@username.not_nil!)).first["cn"].first
2022-01-28 17:30:20 +00:00
end
2022-02-07 20:10:04 +00:00
# User's email
2022-02-06 15:42:08 +00:00
def email : String
Ldap.user(Ldap.uid(@username.not_nil!)).first["mail"].first
2022-01-08 12:29:22 +00:00
end
validate :role, "needs to be a valid role" do |user|
2022-01-28 17:30:20 +00:00
UserRole.parse(user.role).in?(UserRole.values)
2022-01-08 12:29:22 +00:00
end
validate :role, "user external needs to be a valid role" do |user|
2022-02-06 15:42:08 +00:00
if user.teacher.nil? && user.student.nil?
2022-01-08 12:29:22 +00:00
true
else
!!case UserRole.parse(user.role)
2022-02-06 15:42:08 +00:00
when .teacher?
user.teacher && user.student.nil?
when .student?
user.teacher.nil? && user.student
2022-01-08 12:29:22 +00:00
else
false
end
end
end
end
end
end