Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: create wallet api #14

Open
wants to merge 2 commits into
base: feature/authentication-api
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 26 additions & 26 deletions app/controllers/api/v1/sessions_controller.rb
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
class Api::V1::SessionsController < ApplicationController
def create
@user = User.find_by(email: login_params[:email])
if @user&.valid_password?(login_params[:password])
token = JsonWebToken.encode({
user_id: @user.id,
jti: SecureRandom.uuid,
exp: Time.now.to_i + ENV["token_expire_time"].to_i
})
response.headers['Authorization'] = "Bearer #{token}"
else
render_error :unauthorized, "Email or password is incorrect"
end
end
def destroy
response.headers.delete('Authorization')
end
private
def login_params
params.permit User::LOGIN_PARAMS
end
end
class Api::V1::SessionsController < ApplicationController
def create
@user = User.find_by(email: login_params[:email])

if @user&.valid_password?(login_params[:password])
token = JsonWebToken.encode({
user_id: @user.id,
jti: SecureRandom.uuid,
exp: Time.now.to_i + ENV["token_expire_time"].to_i
})
response.headers['Authorization'] = "Bearer #{token}"
else
render_error :unauthorized, "Email or password is incorrect"
end
end

def destroy
response.headers.delete('Authorization')
end

private

def login_params
params.permit User::LOGIN_PARAMS
end
end
34 changes: 17 additions & 17 deletions app/controllers/api/v1/users_controller.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
class Api::V1::UsersController < ApplicationController
def create
@user = User.create(user_params)
if @user.errors.blank?
render :create, status: :ok
else
render_error :bad_request, @user.errors.full_messages
end
end
private
def user_params
params.permit User::USER_PARAMS
end
end
class Api::V1::UsersController < ApplicationController
def create
@user = User.create(user_params)

if @user.errors.blank?
render :create, status: :ok
else
render_error :bad_request, @user.errors.full_messages
end
end

private

def user_params
params.permit User::USER_PARAMS
end
end
77 changes: 77 additions & 0 deletions app/controllers/api/v1/wallets_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
class Api::V1::WalletsController < ApplicationController
before_action :authenticate_request!
before_action :find_wallet, only: [:show, :update, :destroy]

def index
@wallets = []
current_user.user_wallets.each do |user_wallet|
@wallets.push(user_wallet.wallet)
end
Comment on lines +7 to +9
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
current_user.user_wallets.each do |user_wallet|
@wallets.push(user_wallet.wallet)
end
@wallets = user_wallet.wallet

だけでいいかも

render :index, status: :ok
end

def create
@wallet = Wallet.new(create_params)

if @wallet.save
UserWallet.create(
user_id: current_user.id,
wallet_id: @wallet.id,
user_role: User::roles[:OWNER]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
user_role: User::roles[:OWNER]
user_role: User.roles[:OWNER]

https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/ColonMethodCall

)

render :create, status: :created
else
render_error :bad_request, "Create wallet failed"
end
end

def show
if accessible?
render :show, status: :ok
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

省略可

else
render_error :forbidden, "Not allow to access this wallet"
end
end

def update
if owner?
@wallet.update(update_params)
render :update, status: :ok
else
render_error :forbidden, "Not allow to update this wallet"
end
end

def destroy
if owner?
@wallet.destroy
else
render_error :forbidden, "Not allow to delete this wallet"
end
end

private

def create_params
params.permit(Wallet::CREATE_PARAMS)
end

def update_params
params.permit(Wallet::UPDATE_PARAMS)
end

def find_wallet
@wallet = Wallet.find_by(id: params[:id])
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idの時はfindの時の方がシンプル


render_error :not_found, "Wallet ##{params[:id]} not found" unless @wallet
end

def owner?
UserWallet.find_by(user_id: current_user.id, wallet_id: @wallet.id, user_role: User::roles[:OWNER])
end

def accessible?
UserWallet.find_by(user_id: current_user.id, wallet_id: @wallet.id)
end
end
31 changes: 31 additions & 0 deletions app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,39 @@
class ApplicationController < ActionController::API
rescue_from Exception, with: :rescue_error

attr_reader :current_user

protected
def authenticate_request!
unless user_id_in_token?
render_error :unauthorized, "Not authenticated"
return
end
@current_user = User.find(auth_token['user_id'])
rescue JWT::VerificationError, JWT::DecodeError
render_error :unauthorized, "Not authenticated"
end

def render_error status, message
@error_message = message
render 'api/error', status: status
end

