trabajo-afectivo/app/models/token.rb

129 lines
2.6 KiB
Ruby
Raw Normal View History

2016-10-19 03:11:36 +00:00
# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
2012-04-23 06:55:16 +00:00
class Token < ActiveRecord::Base
2015-08-21 13:33:06 +00:00
before_create :generate_token
belongs_to :user
store :preferences
2012-04-23 06:55:16 +00:00
2015-08-21 13:33:06 +00:00
=begin
create new token
token = Token.create(action: 'PasswordReset', user_id: user.id)
2015-08-21 13:33:06 +00:00
returns
the token
create new persistent token
token = Token.create(
action: 'api',
2015-08-21 13:33:06 +00:00
persistent: true,
user_id: user.id,
preferences: {
permission: {
'user_preferences.calendar' => true,
}
}
2015-08-21 13:33:06 +00:00
)
in case if you use it via an controller, e. g. you can verify via "curl -H "Authorization: Token token=33562a00d7eda2a7c2fb639b91c6bcb8422067b6" http://...
returns
the token
=end
=begin
check token
user = Token.check(action: 'PasswordReset', name: '123abc12qweads')
2015-08-21 13:33:06 +00:00
check api token with permissions
user = Token.check(action: 'api', name: '123abc12qweads', permission: 'admin.session')
user = Token.check(action: 'api', name: '123abc12qweads', permission: ['admin.session', 'ticket.agent'])
2015-08-21 13:33:06 +00:00
returns
user for who this token was created
=end
2012-04-23 06:55:16 +00:00
def self.check(data)
2012-04-23 06:55:16 +00:00
# fetch token
token = Token.find_by(action: data[:action], name: data[:name])
2012-04-23 06:55:16 +00:00
return if !token
2012-04-23 06:55:16 +00:00
# check if token is still valid
if !token.persistent &&
token.created_at < 1.day.ago
2013-01-03 12:00:55 +00:00
2012-04-23 06:55:16 +00:00
# delete token
token.delete
token.save
return
end
2013-01-03 12:00:55 +00:00
user = token.user
# persistent token not valid if user is inactive
if !data[:inactive_user]
return if token.persistent && user.active == false
end
# add permission check
if data[:permission]
return if !user.permissions?(data[:permission])
return if !token.preferences[:permission]
local_permissions = data[:permission]
if data[:permission].class != Array
local_permissions = [data[:permission]]
end
match = false
local_permissions.each do |local_permission|
local_permissions = Permission.with_parents(local_permission)
local_permissions.each do |local_permission_name|
next if !token.preferences[:permission].include?(local_permission_name)
match = true
break
end
next if !match
break
end
return if !match
end
2015-06-23 12:27:17 +00:00
# return token user
user
2012-04-23 06:55:16 +00:00
end
2015-08-24 10:09:04 +00:00
=begin
cleanup old token
Token.cleanup
=end
def self.cleanup
Token.where('persistent IS ? AND created_at < ?', nil, Time.zone.now - 30.days).delete_all
true
end
2012-04-23 06:55:16 +00:00
private
def generate_token
loop do
self.name = SecureRandom.urlsafe_base64(48)
break if !Token.exists?(name: name)
end
true
end
end