-
-
Save natekandler/8cb463de66413e5760b4 to your computer and use it in GitHub Desktop.
login and authenticate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#if using has_secure_password in model | |
#use password_digest and confirm_password in migration | |
#otherwise password_hash in migration | |
#CONTOLLER | |
get '/' do | |
# Look in app/views/index.erb | |
erb :index | |
end | |
post '/' do | |
if User.authenticate(params[:username], params[:password]) | |
@user = User.find_by_username(params[:username]) | |
session[:user_id] = @user.id #creates session | |
redirect "/user/#{current_user.id}" | |
else | |
redirect '/' | |
end | |
end | |
#MODEL | |
class User < ActiveRecord::Base | |
def password | |
@password ||= BCrypt::Password.new(password_hash) | |
end | |
def password=(pass) | |
@entered_password = pass | |
@password = BCrypt::Password.create(pass) | |
self.password_hash = @password | |
end | |
def self.authenticate(email, password) | |
user = User.find_by_email(email) | |
return user if user && (user.password == password) | |
nil # either invalid email or wrong password | |
end | |
end | |
#INDEX VIEW | |
<div class="container"> | |
<div id="sign_in"> | |
<h1>Sign in</h1> | |
<form method="post" action="/"> | |
<div class="username"> | |
<label>username</label></br> | |
<input type="text" name="username"> | |
</div> | |
<div class="password"> | |
<label>password</label></br> | |
<input type="password" name="password"> | |
</div> | |
<div class="submit"> | |
<input type="submit" value="Submit" class="submit_button"> | |
</div> | |
<h2>or</h2> | |
<div id="create"> | |
<a href="/user/new">Create Account</a> | |
</div> | |
</form> | |
</div> | |
</div> | |
#CREATE ACCOUNT VIEW | |
<div class="container"> | |
<div id="create_account"> | |
<h1>Create account</h1> | |
<form method="post" action="/create_account"> | |
<div class="username"> | |
<label>username</label></br> | |
<input type="text" name="user[username]"> | |
</div> | |
<div class="password" | |
<label>password</label></br> | |
<input type="password" name="user[password]"> | |
</div> | |
<div class="submit"> | |
<input type="submit" value="Create" class="submit_button"> | |
</div> | |
</form> | |
</div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome! Thanks, Nate!
This is a nice helper method to consider including in a helper file.
Other things I'm throwing on here so that all Bcrypt-esque items are in one place...don't forget to:
require 'bcrypt'
in your environment (or in the User model, above/outside of class User)gem 'bcrypt'
)bundle
after you've made sure to include the bcrypt gem in your gemfile...in addition to calling
include BCrypt
inside of your User model