trabajo-afectivo/app/models/token.rb

76 lines
1.2 KiB
Ruby
Raw Normal View History

2014-02-03 19:23:00 +00:00
# Copyright (C) 2012-2014 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
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 )
returns
the token
create new persistent token
token = Token.create(
action: 'CalendarSubscriptions',
persistent: true,
user_id: user.id,
)
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: 'TheTokenItSelf' )
returns
user for who this token was created
=end
2012-04-23 06:55:16 +00:00
def self.check( data )
# 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
2015-06-23 12:27:17 +00:00
# return token user
token.user
2012-04-23 06:55:16 +00:00
end
private
def generate_token
loop do
2015-08-21 13:33:06 +00:00
self.name = SecureRandom.hex(30)
break if !Token.exists?( name: name )
end
end
end