def_find_or_create_user.rb

James Turnbull, 2008-06-02 16:53

Download (1.78 KB)

 
1
   class TracAttribute < ActiveRecord::Base
2
        set_table_name :session_attribute
3
   end
4

    
5
  def self.find_or_create_user(username, project_member = false)
6
        return User.anonymous if username.blank?
7
        
8
        u = User.find_by_login(username)
9
        if !u
10
          # Create a new user if not found
11
          TracAttribute.find_by_sql("SELECT value FROM #{TracAttribute.table_name} WHERE sid='#{username}' AND name='email'").each do |attrib|
12
              @mail = attrib.value
13
          end
14
          TracAttribute.find_by_sql("SELECT value FROM #{TracAttribute.table_name} WHERE sid='#{username}' AND name='name'").each do |attrib|
15
              @fn = $1 if attrib.value =~ (/(\w+)/)
16
              @ln = $1 if attrib.value =~ (/(\s+\w+)/)
17
          end
18
          @ln2 = @ln.gsub(/^\s+/, "")
19
          u = User.new :firstname => @fn,
20
                       :lastname => @ln2,
21
                       :mail => @mail
22
          u.login = username[0,limit_for(User, 'login')].gsub(/[^a-z0-9_\-@\.]/i, '-')
23
          u.password = 'trac'
24
          u.admin = true if TracPermission.find_by_username_and_action(username, 'admin')
25
          @fn = ''
26
          @ln = ''
27
          @ln2 = ''
28
          @mail = ''
29
          # finally, a default user is used if the new user is not valid
30
          u = User.find(:first) unless u.save
31
        end
32
        # Make sure he is a member of the project
33
        if project_member && !u.member_of?(@target_project)
34
          role = DEFAULT_ROLE
35
          if u.admin
36
            role = ROLE_MAPPING['admin']
37
          elsif TracPermission.find_by_username_and_action(username, 'developer')
38
            role = ROLE_MAPPING['developer']
39
          end
40
          Member.create(:user => u, :project => @target_project, :role => role)
41
          u.reload
42
        end
43
        u
44
      end