private
def http_token
@http_token = request.headers['Authorization'].split(' ').last if request.headers['Authorization'].present?
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indentずれてる?

end

def auth_token
@auth_token = JsonWebToken.decode(http_token)
end

def user_id_in_token?
http_token && auth_token && auth_token[:user_id].to_i
end

def rescue_error error
@error_message = error.message
render 'api/error', status: :bad_request
end
end
4 changes: 4 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ class User < ApplicationRecord
USER_PARAMS = %i(email password password_confirmation name).freeze
LOGIN_PARAMS = %i(email password).freeze

enum roles: [:OWNER, :MANAGER, :OBSERVER]

has_many :user_wallets, dependent: :destroy

# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
Expand Down
4 changes: 4 additions & 0 deletions app/models/user_wallet.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class UserWallet < ApplicationRecord
belongs_to :user
belongs_to :wallet
end
6 changes: 6 additions & 0 deletions app/models/wallet.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class Wallet < ApplicationRecord
CREATE_PARAMS = %i(name)
UPDATE_PARAMS = %i(name is_freezed)

has_many :user_wallets, dependent: :destroy
end
6 changes: 3 additions & 3 deletions app/views/api/error.json.jbuilder
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
json.data do
json.message @error_message || 'Some thing went wrong'
end
json.data do
json.message @error_message || 'Some thing went wrong'
end
10 changes: 5 additions & 5 deletions app/views/api/v1/sessions/create.json.jbuilder
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
json.data do
json.id @user.id
json.email @user.email
json.name @user.name
end
json.data do
json.id @user.id
json.email @user.email
json.name @user.name
end
6 changes: 3 additions & 3 deletions app/views/api/v1/sessions/destroy.json.jbuilder
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
json.data do
json.message "Logout successfully"
end
json.data do
json.message "Logout successfully"
end
6 changes: 3 additions & 3 deletions app/views/api/v1/users/create.json.jbuilder
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
json.data do
json.user @user
end
json.data do
json.user @user
end
3 changes: 3 additions & 0 deletions app/views/api/v1/wallets/create.json.jbuilder
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
json.data do
json.wallet @wallet
end
3 changes: 3 additions & 0 deletions app/views/api/v1/wallets/destroy.json.jbuilder
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
json.data do
json.message "Delete the wallet successfully"
end
3 changes: 3 additions & 0 deletions app/views/api/v1/wallets/index.json.jbuilder
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
json.data do
json.wallets @wallets
end
3 changes: 3 additions & 0 deletions app/views/api/v1/wallets/show.json.jbuilder
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
json.data do
json.wallet @wallet
end
3 changes: 3 additions & 0 deletions app/views/api/v1/wallets/update.json.jbuilder
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
json.data do
json.wallet @wallet
end
2 changes: 2 additions & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
post '/login', to: "sessions#create"
post '/logout', to: "sessions#destroy"
post '/signup', to: "users#create"

resources :wallets, only: [:index, :create, :show, :update, :destroy]
end
end
end
11 changes: 11 additions & 0 deletions db/migrate/20211110172151_create_wallets.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class CreateWallets < ActiveRecord::Migration[6.1]
def change
create_table :wallets do |t|
t.string :name, null: false, default: ""
t.integer :total, null: false, default: 0
t.boolean :is_freezed, null: false, default: false

t.timestamps
end
end
end
9 changes: 9 additions & 0 deletions db/migrate/20211110173054_create_user_wallets.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class CreateUserWallets < ActiveRecord::Migration[6.1]
def change
create_table :user_wallets do |t|
t.integer :user_role, null: false, default: 0

t.timestamps
end
end
end
5 changes: 5 additions & 0 deletions db/migrate/20211110173638_add_user_to_user_wallets.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class AddUserToUserWallets < ActiveRecord::Migration[6.1]
def change
add_reference :user_wallets, :user, foreign_key: true
end
end
5 changes: 5 additions & 0 deletions db/migrate/20211110173738_add_wallet_to_user_wallets.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class AddWalletToUserWallets < ActiveRecord::Migration[6.1]
def change
add_reference :user_wallets, :wallet, foreign_key: true
end
end
22 changes: 21 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions test/fixtures/user_wallets.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value
11 changes: 11 additions & 0 deletions test/fixtures/wallets.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value
7 changes: 7 additions & 0 deletions test/models/user_wallet_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
require "test_helper"

class UserWalletTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
7 changes: 7 additions & 0 deletions test/models/wallet_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
require "test_helper"

class WalletTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end