From 425e7f5fc5644f3a6db4fdaf2cbeb9f96edf8874 Mon Sep 17 00:00:00 2001 From: jcwimer Date: Thu, 28 Apr 2016 01:13:58 +0000 Subject: [PATCH] Frontend authentication working. --- app/controllers/application_controller.rb | 13 +++++ app/views/api/tournament.jbuilder | 10 ++-- app/views/layouts/_cdn.html.erb | 2 +- config/application.rb | 4 ++ frontend/app/js/app.js | 2 +- .../app/js/controllers/login-controller.js | 51 +++++++++++++++++++ .../js/controllers/tournament-controller.js | 39 +++++++++++++- frontend/app/js/models/wrestler.js | 9 ++-- frontend/app/js/routes.js | 2 +- frontend/app/js/services/auth-service.js | 49 ------------------ .../app/js/services/tournaments-service.js | 4 +- frontend/app/pages/index.us | 33 +++++++++--- frontend/app/pages/static_pages/home.html | 2 +- .../pages/tournaments/tournaments-search.html | 2 +- .../pages/tournaments/tournaments-show.html | 27 ++++++---- frontend/config/application.js | 3 +- frontend/vendor/js/devise-min.js | 10 ++++ test/integration/single_test_test.rb | 2 +- 18 files changed, 175 insertions(+), 89 deletions(-) create mode 100644 frontend/app/js/controllers/login-controller.js delete mode 100644 frontend/app/js/services/auth-service.js create mode 100644 frontend/vendor/js/devise-min.js diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 5540030..a9f6dc6 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -3,8 +3,21 @@ class ApplicationController < ActionController::Base # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception + after_filter :set_csrf_cookie_for_ng + + def set_csrf_cookie_for_ng + cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery? + end + rescue_from CanCan::AccessDenied do |exception| # flash[:error] = "Access denied!" redirect_to '/static_pages/not_allowed' end + + protected + + # In Rails 4.2 and above + def verified_request? + super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN']) + end end diff --git a/app/views/api/tournament.jbuilder b/app/views/api/tournament.jbuilder index 3241efb..09fe7aa 100644 --- a/app/views/api/tournament.jbuilder +++ b/app/views/api/tournament.jbuilder @@ -1,7 +1,7 @@ json.cache! ["api_tournament", @tournament] do json.content(@tournament) - json.(@tournament, :id, :name, :address, :director, :director_email, :tournament_type, :created_at, :updated_at) + json.(@tournament, :id, :name, :address, :director, :director_email, :tournament_type, :created_at, :updated_at, :user_id) json.schools @tournament.schools do |school| json.name school.name @@ -28,8 +28,6 @@ json.cache! ["api_tournament", @tournament] do json.mats @tournament.mats do |mat| json.name mat.name json.unfinishedMatches mat.unfinishedMatches do |match| - json.w1 = match.w1 - json.w2 = match.w2 json.bout_number match.bout_number json.w1_name match.w1_name json.w2_name match.w2_name @@ -42,8 +40,6 @@ json.cache! ["api_tournament", @tournament] do json.w2_name match.w2_name json.weightClass match.weight.max json.round match.round - json.w1 = match.w1 - json.w2 = match.w2 end json.matches @tournament.matches do |match| @@ -52,7 +48,7 @@ json.cache! ["api_tournament", @tournament] do json.w2_name match.w2_name json.weightClass match.weight.max json.round match.round - json.w1 = match.w1 - json.w2 = match.w2 + json.w1 match.w1 + json.w2 match.w2 end end diff --git a/app/views/layouts/_cdn.html.erb b/app/views/layouts/_cdn.html.erb index 70538f0..f923e78 100644 --- a/app/views/layouts/_cdn.html.erb +++ b/app/views/layouts/_cdn.html.erb @@ -9,7 +9,7 @@ - + diff --git a/config/application.rb b/config/application.rb index d8037e7..786352b 100644 --- a/config/application.rb +++ b/config/application.rb @@ -30,6 +30,10 @@ module Wrestling config.active_job.queue_adapter = :delayed_job config.rails_lineman.lineman_project_location = "frontend" + + config.to_prepare do + DeviseController.respond_to :html, :json + end end diff --git a/frontend/app/js/app.js b/frontend/app/js/app.js index db68ef9..395e7c2 100644 --- a/frontend/app/js/app.js +++ b/frontend/app/js/app.js @@ -1,4 +1,4 @@ -var app = angular.module("wrestlingdev", ["ngRoute"]).run(function($rootScope) { +var app = angular.module("wrestlingdev", ["ngRoute","Devise"]).run(function($rootScope) { // adds some basic utilities to the $rootScope for debugging purposes $rootScope.log = function(thing) { console.log(thing); diff --git a/frontend/app/js/controllers/login-controller.js b/frontend/app/js/controllers/login-controller.js new file mode 100644 index 0000000..c316d8b --- /dev/null +++ b/frontend/app/js/controllers/login-controller.js @@ -0,0 +1,51 @@ +'use strict'; +app.controller("loginController", function($scope, $routeParams, Auth, $rootScope) { + $scope.credentials = { + email: '', + password: '' + }; + + var config = { + headers: { + 'X-HTTP-Method-Override': 'POST' + } + }; + + + $scope.login = function(){ + Auth.login($scope.credentials, config).then(function(user) { + console.log(user); // => {id: 1, ect: '...'} + $rootScope.user = user; + $rootScope.alertClass = "alert alert-success"; + $rootScope.alertMessage = "Logged in successfully"; + }, function(error) { + console.log(error); + $rootScope.alertClass = "alert alert-danger"; + $rootScope.alertMessage = "Username and/or password is incorrect"; + }); + }; + + $scope.logout = function(){ + Auth.logout(config).then(function(oldUser) { + // alert(oldUser.name + "you're signed out now."); + $rootScope.user = null; + $rootScope.alertClass = "alert alert-success"; + $rootScope.alertMessage = "Logged out successfully"; + }, function(error) { + // An error occurred logging out. + $rootScope.alertClass = "alert alert-danger"; + $rootScope.alertMessage = "There was an error logging out"; + }); + }; + + Auth.currentUser().then(function(user) { + // User was logged in, or Devise returned + // previously authenticated session. + $rootScope.user = user; + }, function(error) { + // unauthenticated error + $rootScope.user = null; + }); + + +}); \ No newline at end of file diff --git a/frontend/app/js/controllers/tournament-controller.js b/frontend/app/js/controllers/tournament-controller.js index 8c09a41..21816bd 100644 --- a/frontend/app/js/controllers/tournament-controller.js +++ b/frontend/app/js/controllers/tournament-controller.js @@ -1,7 +1,8 @@ 'use strict'; -app.controller("tournamentController", function($scope, tournamentsService, $routeParams, Wrestler) { +app.controller("tournamentController", function($scope, tournamentsService, $routeParams, Wrestler, Auth, $rootScope) { $scope.message = "Test message in scope."; + // $scope.tournamentData = "test"; tournamentsService.tournamentDetails($routeParams.id).then(function(data) { //this will execute when the @@ -9,7 +10,43 @@ app.controller("tournamentController", function($scope, tournamentsService, $rou $scope.tournament = data; }); + // refresh tournament data every 10 seconds + // setInterval(function(){ + // tournamentsService.tournamentDetails($routeParams.id).then(function(data) { + // //this will execute when the + // //AJAX call completes. + // $scope.tournament = data; + // }); + // }, 10000); + $scope.wrestler = Wrestler; + $scope.showSchools = false; + + $scope.toggleSchools = function(){ + $scope.showSchools = !$scope.showSchools; + }; + + $scope.showWeightSeeds = false; + + $scope.toggleWeightSeeds = function(){ + $scope.showWeightSeeds = !$scope.showWeightSeeds; + }; + + $scope.showBoutBoard = false; + + $scope.toggleBoutBoard = function(){ + $scope.showBoutBoard = !$scope.showBoutBoard; + }; + + $scope.isTournamentOwner = function(tournamentId,userId){ + if(userId == tournamentId){ + return true; + } else { + return false; + } + }; + + }); \ No newline at end of file diff --git a/frontend/app/js/models/wrestler.js b/frontend/app/js/models/wrestler.js index 4f45c5e..30c2c89 100644 --- a/frontend/app/js/models/wrestler.js +++ b/frontend/app/js/models/wrestler.js @@ -4,16 +4,15 @@ app.factory('Wrestler', function Wrestler(){ var vm = this; - vm.matches = function(matches,wrestler){ - var givenWrestler = wrestler; + vm.matches = function(wrestler,matches){ - console.log(givenWrestler.id); + console.log(matches); return _.filter(matches, function(match){ - return match.w1 == givenWrestler.id || match.w2 == givenWrestler.id; + return match.w1 == wrestler.id || match.w2 == wrestler.id; }); - } + }; return vm; }); \ No newline at end of file diff --git a/frontend/app/js/routes.js b/frontend/app/js/routes.js index 2c97620..194d2f6 100644 --- a/frontend/app/js/routes.js +++ b/frontend/app/js/routes.js @@ -40,5 +40,5 @@ app.config(['$routeProvider', '$locationProvider', function($routeProvider,$loca $routeProvider.otherwise({redirectTo: '/'}); //this give me normal routes instead of /#/ - $locationProvider.html5Mode(true); + // $locationProvider.html5Mode(true); }]); \ No newline at end of file diff --git a/frontend/app/js/services/auth-service.js b/frontend/app/js/services/auth-service.js deleted file mode 100644 index db0c7d9..0000000 --- a/frontend/app/js/services/auth-service.js +++ /dev/null @@ -1,49 +0,0 @@ -app.factory('AuthenticationService', - ['Base64', '$http', '$cookieStore', '$rootScope', '$timeout', - function (Base64, $http, $cookieStore, $rootScope, $timeout) { - var service = {}; - - service.Login = function (username, password, callback) { - - /* Dummy authentication for testing, uses $timeout to simulate api call - ----------------------------------------------*/ - // $timeout(function(){ - // var response = { success: username === 'test' && password === 'test' }; - // if(!response.success) { - // response.message = 'Username or password is incorrect'; - // } - // callback(response); - // }, 1000); - - - /* Use this for real authentication - ----------------------------------------------*/ - $http.post('/api/authenticate', { username: username, password: password }) - .success(function (response) { - callback(response); - }); - - }; - - service.SetCredentials = function (username, password) { - var authdata = Base64.encode(username + ':' + password); - - $rootScope.globals = { - currentUser: { - username: username, - authdata: authdata - } - }; - - $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line - $cookieStore.put('globals', $rootScope.globals); - }; - - service.ClearCredentials = function () { - $rootScope.globals = {}; - $cookieStore.remove('globals'); - $http.defaults.headers.common.Authorization = 'Basic '; - }; - - return service; - }]); \ No newline at end of file diff --git a/frontend/app/js/services/tournaments-service.js b/frontend/app/js/services/tournaments-service.js index 0ac1a3f..36d2a02 100644 --- a/frontend/app/js/services/tournaments-service.js +++ b/frontend/app/js/services/tournaments-service.js @@ -37,8 +37,8 @@ function tournamentsService($http){ } function errorCallback(err){ - console.log("error log below"); - console.log(err); + // console.log("error log below"); + // console.log(err); return err; } diff --git a/frontend/app/pages/index.us b/frontend/app/pages/index.us index 8ed5e16..213c950 100644 --- a/frontend/app/pages/index.us +++ b/frontend/app/pages/index.us @@ -1,7 +1,7 @@ - + WrestlingDev @@ -21,13 +21,30 @@ - WrestlingDev + WrestlingDev @@ -35,6 +52,10 @@
+
+ + {{alertMessage}} +
@@ -66,7 +87,7 @@ - + diff --git a/frontend/app/pages/static_pages/home.html b/frontend/app/pages/static_pages/home.html index ff9797e..adea8bd 100644 --- a/frontend/app/pages/static_pages/home.html +++ b/frontend/app/pages/static_pages/home.html @@ -5,6 +5,6 @@

