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

79 lines
2.2 KiB
Crystal

# 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/>.
module Backend
module Db
# User model
class User < Granite::Base
table users
has_one :teacher
has_one :student
# User's ID
column id : Int64, primary: true
# User's LDAP username
column username : String
# User's role
column role : String
# User is admin
column admin : Bool = false
# User's first name
def firstname : String
Ldap.user(Ldap.uid(@username.not_nil!)).first["givenName"].first
end
# User's last name
def lastname : String
Ldap.user(Ldap.uid(@username.not_nil!)).first["sn"].first
end
# User's full name
def name : String
Ldap.user(Ldap.uid(@username.not_nil!)).first["cn"].first
end
# User's email
def email : String
Ldap.user(Ldap.uid(@username.not_nil!)).first["mail"].first
end
validate :role, "needs to be a valid role" do |user|
UserRole.parse(user.role).in?(UserRole.values)
end
validate :role, "user external needs to be a valid role" do |user|
if user.teacher.nil? && user.student.nil?
true
else
!!case UserRole.parse(user.role)
when .teacher?
user.teacher && user.student.nil?
when .student?
user.teacher.nil? && user.student
else
false
end
end
end
end
end
end