Class: UserAuthToken

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/user_auth_token.rb

Constant Summary collapse

ROTATE_TIME_MINS =
10
ROTATE_TIME =
ROTATE_TIME_MINS.minutes
URGENT_ROTATE_TIME =

used when token did not arrive at client

1.minute
MAX_SESSION_COUNT =
60
USER_ACTIONS =
["generate"]
RAD_PER_DEG =
Math::PI / 180
EARTH_RADIUS_KM =

kilometers

6371

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#unhashed_auth_tokenObject

Returns the value of attribute unhashed_auth_token.



16
17
18
# File 'app/models/user_auth_token.rb', line 16

def unhashed_auth_token
  @unhashed_auth_token
end

Class Method Details

.cleanup!Object



198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'app/models/user_auth_token.rb', line 198

def self.cleanup!
  if SiteSetting.verbose_auth_token_logging
    UserAuthTokenLog.where(
      "created_at < :time",
      time: SiteSetting.maximum_session_age.hours.ago - ROTATE_TIME,
    ).delete_all
  end

  where(
    "rotated_at < :time",
    time: SiteSetting.maximum_session_age.hours.ago - ROTATE_TIME,
  ).delete_all
end

.distance(loc1, loc2) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
# File 'app/models/user_auth_token.rb', line 46

def self.distance(loc1, loc2)
  lat1_rad, lon1_rad = loc1[0] * RAD_PER_DEG, loc1[1] * RAD_PER_DEG
  lat2_rad, lon2_rad = loc2[0] * RAD_PER_DEG, loc2[1] * RAD_PER_DEG

  a =
    Math.sin((lat2_rad - lat1_rad) / 2)**2 +
      Math.cos(lat1_rad) * Math.cos(lat2_rad) * Math.sin((lon2_rad - lon1_rad) / 2)**2
  c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))

  c * EARTH_RADIUS_KM
end

.enforce_session_count_limit!(user_id) ⇒ Object



260
261
262
263
264
265
266
267
268
# File 'app/models/user_auth_token.rb', line 260

def self.enforce_session_count_limit!(user_id)
  tokens_to_destroy =
    where(user_id: user_id)
      .where("rotated_at > ?", SiteSetting.maximum_session_age.hours.ago)
      .order("rotated_at DESC")
      .offset(MAX_SESSION_COUNT)

  tokens_to_destroy.delete_all # Returns the number of deleted rows
end

.generate!(user_id:, user_agent: nil, client_ip: nil, path: nil, staff: nil, impersonate: false) ⇒ Object



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
115
116
# File 'app/models/user_auth_token.rb', line 75

def self.generate!(
  user_id:,
  user_agent: nil,
  client_ip: nil,
  path: nil,
  staff: nil,
  impersonate: false
)
  token = SecureRandom.hex(16)
  hashed_token = hash_token(token)
  user_auth_token =
    UserAuthToken.create!(
      user_id: user_id,
      user_agent: user_agent,
      client_ip: client_ip,
      auth_token: hashed_token,
      prev_auth_token: hashed_token,
      rotated_at: Time.zone.now,
    )
  user_auth_token.unhashed_auth_token = token

  log(
    action: "generate",
    user_auth_token_id: user_auth_token.id,
    user_id: user_id,
    user_agent: user_agent,
    client_ip: client_ip,
    path: path,
    auth_token: hashed_token,
  )

  if staff && !impersonate
    Jobs.enqueue(
      :suspicious_login,
      user_id: user_id,
      client_ip: client_ip,
      user_agent: user_agent,
    )
  end

  user_auth_token
end

.hash_token(token) ⇒ Object



194
195
196
# File 'app/models/user_auth_token.rb', line 194

def self.hash_token(token)
  Digest::SHA1.base64digest("#{token}#{GlobalSetting.safe_secret_key_base}")
end

.is_suspicious(user_id, user_ip) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'app/models/user_auth_token.rb', line 58

def self.is_suspicious(user_id, user_ip)
  return false unless User.find_by(id: user_id)&.staff?

  ips = UserAuthTokenLog.where(user_id: user_id).pluck(:client_ip)
  ips.delete_at(ips.index(user_ip) || ips.length) # delete one occurrence (current)
  ips.uniq!
  return false if ips.empty? # first login is never suspicious

  if user_location = (user_ip)
    ips.none? do |ip|
      if location = (ip)
        distance(user_location, location) < SiteSetting.max_suspicious_distance_km
      end
    end
  end
