-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathuser.rb
More file actions
114 lines (86 loc) · 1.97 KB
/
user.rb
File metadata and controls
114 lines (86 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# frozen_string_literal: true
class User
include ActiveModel::Serialization
include ActiveModel::Model
ATTRIBUTES = %w[
country
country_code
email
email_verified
id
name
nickname
picture
postcode
profile
token
username
roles
].freeze
attr_accessor(*ATTRIBUTES)
def attributes
ATTRIBUTES.index_with { |_k| nil }
end
def schools
School.joins(:roles).merge(Role.where(user_id: id)).distinct
end
def school_roles(school)
Role.where(school:, user_id: id).map(&:role)
end
def school_owner?(school)
Role.owner.find_by(school:, user_id: id)
end
def school_teacher?(school)
Role.teacher.find_by(school:, user_id: id)
end
def school_student?(school)
Role.student.find_by(school:, user_id: id)
end
def student?
Role.student.exists?(user_id: id)
end
def admin?
parsed_roles.include?('editor-admin')
end
def experience_cs_admin?
parsed_roles.include?('experience-cs-admin')
end
def parsed_roles
roles&.to_s&.split(',')&.map(&:strip) || []
end
def ==(other)
id == other.id
end
def self.where(id:)
from_userinfo(ids: id)
end
def self.from_userinfo(ids:)
user_ids = Array(ids)
UserInfoApiClient.fetch_by_ids(user_ids).map do |info|
info = info.stringify_keys
args = info.slice(*ATTRIBUTES)
new(args)
end
end
def self.from_omniauth(auth = nil)
return nil unless auth
from_auth(auth)
end
def self.from_auth(auth)
return nil unless auth
args = auth.extra.raw_info.to_h.slice(*ATTRIBUTES)
args['id'] = auth.uid
args['token'] = auth.credentials&.token
new(args)
end
def self.from_token(token:)
return nil if token.blank?
auth = HydraPublicApiClient.fetch_oauth_user(token:)
return nil if auth.blank?
auth = auth.stringify_keys
args = auth.slice(*ATTRIBUTES)
args['id'] ||= auth['sub'].sub('student:', '')
args['token'] = token
new(args)
end
end