From 9a4be12e6e2cec7ce35a5cf5a8ecdcd30571ea99 Mon Sep 17 00:00:00 2001 From: redfast00 Date: Fri, 12 Apr 2019 11:31:59 +0200 Subject: [PATCH] API create transaction --- app/controllers/application_controller.rb | 7 ++++++- app/controllers/transactions_controller.rb | 2 +- python_api_example/transactions.py | 20 ++++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 python_api_example/transactions.py diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index ddae356..7e9a6e9 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,7 +1,12 @@ class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. - # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception + # Don't verfiy authenticity token (protects against CSRF) for API requests + skip_before_action :verify_authenticity_token, if: :api_request? + + def api_request? + user_token && request.format.json? + end rescue_from CanCan::AccessDenied do |exception| respond_to do |format| diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rb index b17b4b4..da84be7 100644 --- a/app/controllers/transactions_controller.rb +++ b/app/controllers/transactions_controller.rb @@ -51,7 +51,7 @@ class TransactionsController < ApplicationController { debtor: t[:debtor] ? User.find_or_create_by(name: t[:debtor]) : User.zeus, creditor: t[:creditor] ? User.find_or_create_by(name: t[:creditor]) : User.zeus, - issuer: current_client || current_user, + issuer: authenticate_user_or_client!, amount: (t[:euros].to_f * 100 + t[:cents].to_f).to_i, message: t[:message], }.merge(current_client ? { id_at_client: t[:id_at_client] } : {}) diff --git a/python_api_example/transactions.py b/python_api_example/transactions.py new file mode 100644 index 0000000..c416a5c --- /dev/null +++ b/python_api_example/transactions.py @@ -0,0 +1,20 @@ +import requests + + +base_url = 'http://localhost:3000' +user = 'j' +user_token = '1idEG5bFVVjUcl+15Y1DsQ==' + +headers = {'Authorization': f'Token token={user_token}'} + +data = { + 'transaction': { + 'euros': 5.0, + 'message': 'Transaction from Python', + 'debtor': user, + 'creditor': 'Zeus' + } +} + +r = requests.post((base_url + f'/transactions.json'), headers=headers, json=data) +print(r.text)