end

.log(info) ⇒ Object



29
30
31
# File 'app/models/user_auth_token.rb', line 29

def self.log(info)
  UserAuthTokenLog.create!(info)
end

.log_verbose(info) ⇒ Object



33
34
35
# File 'app/models/user_auth_token.rb', line 33

def self.log_verbose(info)
  log(info) if SiteSetting.verbose_auth_token_logging
end

.login_location(ip) ⇒ Object



40
41
42
43
44
# File 'app/models/user_auth_token.rb', line 40

def self.(ip)
  ipinfo = DiscourseIpInfo.get(ip)

  ipinfo[:latitude] && ipinfo[:longitude] ? [ipinfo[:latitude], ipinfo[:longitude]] : nil
end

.lookup(unhashed_token, opts = nil) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'app/models/user_auth_token.rb', line 118

def self.lookup(unhashed_token, opts = nil)
  mark_seen = opts && opts[:seen]

  token = hash_token(unhashed_token)
  expire_before = SiteSetting.maximum_session_age.hours.ago

  user_token =
    find_by(
      "(auth_token = :token OR
                        prev_auth_token = :token) AND rotated_at > :expire_before",
      token: token,
      expire_before: expire_before,
    )

  if !user_token
    log_verbose(
      action: "miss token",
      user_id: nil,
      auth_token: token,
      user_agent: opts && opts[:user_agent],
      path: opts && opts[:path],
      client_ip: opts && opts[:client_ip],
    )

    return nil
  end

  if user_token.auth_token != token && user_token.prev_auth_token == token &&
       user_token.auth_token_seen
    changed_rows =
      UserAuthToken
        .where("rotated_at < ?", 1.minute.ago)
        .where(id: user_token.id, prev_auth_token: token)
        .update_all(auth_token_seen: false)

    # not updating AR model cause we want to give it one more req
    # with wrong cookie
    UserAuthToken.log_verbose(
      action: changed_rows == 0 ? "prev seen token unchanged" : "prev seen token",
      user_auth_token_id: user_token.id,
      user_id: user_token.user_id,
      auth_token: user_token.auth_token,
      user_agent: opts && opts[:user_agent],
      path: opts && opts[:path],
      client_ip: opts && opts[:client_ip],
    )
  end

  if mark_seen && user_token && !user_token.auth_token_seen && user_token.auth_token == token
    # we must protect against concurrency issues here
    changed_rows =
      UserAuthToken.where(id: user_token.id, auth_token: token).update_all(
        auth_token_seen: true,
        seen_at: Time.zone.now,
      )

    if changed_rows == 1
      # not doing a reload so we don't risk loading a rotated token
      user_token.auth_token_seen = true
      user_token.seen_at = Time.zone.now
    end

    log_verbose(
      action: changed_rows == 0 ? "seen wrong token" : "seen token",
      user_auth_token_id: user_token.id,
      user_id: user_token.user_id,
      auth_token: user_token.auth_token,
      user_agent: opts && opts[:user_agent],
      path: opts && opts[:path],
      client_ip: opts && opts[:client_ip],
    )
  end

  user_token
end

Instance Method Details

#rotate!(info = nil) ⇒ Object



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'app/models/user_auth_token.rb', line 212

def rotate!(info = nil)
  user_agent = (info && info[:user_agent] || self.user_agent)
  client_ip = (info && info[:client_ip] || self.client_ip)

  token = SecureRandom.hex(16)

  result =
    DB.exec(
      "
UPDATE user_auth_tokens
SET
  auth_token_seen = false,
  seen_at = null,
  user_agent = :user_agent,
  client_ip = :client_ip,
  prev_auth_token = case when auth_token_seen then auth_token else prev_auth_token end,
  auth_token = :new_token,
  rotated_at = :now
WHERE id = :id AND (auth_token_seen or rotated_at < :safeguard_time)
",
      id: self.id,
      user_agent: user_agent,
      client_ip: client_ip&.to_s,
      now: Time.zone.now,
      new_token: UserAuthToken.hash_token(token),
      safeguard_time: 30.seconds.ago,
    )

  if result > 0
    reload
    self.unhashed_auth_token = token

    UserAuthToken.log(
      action: "rotate",
      user_auth_token_id: id,
      user_id: user_id,
      auth_token: auth_token,
      user_agent: user_agent,
      client_ip: client_ip,
      path: info && info[:path],
    )

    true
  else
    false
  end
end