Skip to content

Commit

Permalink
implemented JWT oauth using the github provider.
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexanderCleasby committed Sep 1, 2019
1 parent c71a02c commit 6daf0f0
Show file tree
Hide file tree
Showing 29 changed files with 449 additions and 16 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@
# Ignore master key for decrypting credentials and more.
/config/master.key

/.env
.env
8 changes: 7 additions & 1 deletion Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,10 @@ end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'dotenv-rails'
gem 'dotenv-rails'

gem 'faraday', '~> 0.11'

gem 'jwt', '~> 1.5'

gem 'pry'
11 changes: 11 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -60,18 +60,22 @@ GEM
msgpack (~> 1.0)
builder (3.2.3)
byebug (11.0.1)
coderay (1.1.2)
concurrent-ruby (1.1.5)
crass (1.0.4)
dotenv (2.7.5)
dotenv-rails (2.7.5)
dotenv (= 2.7.5)
railties (>= 3.2, < 6.1)
erubi (1.8.0)
faraday (0.15.4)
multipart-post (>= 1.2, < 3)
ffi (1.11.1)
globalid (0.4.2)
activesupport (>= 4.2.0)
i18n (1.6.0)
concurrent-ruby (~> 1.0)
jwt (1.5.6)
listen (3.1.5)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
Expand All @@ -89,9 +93,13 @@ GEM
mini_portile2 (2.4.0)
minitest (5.11.3)
msgpack (1.3.1)
multipart-post (2.1.1)
nio4r (2.5.1)
nokogiri (1.10.4)
mini_portile2 (~> 2.4.0)
pry (0.12.2)
coderay (~> 1.1.0)
method_source (~> 0.9.0)
puma (3.12.1)
rack (2.0.7)
rack-test (1.1.0)
Expand Down Expand Up @@ -155,7 +163,10 @@ DEPENDENCIES
bootsnap (>= 1.4.2)
byebug
dotenv-rails
faraday (~> 0.11)
jwt (~> 1.5)
listen (>= 3.0.5, < 3.2)
pry
puma (~> 3.11)
rails (~> 6.0.0)
spring
Expand Down
2 changes: 2 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

require_relative 'config/application'
require 'fileutils'
require 'dotenv'


namespace :start do
task :development do
Expand Down
16 changes: 15 additions & 1 deletion app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
@@ -1,2 +1,16 @@
class ApplicationController < ActionController::API
end
def current_user
token = params[:token]
payload = TokenEncoder.decode(token)
puts payload
@current_user ||= User.find_by_login(payload[0]['sub'])
end

def logged_in?
current_user != nil
end

def authenticate_user!
head :unauthorized unless logged_in?
end
end
35 changes: 35 additions & 0 deletions app/controllers/authentication_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

require 'pry'

class AuthenticationController < ApplicationController
def github

#binding.pry

authenticator = Authenticator.new
user_info = authenticator.github(params[:code])

login = user_info[:login]
name = user_info[:name]
puts login

# Generate token...
token = TokenEncoder.encode(login)
# ... create user if it doesn't exist...
User.where(login: login).first_or_create!(
name: name,
#avatar_url: avatar_url
)
puts "here: "+token
# ... and redirect to client app.
redirect_to "#{issuer}?token=#{token}"
rescue StandardError => error
redirect_to "#{issuer}?error=#{error.message}"
end

private

def issuer
ENV['CLIENT_URL']
end
end
52 changes: 52 additions & 0 deletions app/controllers/dashboards_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
class DashboardsController < ApplicationController
before_action :authenticate_user!
before_action :set_dashboard, only: [:show, :update, :destroy]

# GET /dashboards
def index
@dashboards = Dashboard.all

render json: @dashboards
end

# GET /dashboards/1
def show
render json: @dashboard
end

# POST /dashboards
def create
@dashboard = Dashboard.new(dashboard_params)

