scinote-web/app/utilities/users_generator.rb

84 lines
2.4 KiB
Ruby
Raw Normal View History

2016-02-12 23:52:43 +08:00
module UsersGenerator
# Simply validate the user with the given data,
# and return an array of errors (which is 0-length
# if user is valid)
def validate_user(
full_name,
email,
password
)
2017-01-25 17:24:50 +08:00
nu = User.new(full_name: full_name,
initials: get_user_initials(full_name),
email: email,
password: password)
2016-02-12 23:52:43 +08:00
nu.validate
nu.errors
end
# If confirmed == true, the user is automatically confirmed;
# otherwise, SciNote sends the "confirmation" email to the user
2017-01-25 17:24:50 +08:00
# If private_team_name == nil, private taem is not created.
def create_user(full_name,
email,
password,
confirmed,
private_team_name,
team_ids,
options = {})
nu = User.new({ full_name: full_name,
initials: get_user_initials(full_name),
email: email,
password: password,
password_confirmation: password }.merge(options))
2017-01-25 17:24:50 +08:00
nu.confirmed_at = Time.now if confirmed
2016-07-21 19:11:15 +08:00
nu.save!
2016-02-12 23:52:43 +08:00
# TODO: If user is not confirmed, maybe additional email
# needs to be sent with his/her password & email?
2017-01-25 17:24:50 +08:00
# Create user's own team of needed
if private_team_name.present?
create_private_user_team(nu, private_team_name)
2016-02-12 23:52:43 +08:00
end
2017-01-25 17:24:50 +08:00
# Assign user to additional teams
team_ids.each do |team_id|
team = Team.find_by_id(team_id)
UserTeam.create(user: nu, team: team, role: :admin) if team.present?
2016-02-12 23:52:43 +08:00
end
2017-01-25 17:24:50 +08:00
# Assign user team as user current team
2021-07-23 17:56:28 +08:00
nu.current_team_id = nu.teams.first.id unless nu.teams.blank?
2016-10-13 16:12:11 +08:00
nu.save!
2016-02-12 23:52:43 +08:00
nu.reload
2017-01-25 17:24:50 +08:00
nu
2016-02-12 23:52:43 +08:00
end
2017-01-25 17:24:50 +08:00
def create_private_user_team(user, private_team_name)
no = Team.create(name: private_team_name, created_by: user)
UserTeam.create(user: user, team: no, role: :admin)
2016-02-12 23:52:43 +08:00
end
def print_user(user, password)
puts "USER ##{user.id}"
puts " Full name: #{user.full_name}"
puts " Initials: #{user.initials}"
puts " Email: #{user.email}"
puts " Password: #{password}"
puts " Confirmed at: #{user.confirmed_at}"
2017-01-25 17:24:50 +08:00
teams = user.teams.collect(&:name).join(', ')
puts " Member of teams: #{teams}"
2016-02-12 23:52:43 +08:00
end
def generate_user_password
require 'securerandom'
SecureRandom.hex(5)
end
def get_user_initials(full_name)
2017-01-25 17:24:50 +08:00
full_name.split(' ').collect { |n| n.capitalize[0] }.join[0..3]
2016-02-12 23:52:43 +08:00
end
2016-10-13 16:12:11 +08:00
end