mentorenwahl/backend/src/backend/ldap/user.cr
Dominic Grimm 6620dea812
Some checks failed
continuous-integration/drone/push Build is failing
Update
2022-12-29 22:24:29 +01:00

87 lines
2.4 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/>.
require "json"
module Backend
module Ldap
# LDAP user properties
struct User
include JSON::Serializable
alias Raw = Hash(String, Array(String))
# First name
getter first_name : String
# Last name
getter last_name : String
@[JSON::Field(key: "mail")]
# Email address
getter email : String
def initialize(@first_name : String, @last_name : String, @email : String)
end
# Name
def name(formal = true) : String
if formal
"#{@last_name}, #{@first_name}"
else
"#{@first_name} #{@last_name}"
end
end
# Creates user data from LDAP entry
def self.from_raw(raw : Raw) : self
self.new(
first_name: raw["givenName"].first,
last_name: raw["sn"].first,
email: raw["mail"].first
)
end
# Creates user data from LDAP DN entry
def self.from_dn(dn : String) : self
from_raw(
CLIENT.connection do |client|
client
.authenticate(Backend.config.ldap.bind_dn, Backend.config.ldap.bind_password)
.search(base: dn, attributes: %w(givenName sn mail))
.first
end
)
end
# Creates user data from LDAP username
def self.from_username(username : String) : self
from_dn(Ldap::DN.uid(username))
end
# Creates user data from DB entry
def self.from_db(user : Db::User) : self
from_username(user.username)
end
# Creates user data from DB entry index
def self.from_id(id : Int32) : self
from_username(Db::User.query.first(id).select(:id))
end
end
end
end