-
Notifications
You must be signed in to change notification settings - Fork 1
/
ember-simple-auth.rb
237 lines (191 loc) · 6.66 KB
/
ember-simple-auth.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
Dir[File.join(File.dirname(__FILE__), 'utils/*.rb')].each {|file| require file }
# rails new APP_PATH -m=https://raw.github.com/bazzel/rails-templates/master/ember-simple-auth.rb
# bundle exec rake rails:template LOCATION=https://raw.github.com/bazzel/rails-templates/master/ember-simple-auth.rb
#
# Tested with:
# Rails 4.0.2
# Ember 1.4.0-beta.5
# Ember Data 1.0.0-beta.6
# Ember SimpleAuth 0.1.1
#
# This template:
# - sets up Ember SimpleAuth as described on the site
# - sets up simple authentication inspired by RailsCast #250 and reviewed by Marco Otte-Witte
# - Shows an error message when authentication fails with a X to close the message
# -
# -
#
puts <<-CODE
== Rails template for setting up authentication with Ember.SimpleAuth ================================
-- see: http://emberjs.com and http://ember-simple-auth.simplabs.com for more info
If you haven\'t set up Ember.js in Rails yet, you can do this by running the following template:
bundle exec rake rails:template LOCATION=https://raw.github.com/bazzel/rails-templates/master/ember.rb
CODE
# Declare and install gems
#
bundle_install do
gem 'bcrypt-ruby', '~> 3.1.2'
end
#
# End Declare and install gems
script_name = 'ember-simple-auth'
script_file_name = "#{script_name}.js"
tmp_folder = Pathname.new("/tmp/#{script_name}")
# Sample user credentials:
username = 'ember'
password = 'password'
# Build and use ember-simple-auth
# (See also https://github.com/simplabs/ember-simple-auth#building):
#
run "git clone https://github.com/simplabs/ember-simple-auth.git #{tmp_folder}"
inside(tmp_folder) do
Bundler.with_clean_env do
run 'bundle install'
run 'bundle exec rake dist' # `rake 'dist'` throws an error...
end
copy_file tmp_folder.join('dist', script_file_name), vendor_js.join(script_file_name)
end
remove_dir(tmp_folder)
#
# End Build and use ember-simple-auth
# Setup Ember
#
inject_into_file app_js.join('application.js.coffee'), after: "#= require ember\n" do
"#= require #{script_name}\n"
end
# Enable Ember.SimpleAuth in a custom initializer first:
file app_js.join('initializers/simple_auth.js.coffee'), <<-CODE
Ember.Application.initializer
name: 'authentication',
initialize: (container, application) ->
Ember.SimpleAuth.setup(application)
CODE
# then implement the respective mixin in the application route:
file app_js.join('routes/application_route.js.coffee'), <<-CODE
App.ApplicationRoute = Ember.Route.extend Ember.SimpleAuth.ApplicationRouteMixin
CODE
# Render login/logout buttons in the template:
prepend_file app_js.join('templates/application.handlebars'), <<-CODE
{{#if session.isAuthenticated}}
<a {{action 'invalidateSession'}}>Logout</a>
{{else}}
{{#link-to 'login'}}Login{{/link-to}}
{{/if}}
CODE
# Setup the route for the login form...
inject_into_file app_js.join('router.js.coffee'), after: /^App\.Router\.map.*\n/ do
" @route 'login'\n"
end
# ...and implement the Ember.SimpleAuth mixin in the login controller:
file app_js.join('controllers', 'login_controller.js.coffee'), <<-CODE
App.LoginController = Ember.Controller.extend Ember.SimpleAuth.LoginControllerMixin,
actions:
sessionAuthenticationFailed: (error) ->
msg = JSON.parse(error).error
@set('errorMessage', msg)
closeMessage: ->
@set('errorMessage', null)
reset: ->
@setProperties
errorMessage: null
identification: null
password: null
CODE
file app_js.join('routes', 'login_route.js.coffee'), <<-CODE
App.LoginRoute = Ember.Route.extend
setupController: (controller, model) ->
controller.reset()
CODE
# Render the login form:
file app_js.join('templates/login.handlebars'), <<-CODE
{{#if errorMessage}}
<div data-alert class='alert alert-box radius'>
{{errorMessage}}
<a {{action 'closeMessage'}} class='close'>x</a>
</div>
{{/if}}
<form {{action 'authenticate' on='submit'}}>
<label for='identification'>Login</label>
{{input id='identification' placeholder='Enter Login' value=identification}}
<label for='password'>Password</label>
{{input id='password' placeholder='Enter Password' type='password' value=password}}
<button type='submit'>Login</button>
</form>
CODE
#
# Setup Ember
# Set up Rails
#
# User model
#
generate(:resource, 'user', 'username', 'password_digest', 'token')
remove_file app_js.join('models/user.js.coffee')
inject_into_file 'app/models/user.rb', after: "class User < ActiveRecord::Base\n" do
" has_secure_password\n"
end
# Add `authenticate` to ApplicationController
#
application_controller = Rails.root.join('app', 'controllers', 'application_controller.rb')
# Do we need a `private` method?
application_controller.each_line do |line|
next if line =~ /private/
inject_into_file 'app/controllers/application_controller.rb', before: /^end/ do
"\nprivate\n"
end
end
inject_into_file application_controller, after: /^\s*private\s*\n/ do
<<-CODE
def authenticate
head :unauthorized and return unless current_user
end
def current_user
@current_user ||= access_token && User.find_by_token(access_token)
end
def access_token
@access_token ||= request.authorization && request.authorization.split(' ').last
end
CODE
end
#
# End Add `authenticate` to ApplicationController
file 'app/controllers/sessions_controller.rb', <<-CODE
class SessionsController < ApplicationController
def create
user = User.find_by_username(params[:username])
if user && user.authenticate(params[:password])
user.token = SecureRandom.hex
user.save!
render json: { access_token: user.token, token_type: 'bearer' }
else
render json: {error: "Email or password is invalid"}, status: :unauthorized
end
end
end
CODE
route 'post :token, to: \'sessions#create\''
append_file 'db/seeds.rb', <<-CODE
User.destroy_all
User.create! username: '#{username}', password: '#{password}', password_confirmation: '#{password}'
CODE
rake 'db:migrate'
rake 'db:seed'
puts <<-CODE
*********************************************************************
Congratulations! Ember.SimpleAuth has been added to your Rails project.
Now you can make routes protected by simply implementing the mixin:
App.Router.map ->
@route 'posts'
App.PostsRoute = Ember.Route.extend Ember.SimpleAuth.AuthenticatedRouteMixin,
model: ->
@store.find 'post'
Add the following code to your (Rails) controllers to authenticate the user:
class ProtectedController < ApplicationController
before_action :authenticate
...
end
A sample user with username `#{username}` and password `#{password}` was created.
More Resources:
* http://ember-simple-auth.simplabs.com
* http://railscasts.com/episodes/250-authentication-from-scratch or
http://railscasts.com/episodes/250-authentication-from-scratch-revised
CODE