Merge pull request #31 from ZeusWPI/oauth

Oauth
This commit is contained in:
benji 2015-03-20 04:56:47 +01:00
commit c4cee1aac0
28 changed files with 171 additions and 119 deletions

View file

@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/

View file

@ -0,0 +1,3 @@
// Place all the styles related to the user_avatar controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

View file

@ -2,7 +2,6 @@ class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception. # Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead. # For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from CanCan::AccessDenied do |exception| rescue_from CanCan::AccessDenied do |exception|
redirect_to root_path, flash: { error: exception.message } redirect_to root_path, flash: { error: exception.message }
@ -15,17 +14,4 @@ class ApplicationController < ActionController::Base
def after_sign_up_path_for(resource) def after_sign_up_path_for(resource)
root_path root_path
end end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(
:nickname, :password, :password_confirmation,
:avatar
) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(
:password, :password_confirmation, :current_password, :avatar
) }
end
end end

View file

@ -1,7 +1,18 @@
class CallbacksController < Devise::OmniauthCallbacksController class CallbacksController < Devise::OmniauthCallbacksController
def zeuswpi def zeuswpi
@user = User.from_omniauth(request.env["omniauth.auth"]) @user = User.from_omniauth(request.env["omniauth.auth"])
@user.save @user.save!(validate: false)
sign_in_and_redirect @user if @user.valid?
flash[:success] = "You are now logged in."
sign_in_and_redirect @user
else
flash[:error] = "Please complete your profile first."
session[:id] = @user.id
redirect_to new_user_avatar_path
end
end
def after_omniauth_failure_path_for(scope)
root_path
end end
end end

View file

@ -37,7 +37,7 @@ class OrdersController < ApplicationController
end end
def overview def overview
@users = User.members.order(:nickname) @users = User.members.order(:uid)
end end
def quickpay def quickpay

View file

@ -0,0 +1,9 @@
class SessionsController < Devise::SessionsController
def new
if session[:id]
redirect_to new_user_avatar_path
return
end
super
end
end

View file

@ -0,0 +1,35 @@
class UserAvatarController < ApplicationController
before_action :authenticate_session_user!
def new
end
def create
if @user.update_attributes(user_params)
flash[:success] = "Your profile is complete. You are now logged in."
sign_in_and_redirect @user
else
render 'new'
end
end
def destroy
reset_session
redirect_to root_path
end
private
def authenticate_session_user!
redirect_to root_path unless session[:id]
@user = User.find_by session[:id]
unless @user
reset_session
redirect_to root_path
end
end
def user_params
params.require(:user).permit(:avatar)
end
end

View file

@ -20,6 +20,19 @@ class UsersController < ApplicationController
.group(:category) .group(:category)
end end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
redirect_to @user, success: "Successfully updated!"
else
render 'edit'
end
end
def index def index
@users = User.members @users = User.members
end end
@ -63,4 +76,8 @@ class UsersController < ApplicationController
@user = User.find(params[:user_id]) @user = User.find(params[:user_id])
redirect_to root_path, error: "You are not authorized to access this page." unless @user == current_user || current_user.admin? redirect_to root_path, error: "You are not authorized to access this page." unless @user == current_user || current_user.admin?
end end
def user_params
params.require(:user).permit(:avatar)
end
end end

View file

@ -0,0 +1,2 @@
module UserAvatarHelper
end

View file