If you would like to run a tournament, please click log in and then click sign up.


-Browse Tournaments +Browse Tournaments

diff --git a/frontend/app/pages/tournaments/tournaments-search.html b/frontend/app/pages/tournaments/tournaments-search.html index 52d8282..4afdaa8 100644 --- a/frontend/app/pages/tournaments/tournaments-search.html +++ b/frontend/app/pages/tournaments/tournaments-search.html @@ -18,7 +18,7 @@ - {{ tournament.name }} + {{ tournament.name }} {{ tournament.date }} diff --git a/frontend/app/pages/tournaments/tournaments-show.html b/frontend/app/pages/tournaments/tournaments-show.html index 071fb0b..957890d 100644 --- a/frontend/app/pages/tournaments/tournaments-show.html +++ b/frontend/app/pages/tournaments/tournaments-show.html @@ -1,9 +1,8 @@ - Back to browse tournaments + Back to browse tournaments

{{ tournament.name }}

-

{{ wrestler.matches(tournament.matches,tournament.weights[0].wrestlers[0]) }}

Address: {{ tournament.address }} @@ -22,16 +21,19 @@


- +

School Lineups and Team Scores +

-
+
+ + @@ -40,6 +42,7 @@ +
Name ScoreActions
{{ school.name }} {{ school.score }}
@@ -48,10 +51,11 @@
- +

