OSDN Git Service

fix:error dlg
[pettanr/pettanr.git] / app / models / user.rb
1 class User < ActiveRecord::Base
2   has_one :author
3   has_one :artist
4   
5   # Include default devise modules. Others available are:
6   # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
7   devise :database_authenticatable, :registerable,
8          :recoverable, :rememberable, :trackable,  :validatable, 
9          :omniauthable, :omniauth_providers => [:twitter, :google_oauth2]
10          #, :confirmable
11   
12   def create_token
13     loop do
14       token = Devise.friendly_token
15       if token_suitable?(token)
16         self.authentication_token = token
17         break
18       end
19     end
20     self.save
21   end
22   
23   def token_suitable?(token)
24     !self.class.exists?(authentication_token: token)
25   end
26   
27   def delete_token
28     self.authentication_token = nil
29     self.save
30   end
31   
32   def destroy
33     res = false
34     User.transaction do
35       self.author.scrolls.each do |scroll|
36         raise ActiveRecord::Rollback unless scroll.destroy_with_scroll_panel
37       end
38       self.author.panels.each do |panel|
39         raise ActiveRecord::Rollback unless panel.destroy_with_elements
40       end
41       if self.artist
42         self.artist.original_pictures.each do |original_picture|
43           raise ActiveRecord::Rollback unless original_picture.destroy_with_resource_picture
44         end
45         raise ActiveRecord::Rollback unless self.artist.destroy
46       end
47       raise ActiveRecord::Rollback unless self.author.destroy
48       raise ActiveRecord::Rollback unless super
49       res = true
50     end
51     res
52   end
53   
54   def self.from_omniauth(auth)
55     where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
56       user.name = auth.info.nickname
57       user.email = auth.info.email
58     end
59   end
60   
61   def self.new_with_session(params, session)
62     if session["devise.user_attributes"]
63       new(session["devise.user_attributes"], without_protection: true) do |user|
64         user.attributes = params
65         user.valid?
66       end
67     else
68       super
69     end
70   end
71   
72   def password_required?
73     super && provider.blank?
74   end
75   
76   private
77   def user_params
78     params.require(:user).permit(:email, :password, :password_confirmation, :remember_me, :authentication_token)
79   end
80   
81 end