@ -4,10 +4,8 @@
# #
# id :integer not null, primary key # id :integer not null, primary key
# debt_cents :integer default("0"), not null # debt_cents :integer default("0"), not null
# nickname :string
# created_at :datetime # created_at :datetime
# updated_at :datetime # updated_at :datetime
# encrypted_password :string default(""), not null
# remember_created_at :datetime # remember_created_at :datetime
# sign_in_count :integer default("0"), not null # sign_in_count :integer default("0"), not null
# current_sign_in_at :datetime # current_sign_in_at :datetime
@ -24,10 +22,11 @@
# koelkast :boolean default("f") # koelkast :boolean default("f")
# provider :string # provider :string
# uid :string # uid :string
# encrypted_password :string
# #
class User < ActiveRecord::Base class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:zeuswpi] devise :database_authenticatable, :trackable, :omniauthable, :omniauth_providers => [:zeuswpi]
has_paper_trail only: [:debt_cents, :admin, :orders_count, :koelkast] has_paper_trail only: [:debt_cents, :admin, :orders_count, :koelkast]
@ -37,7 +36,6 @@ class User < ActiveRecord::Base
has_many :products, through: :orders has_many :products, through: :orders
belongs_to :dagschotel, class_name: 'Product' belongs_to :dagschotel, class_name: 'Product'
validates :nickname, presence: true, uniqueness: true
validates_attachment :avatar, validates_attachment :avatar,
presence: true, presence: true,
content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] } content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }
@ -45,10 +43,20 @@ class User < ActiveRecord::Base
scope :members, -> { where koelkast: false } scope :members, -> { where koelkast: false }
def self.from_omniauth(auth) def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user| newuser = where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider user.provider = auth.provider
user.uid = auth.uid user.uid = auth.uid
end end
newuser.password = Devise.friendly_token[0,20]
newuser
end
def nickname
self.uid
end
def nickname=(name)
self.uid = name
end end
def debt def debt
@ -65,14 +73,4 @@ class User < ActiveRecord::Base
def to_param def to_param
"#{id} #{nickname}".parameterize "#{id} #{nickname}".parameterize
end end
# This is needed so Devise doesn't try to validate :email
def email_required?
false
end
def email_changed?
false
end
end end

View file

@ -1,15 +0,0 @@
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<%= render 'flash' %>
<%= f_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>
<%= f.error_messages %>
<%= f.password_field :password %>
<%= f.password_field :password_confirmation %>
<%= f.password_field :current_password %>
<%= f.file_field :avatar %>
<%= f.submit "Update" %>
<% end %>

View file

@ -1,16 +0,0 @@
<h2>Sign up</h2>
<%= f_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= f.error_messages %>
<%= f.text_field :nickname %>
<%= f.password_field :password %>
<%= f.password_field :password_confirmation %>
<%= f.file_field :avatar %>
<%= f.submit "Sign up" %>
<% end %>
<%= render "devise/shared/links" %>

View file

@ -1,17 +1,8 @@
<h2>Sign in</h2> <h2>Login</h2>
<%= render partial: 'flash' %> <%= render 'flash' %>
If this is the first time you log in, an account will be created for you.
<div class="sign-in"> <div>
<%= f_form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %> <br />
<%= f.text_field :nickname %> <%= render 'devise/shared/links' %>
<%= f.password_field :password %>
<% if devise_mapping.rememberable? %>
<%= f.check_box :remember_me %>
<% end %>
<%= f.submit "Sign in" %>
<% end %>
</div> </div>
<%= render "devise/shared/links" %>

View file

@ -2,10 +2,6 @@
<%= link_to "Log in", new_session_path(resource_name) %><br /> <%= link_to "Log in", new_session_path(resource_name) %><br />
<% end -%> <% end -%>
<%- if devise_mapping.registerable? && controller_name != 'registrations' %>
<%= link_to "Sign up", new_registration_path(resource_name) %><br />
<% end -%>
<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> <%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %>
<%= link_to "Forgot your password?", new_password_path(resource_name) %><br /> <%= link_to "Forgot your password?", new_password_path(resource_name) %><br />
<% end -%> <% end -%>
@ -20,6 +16,6 @@
<%- if devise_mapping.omniauthable? %> <%- if devise_mapping.omniauthable? %>
<%- resource_class.omniauth_providers.each do |provider| %> <%- resource_class.omniauth_providers.each do |provider| %>
<%= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider) %><br /> <%= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider), class: "btn btn-large btn-primary" %><br />
<% end -%> <% end -%>
<% end -%> <% end -%>

View file

