-
Notifications
You must be signed in to change notification settings - Fork 12
/
github_user_syncer.rb
77 lines (63 loc) · 1.83 KB
/
github_user_syncer.rb
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
# frozen_string_literal: true
module DiscourseCodeReview
class GithubUserSyncer
def ensure_user(name:, email: nil, github_login: nil, github_id: nil)
user = nil
user ||=
if github_id
User.find_by(
id:
UserCustomField
.select(:user_id)
.where(name: GithubId, value: github_id)
.limit(1)
)
end
user ||=
if github_login
user =
User.find_by(
id:
UserCustomField
.select(:user_id)
.where(name: GithubLogin, value: github_login)
.limit(1)
)
end
user ||= begin
email ||= email_for(github_login)
User.find_by_email(email)
end
user ||= begin
username = UserNameSuggester.sanitize_username(github_login || name)
User.create!(
email: email,
username: UserNameSuggester.suggest(username.presence || email),
name: name.presence || User.suggest_name(email),
staged: true
)
end
if github_login
rel = UserCustomField.where(name: GithubLogin, value: github_login)
existing = rel.pluck(:user_id)
if existing != [user.id]
rel.destroy_all
UserCustomField.create!(name: GithubLogin, value: github_login, user_id: user.id)
end
end
if github_id
rel = UserCustomField.where(name: GithubId, value: github_id)
existing = rel.pluck(:user_id)
if existing != [user.id]
rel.destroy_all
UserCustomField.create!(name: GithubId, value: github_id, user_id: user.id)
end
end
user
end
private
def email_for(github_login)
"#{github_login}@fake.github.com"
end
end
end