Module: Sinatra::Helpers

Defined in:
lib/sinatra-authentication.rb

Instance Method Summary collapse

Instance Method Details

#current_userObject



160
161
162
163
164
165
166
# File 'lib/sinatra-authentication.rb', line 160

def current_user
  if session[:user]
    User.get(:id => session[:user])
  else
    GuestUser.new
  end
end

#get_view_as_string(filename) ⇒ Object

BECAUSE sinatra 9.1.1 can’t load views from different paths properly



177
178
179
180
181
182
183
184
185
# File 'lib/sinatra-authentication.rb', line 177

def get_view_as_string(filename)
  view = options.sinatra_authentication_view_path + filename
  data = ""
  f = File.open(view, "r")
  f.each_line do |line|
    data += line
  end
  return data
end

#logged_in?Boolean

Returns:

  • (Boolean)


168
169
170
# File 'lib/sinatra-authentication.rb', line 168

def logged_in?
  !!session[:user]
end

#login_requiredObject



149
150
151
152
153
154
155
156
157
158
# File 'lib/sinatra-authentication.rb', line 149

def 
  #not as efficient as checking the session. but this inits the fb_user if they are logged in
  if current_user.class != GuestUser
    return true
  else
    session[:return_to] = request.fullpath
    redirect '/login'
    return false
  end
end

#render_login_logout(html_attributes = {:class => ""}) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/sinatra-authentication.rb', line 187

def (html_attributes = {:class => ""})
css_classes = html_attributes.delete(:class)
parameters = ''
html_attributes.each_pair do |attribute, value|
  parameters += "#{attribute}=\"#{value}\" "
end

  result = "<div id='sinatra-authentication-login-logout' >"
  if logged_in?
    logout_parameters = html_attributes
    # a tad janky?
    logout_parameters.delete(:rel)
    result += "<a href='/users/#{current_user.id}/edit' class='#{css_classes} sinatra-authentication-edit' #{parameters}>Edit account</a> "
    result += "<a href='/logout' class='#{css_classes} sinatra-authentication-logout' #{logout_parameters}>Logout</a>"
  else
    result += "<a href='/signup' class='#{css_classes} sinatra-authentication-signup' #{parameters}>Signup</a> "
    result += "<a href='/login' class='#{css_classes} sinatra-authentication-login' #{parameters}>Login</a>"
  end

  result += "</div>"
end

#use_layout?Boolean

Returns:

  • (Boolean)


172
173
174
# File 'lib/sinatra-authentication.rb', line 172

def use_layout?
  !request.xhr?
end