@ -17,9 +17,10 @@
<div class="form-group"> <div class="form-group">
<% if user_signed_in? %> <% if user_signed_in? %>
<%= button_to "Logout", destroy_user_session_path, class: "btn btn-default form-control", method: :delete %> <%= button_to "Logout", destroy_user_session_path, class: "btn btn-default form-control", method: :delete %>
<% elsif session[:id] %>
<%= button_to "Logout", user_avatar_path(session[:id]), class: "btn btn-default form-control", method: :delete %>
<% else %> <% else %>
<%= link_to "Login", new_user_session_path, class: "btn btn-success form-control" %> <%= link_to "Login", new_user_session_path, class: "btn btn-success form-control" %>
<%= link_to "Register", new_user_registration_path, class: "btn btn-default form-control" %>
<% end %> <% end %>
</div> </div>
</div> </div>
@ -50,7 +51,7 @@
<li class="dropdown"> <li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Logged in as <%= current_user.nickname %> <b class="caret"></b></a> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Logged in as <%= current_user.nickname %> <b class="caret"></b></a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li><%= link_to "Edit password", edit_user_registration_path %></li> <li><%= link_to "Edit avatar", edit_user_path(current_user) %></li>
</ul> </ul>
</li> </li>
<% end %> <% end %>
@ -62,7 +63,6 @@
<%= button_to "Logout", destroy_user_session_path, class: "btn btn-default form-control", method: :delete %> <%= button_to "Logout", destroy_user_session_path, class: "btn btn-default form-control", method: :delete %>
<% else %> <% else %>
<%= link_to "Login", new_user_session_path, class: "btn btn-success form-control" %> <%= link_to "Login", new_user_session_path, class: "btn btn-success form-control" %>
<%= link_to "Register", new_user_registration_path, class: "btn btn-default form-control" %>
<% end %> <% end %>
</div> </div>
</div> </div>

View file

@ -0,0 +1,13 @@
<h2>Add avatar to <%= @user.uid %></h2>
<%= render 'flash' %>
<%= f_form_for @user, url: '/user_avatar', method: :post do |f| %>
<%= f.error_messages %>
<!-- To prevent an empty form submit from crashing -->
<%= f.hidden_field :generate_form, value: '1' %>
<%= f.file_field :avatar %>
<%= f.submit "Update" %>
<% end %>

View file

@ -0,0 +1,10 @@
<h2>Edit <%= @user.nickname %></h2>
<%= render 'flash' %>
<%= f_form_for @user do |f| %>
<%= f.error_messages %>
<%= f.file_field :avatar %>
<%= f.submit "Update" %>
<% end %>

View file

@ -4,7 +4,7 @@
<% if current_user == @user %> <% if current_user == @user %>
<h5> <h5>
<%= link_to "[Edit dagschotel]" , user_edit_dagschotel_path(@user) %> <%= link_to "[Edit dagschotel]" , user_edit_dagschotel_path(@user) %>
<%= link_to "[Edit profile]" , edit_user_registration_path %> <%= link_to "[Edit profile]" , edit_user_path(@user) %>
</h5> </h5>
<% end %> <% end %>
<h2><%= @user.nickname %></h2> <h2><%= @user.nickname %></h2>

View file

@ -0,0 +1 @@
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE

View file

@ -12,7 +12,7 @@ module OmniAuth
# This is where you pass the options you would pass when # This is where you pass the options you would pass when
# initializing your consumer from the OAuth gem. # initializing your consumer from the OAuth gem.
option :client_options, { option :client_options, {
site: "http://kelder.zeus.ugent.be", site: "https://kelder.zeus.ugent.be",
authorize_url: "/oauth/oauth2/authorize/", authorize_url: "/oauth/oauth2/authorize/",
token_url: "/oauth/oauth2/token/", token_url: "/oauth/oauth2/token/",
} }

View file

