Skip to content

Instantly share code, notes, and snippets.

View kelhusseiny's full-sized avatar
🤡
How about another joke, Murray?

Karim El-Husseiny kelhusseiny

🤡
How about another joke, Murray?
View GitHub Profile
$ rails new User_Auth -d mysql
$ rails cd ./User_Auth
$ rails g model user
$ rails g controller users new
class User < ActiveRecord::Base
attr_accessor :password
EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :confirmation => true #password_confirmation attr
validates_length_of :password, :in => 6..20, :on => :create
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :encrypted_password
t.string :salt
t.timestamps
end
end
<% @page_title = "UserAuth | Signup" %>
<div class="Sign_Form">
<h1>Sign Up</h1>
<%= form_for(:user, :url => {:controller => 'users', :action => 'create'}) do |f| %>
<p> Username:</br> <%= f.text_field :username%> </p>
<p> Email:</br> <%= f.text_field :email%> </p>
<p> Password:</br> <%= f.password_field :password%></p>
<p> Password Confirmation:</br> <%= f.password_field :password_confirmation%> </p>
<%= f.submit :Signup %>
<% end %>
def self.authenticate(username_or_email="", login_password="")
if EMAIL_REGEX.match(username_or_email)
user = User.find_by_email(username_or_email)
else
user = User.find_by_username(username_or_email)
end
if user && user.match_password(login_password)
return user
else
return false
<% @page_title = "UserAuth | Login" -%>
<div class= "Sign_Form">
<h1>Log in</h1>
<%= form_tag(:action => 'login_attempt') do %>
<p>Username or Email:</br> <%= text_field_tag(:username_or_email) %></p>
<p>Password:</br> <%= password_field_tag :login_password %></p>
<%= submit_tag("Log In") %>
<% end %>
</div>
$ bundle install
before_save :encrypt_password
after_save :clear_password
def encrypt_password
if password.present?
self.salt = BCrypt::Engine.generate_salt
self.encrypted_password= BCrypt::Engine.hash_secret(password, salt)
end
end
def clear_password
self.password = nil
$ rails g controller sessions login, home, profile, setting