Today I refactored some of the code in my todo-mvc-lv-code-along repo.
If you checkout my code on Github, you will find that I updated the sessions controller.
The sessions controller now uses a method I created inside of the users model to iterate through the github omniauth.auth hash and add/find/update data in my database.
def create
if auth_hash = request.env["omniauth.auth"]
user = User.find_or_create_by_omniauth(auth_hash)
session[:user_id] = user.id
redirect_to lists_path
else
#normal log in
@user = User.find_by(username: params[:username])
#cookies[:username] = @user.email
if @user && @user.authenticate(params[:password])
# session[:user_id]
log_in(@user)
flash[:sucess] = "Welcome, #{@user.username}"
redirect_to lists_path
else
flash[:danger] = "Improper credentials given"
redirect_to login_path
end
end
end
def self.find_or_create_by_omniauth(auth_hash)
oauth_username = auth_hash["info"]["nickname"]
self.where(username: oauth_username).first_or_create do |user|
user.password = SecureRandom.hex
end
end
Refactoring is important when using MVC because you want to make sure that your controller is not updating or adding things to your database, that job is for the your models. As I learn I am getting a better understanding of the importance of refactoring and hopefully will be able to do it with my eyes closed.
Until then, thanks for reading!
Sincerely,
Brittany
Top comments (0)