@ -1,9 +1,12 @@
Rails.application.routes.draw do Rails.application.routes.draw do
devise_for :users, controllers: { omniauth_callbacks: "callbacks" } devise_for :users, controllers: {
omniauth_callbacks: "callbacks",
sessions: "sessions"
}
devise_scope :user do devise_scope :user do
unauthenticated :user do unauthenticated :user do
root to: 'devise/sessions#new' root to: 'sessions#new'
end end
authenticated :user, ->(u) { u.koelkast? } do authenticated :user, ->(u) { u.koelkast? } do
@ -22,6 +25,8 @@ Rails.application.routes.draw do
get 'dagschotel/:product_id' => 'users#update_dagschotel', as: 'dagschotel' get 'dagschotel/:product_id' => 'users#update_dagschotel', as: 'dagschotel'
end end
resources :user_avatar
resources :products do resources :products do
collection do collection do
get 'stock' => 'products#stock', as: 'stock' get 'stock' => 'products#stock', as: 'stock'

View file

@ -12,8 +12,8 @@
development: development:
secret_key_base: 5d40610321e19e4f71ee2ba8af4f426fe15096c405da3800c6b33bed6779f2d11f55a0edc455974b19a01fd71f6cd508dba980305dbc55ff82521a2d12f891d8 secret_key_base: 5d40610321e19e4f71ee2ba8af4f426fe15096c405da3800c6b33bed6779f2d11f55a0edc455974b19a01fd71f6cd508dba980305dbc55ff82521a2d12f891d8
omniauth_client_id: "client_id" omniauth_client_id: tomtest
omniauth_client_secret: "client_secret" omniauth_client_secret: blargh
test: test:
secret_key_base: 961437e28e7d6055ffaad9cf1f8d614354f57f10cb2d7601c9d6ede72a03b9c9535ad9e63507e3eb31252c4895970a63117493408f2e9a46c7a0c4a5a7836b81 secret_key_base: 961437e28e7d6055ffaad9cf1f8d614354f57f10cb2d7601c9d6ede72a03b9c9535ad9e63507e3eb31252c4895970a63117493408f2e9a46c7a0c4a5a7836b81
@ -24,4 +24,3 @@ production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
omniauth_client_id: "" omniauth_client_id: ""
omniauth_client_secret: "" omniauth_client_secret: ""

View file

@ -0,0 +1,5 @@
class RemoveFieldsFromUsers < ActiveRecord::Migration
def change
remove_column :users, :nickname, :string
end
end

View file

@ -11,7 +11,7 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20150319154236) do ActiveRecord::Schema.define(version: 20150320001338) do
create_table "order_items", force: :cascade do |t| create_table "order_items", force: :cascade do |t|
t.integer "order_id" t.integer "order_id"
@ -45,10 +45,8 @@ ActiveRecord::Schema.define(version: 20150319154236) do
create_table "users", force: :cascade do |t| create_table "users", force: :cascade do |t|
t.integer "debt_cents", default: 0, null: false t.integer "debt_cents", default: 0, null: false
t.string "nickname"
t.datetime "created_at" t.datetime "created_at"
t.datetime "updated_at" t.datetime "updated_at"
t.string "encrypted_password", default: "", null: false
t.datetime "remember_created_at" t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at" t.datetime "current_sign_in_at"
@ -65,6 +63,7 @@ ActiveRecord::Schema.define(version: 20150319154236) do
t.boolean "koelkast", default: false t.boolean "koelkast", default: false
t.string "provider" t.string "provider"
t.string "uid" t.string "uid"
t.string "encrypted_password"
end end
add_index "users", ["koelkast"], name: "index_users_on_koelkast" add_index "users", ["koelkast"], name: "index_users_on_koelkast"

View file

