Skip to content

Commit

Permalink
feat: GitHubログイン機能を実装 (#66)
Browse files Browse the repository at this point in the history
  • Loading branch information
djkazunoko committed Apr 6, 2024
1 parent 3b533cf commit 19905bd
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 0 deletions.
9 changes: 9 additions & 0 deletions app/controllers/user_sessions_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# frozen_string_literal: true

class UserSessionsController < ApplicationController
def create
user = User.find_or_create_from_auth_hash!(request.env['omniauth.auth'])
session[:user_id] = user.id
redirect_to new_group_path, notice: 'ログインしました'
end
end
12 changes: 12 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,16 @@ class User < ApplicationRecord
validates :uid, presence: true, uniqueness: { scope: :provider }
validates :name, presence: true, uniqueness: true
validates :image_url, presence: true, uniqueness: true

def self.find_or_create_from_auth_hash!(auth_hash)
provider = auth_hash[:provider]
uid = auth_hash[:uid]
nickname = auth_hash[:info][:nickname]
image_url = auth_hash[:info][:image]

User.find_or_create_by!(provider:, uid:) do |user|
user.name = nickname
user.image_url = image_url
end
end
end
3 changes: 3 additions & 0 deletions app/views/groups/index.html.slim
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ p.mb-4
.mb-4
= link_to '2次会グループを作成', new_group_path

.mb-4
= button_to "GitHubでログイン", '/auth/github', data: { turbo: false }

p.text-xl.font-bold.mb-4
| 2次会グループ一覧

Expand Down
2 changes: 2 additions & 0 deletions app/views/groups/new.html.slim
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
p style="color: green" = notice

h1.text-2xl.font-bold.mb-4
| 2次会グループを作成

Expand Down
1 change: 1 addition & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@

# Defines the root path route ("/")
root "groups#index"
get "auth/:provider/callback" => "user_sessions#create"
end

0 comments on commit 19905bd

Please sign in to comment.