if @dashboard.save
render json: @dashboard, status: :created, location: @dashboard
else
render json: @dashboard.errors, status: :unprocessable_entity
end
end

# PATCH/PUT /dashboards/1
def update
if @dashboard.update(dashboard_params)
render json: @dashboard
else
render json: @dashboard.errors, status: :unprocessable_entity
end
end

# DELETE /dashboards/1
def destroy
@dashboard.destroy
end

private
# Use callbacks to share common setup or constraints between actions.
def set_dashboard
@dashboard = Dashboard.find(params[:id])
end

# Only allow a trusted parameter "white list" through.
def dashboard_params
params.require(:dashboard).permit(:user_id)
end
end
3 changes: 2 additions & 1 deletion app/controllers/test_controller.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
class TestController < ApplicationController
before_action :authenticate_user!
def new

foo = {foo:"bar"}
foo = {foo:current_user}
render :json => foo
end

Expand Down
51 changes: 51 additions & 0 deletions app/controllers/users_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class UsersController < ApplicationController
before_action :set_user, only: [:show, :update, :destroy]

# GET /users
def index
@users = User.all

render json: @users
end

# GET /users/1
def show
render json: @user
end

# POST /users
def create
@user = User.new(user_params)

if @user.save
render json: @user, status: :created, location: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end

# PATCH/PUT /users/1
def update
if @user.update(user_params)
render json: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end

# DELETE /users/1
def destroy
@user.destroy
end

private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end

# Only allow a trusted parameter "white list" through.
def user_params
params.require(:user).permit(:login, :name)
end
end
3 changes: 3 additions & 0 deletions app/models/dashboard.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class Dashboard < ApplicationRecord
belongs_to :user
end
2 changes: 2 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class User < ApplicationRecord
end
19 changes: 13 additions & 6 deletions client/src/App.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import React from 'react';

import React, { Component } from 'react';
import { getQueryParams } from "./utility/urlUtility"
import './App.css';

function App() {
import Login from'./component/login'
class App extends Component {

constructor(){
super()
this.state = { token: getQueryParams().token }
}
render(){

return (
<div className="App">
Yo!

{!this.state.token ? <Login /> : "" }

</div>
);
);}
}

export default App;
6 changes: 6 additions & 0 deletions client/src/component/login/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import React from 'react'


export default ()=>{
return ( <a href={`https://github.com/login/oauth/authorize?client_id=${process.env.REACT_APP_CLIENT_ID}`} >log in w/ github</a>)
}
10 changes: 5 additions & 5 deletions client/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import * as serviceWorker from './serviceWorker';

ReactDOM.render((
<Router>
<Route path="/poo" render={App} />
</Router>), document.getElementById('root'));
ReactDOM.render(

<App />
, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
Expand Down
8 changes: 8 additions & 0 deletions client/src/utility/urlUtility.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export function getQueryParams() {
const query = window.location.search.substring(1);
const pairs = query.split('&').map((str) => str.split('='));
return pairs.reduce((memo, pair) => {
memo[pair[0]] = pair[1];
return memo;
}, {});
}
5 changes: 5 additions & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,16 @@
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)



module CustomDash
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0

config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
Expand Down
5 changes: 4 additions & 1 deletion config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
Rails.application.routes.draw do
resources :dashboards
resources :users
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
get "/test" => "test#new"
get "/auth/google/callback" => "session#googleAuth"
#get "/auth/google/callback" => "session#googleAuth"
get '/auth/github', to: 'authentication#github', format: false
end
10 changes: 10 additions & 0 deletions db/migrate/20190831164054_create_users.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :login
t.string :name

t.timestamps
end
end
end
9 changes: 9 additions & 0 deletions db/migrate/20190831165244_create_dashboards.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class CreateDashboards < ActiveRecord::Migration[6.0]
def change
create_table :dashboards do |t|
t.references :user, null: false, foreign_key: true

t.timestamps
end
end
end
Loading

0 comments on commit 6daf0f0

Please sign in to comment.