Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate unique username (omniauth + devise)

I have an app with user authentication with devise + omniauth.

In my model that username in my app is unique. I dont want duplicate username in my app.

Some users in facebook has not a defined username in his profile.

I want generate an unique username if the user has not username defined in facebook.

For example for generate password I have this:

:password => Devise.friendly_token[0,20]

How can I generate a unique username for my app if the facebook user has not username in facebook?

Thank you

like image 750
hyperrjas Avatar asked Mar 28 '12 10:03

hyperrjas


2 Answers

You can create a nice readable username (eg generated from the first part of the email) and then ensure it is unique by adding numbers until it is. eg

#in User
def get_unique_login
  login_part = self.email.split("@").first
  new_login = login_part.dup 
  num = 2
  while(User.find_by_login(new_login).count > 0)
    new_login = "#{login_part}#{num}"
    num += 1
  end
  new_login
end

One problem here is that someone could potentially bag that login inbetween you getting it and you saving it. So, maybe it's best to combine it into a before_create filter:

#in User
before_create :ensure_login_uniqueness

def ensure_login_uniqueness 
  if self.login.blank? || User.find_by_login(self.login).count > 0
    login_part = self.email.split("@").first
    new_login = login_part.dup 
    num = 2
    while(User.find_by_login(new_login).count > 0)
      new_login = "#{login_part}#{num}"
      num += 1
    end
    self.login = new_login
  end
end
like image 115
Max Williams Avatar answered Oct 09 '22 06:10

Max Williams


You can take a part of email before the @ sign and add there smth like user_id, or just take the email itself. Or you can combine somehow the first and last names from the fb response.

like image 39
alony Avatar answered Oct 09 '22 07:10

alony