Weights and Seeds +

-
+

Click weight class for seeds


@@ -75,10 +79,11 @@
- +

Mats and Bout Board +

-
+
diff --git a/frontend/config/application.js b/frontend/config/application.js index 88b807f..6a7ddf8 100644 --- a/frontend/config/application.js +++ b/frontend/config/application.js @@ -26,8 +26,7 @@ module.exports = function(lineman) { apiProxy: { enabled: true, host: 'localhost', - port: 8080, - prefix: 'api' + port: 8080 }, web: { port: 8081 diff --git a/frontend/vendor/js/devise-min.js b/frontend/vendor/js/devise-min.js new file mode 100644 index 0000000..97a577f --- /dev/null +++ b/frontend/vendor/js/devise-min.js @@ -0,0 +1,10 @@ +// AngularDevise +// ------------------- +// v1.2.1 +// +// Copyright (c)2016 Justin Ridgewell +// Distributed under MIT license +// +// https://github.com/cloudspace/angular_devise + +!function(a){"use strict";var b=a.module("Devise",[]);b.provider("AuthIntercept",function(){var a=!1;this.interceptAuth=function(b){return a=!!b||void 0===b,this},this.$get=["$rootScope","$q",function(b,c){return{responseError:function(d){var e=d.config.interceptAuth;if(e=!!e||a&&void 0===e,e&&401===d.status){var f=c.defer();return b.$broadcast("devise:unauthorized",d,f),f.reject(d),f.promise}return c.reject(d)}}}]}).config(["$httpProvider",function(a){a.interceptors.push("AuthIntercept")}]),b.provider("Auth",function(){function b(b,c,d){var h={method:f[b].toLowerCase(),url:e[b]};return c&&(g?(h.data={},h.data[g]=c):h.data=c),a.extend(h,d),h}function c(b,c){a.forEach(b,function(a,d){this[d+c]=function(a){return void 0===a?b[d]:(b[d]=a,this)}},this)}function d(a){return function(){return a}}var e={login:"/users/sign_in.json",logout:"/users/sign_out.json",register:"/users.json",sendResetPasswordInstructions:"/users/password.json",resetPassword:"/users/password.json"},f={login:"POST",logout:"DELETE",register:"POST",sendResetPasswordInstructions:"POST",resetPassword:"PUT"},g="user",h=function(a){return a.data};c.call(this,f,"Method"),c.call(this,e,"Path"),this.resourceName=function(a){return void 0===a?g:(g=a,this)},this.parse=function(a){return"function"!=typeof a?h:(h=a,this)},this.$get=["$q","$http","$rootScope",function(a,c,e){function f(a){return j._currentUser=a,a}function g(){f(null),j._promise=null}function i(a){return function(b){return e.$broadcast("devise:"+a,b),b}}var j={_currentUser:null,parse:h,_promise:null,reset:function(){g(),j.currentUser()},login:function(a,d){var e=arguments.length>0,g=j.isAuthenticated();return a=a||{},c(b("login",a,d)).then(j.parse).then(f).then(function(a){return e&&!g?i("new-session")(a):a}).then(i("login"))},logout:function(a){var e=d(j._currentUser);return c(b("logout",void 0,a)).then(g).then(e).then(i("logout"))},register:function(a,d){return a=a||{},c(b("register",a,d)).then(j.parse).then(f).then(i("new-registration"))},sendResetPasswordInstructions:function(a){return a=a||{},c(b("sendResetPasswordInstructions",a)).then(j.parse).then(i("send-reset-password-instructions-successfully"))},resetPassword:function(a){return a=a||{},c(b("resetPassword",a)).then(j.parse).then(f).then(i("reset-password-successfully"))},currentUser:function(){return j.isAuthenticated()?a.when(j._currentUser):(null===j._promise&&(j._promise=j.login()),j._promise)},isAuthenticated:function(){return!!j._currentUser}};return j}]})}(angular); \ No newline at end of file diff --git a/test/integration/single_test_test.rb b/test/integration/single_test_test.rb index af56bca..32a5519 100644 --- a/test/integration/single_test_test.rb +++ b/test/integration/single_test_test.rb @@ -37,11 +37,11 @@ class SingleTestTest < ActionDispatch::IntegrationTest # Yml for wrestlers # @tournament.wrestlers.each do |w| # puts "tournament_1_#{w.name}:" - # puts " id: #{count}" # puts " name: #{w.name}" # puts " school_id: #{w.school_id}" # puts " weight_id: #{w.weight_id}" # puts " original_seed: #{w.original_seed}" + # puts " seed: #{w.seed}" # puts " season_loss: #{w.season_loss}" # puts " season_win: #{w.season_win}" # puts " criteria: #{w.criteria}"