@ -37,37 +37,38 @@ end
users = [ users = [
{ {
nickname: 'admin', uid: 'admin',
avatar: File.new('public/seeds/users/admin.jpg', 'r'), avatar: File.new('public/seeds/users/admin.jpg', 'r'),
admin: true admin: true
}, },
{ {
nickname: 'koelkast', uid: 'koelkast',
avatar: File.new('public/seeds/users/admin.jpg', 'r'), avatar: File.new('public/seeds/users/admin.jpg', 'r'),
koelkast: true koelkast: true
}, },
{ {
nickname: 'benji', uid: 'benji',
avatar: File.new('public/seeds/users/benji.jpg', 'r'), avatar: File.new('public/seeds/users/benji.jpg', 'r'),
dagschotel: Product.first dagschotel: Product.first,
provider: 'zeuswpi'
}, },
{ {
nickname: 'don', uid: 'don',
avatar: File.new('public/seeds/users/don.jpg', 'r') avatar: File.new('public/seeds/users/don.jpg', 'r')
}, },
{ {
nickname: 'silox', uid: 'silox',
avatar: File.new('public/seeds/users/silox.jpg', 'r') avatar: File.new('public/seeds/users/silox.jpg', 'r')
} }
] ]
users.each do |attr| users.each do |attr|
User.create( User.create(
nickname: attr[:nickname], uid: attr[:uid],
provider: attr[:provider],
avatar: attr[:avatar], avatar: attr[:avatar],
dagschotel: attr[:dagschotel], dagschotel: attr[:dagschotel],
password: DEFAULT_PASSWORD, password: DEFAULT_PASSWORD,
password_confirmation: DEFAULT_PASSWORD,
admin: attr[:admin] || false, admin: attr[:admin] || false,
koelkast: attr[:koelkast] || false koelkast: attr[:koelkast] || false
) )
@ -75,9 +76,8 @@ end
50.times do |i| 50.times do |i|
User.create( User.create(
nickname: "testUser#{i}", uid: "testUser#{i}",
avatar: users[0][:avatar], avatar: users[0][:avatar],
password: DEFAULT_PASSWORD, password: DEFAULT_PASSWORD,
password_confirmation: DEFAULT_PASSWORD
) )
end end

View file

@ -0,0 +1,7 @@
require 'test_helper'
class UserAvatarControllerTest < ActionController::TestCase
# test "the truth" do
# assert true
# end
end

View file

@ -4,10 +4,8 @@
# #
# id :integer not null, primary key # id :integer not null, primary key
# debt_cents :integer default("0"), not null # debt_cents :integer default("0"), not null
# nickname :string
# created_at :datetime # created_at :datetime
# updated_at :datetime # updated_at :datetime
# encrypted_password :string default(""), not null
# remember_created_at :datetime # remember_created_at :datetime
# sign_in_count :integer default("0"), not null # sign_in_count :integer default("0"), not null
# current_sign_in_at :datetime # current_sign_in_at :datetime
@ -24,21 +22,22 @@
# koelkast :boolean default("f") # koelkast :boolean default("f")
# provider :string # provider :string
# uid :string # uid :string
# encrypted_password :string
# #
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html # Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
benji: benji:
nickname: benji uid: benji
dagschotel_id: 1 dagschotel_id: 1
iasoon: iasoon:
nickname: iasoon uid: iasoon
admin: admin:
nickname: admin uid: admin
admin: 1 admin: 1
koelkast: koelkast:
nickname: koelkast uid: koelkast
koelkast: 1 koelkast: 1

View file

@ -4,10 +4,8 @@
# #
# id :integer not null, primary key # id :integer not null, primary key
# debt_cents :integer default("0"), not null # debt_cents :integer default("0"), not null
# nickname :string
# created_at :datetime # created_at :datetime
# updated_at :datetime # updated_at :datetime
# encrypted_password :string default(""), not null
# remember_created_at :datetime # remember_created_at :datetime
# sign_in_count :integer default("0"), not null # sign_in_count :integer default("0"), not null
# current_sign_in_at :datetime # current_sign_in_at :datetime
@ -24,6 +22,7 @@
# koelkast :boolean default("f") # koelkast :boolean default("f")
# provider :string # provider :string
# uid :string # uid :string
# encrypted_password :string
# #
require 'test_helper' require 'test_helper'
@ -46,9 +45,4 @@ class UserTest < ActiveSupport::TestCase
test "to_param" do test "to_param" do
assert_equal @user.to_param, "#{@user.id}-benji" assert_equal @user.to_param, "#{@user.id}-benji"
end end
test "devise validatable methods" do
assert_not @user.email_required?
assert_not @user.email_changed?
end
end end