我是一名新手 Rails 4 开发人员,需要一些帮助使用 rest-client 将 API 添加到我的简单应用程序。为简单起见,我将只询问 API 的身份验证系统。
我有一个简单的应用程序,它使用 Devise gem 进行身份验证。我希望每个创建帐户的用户都有一个用于安排和预订目的的日历。为此,我使用了一个名为 timekit ( http://timekit.io/) 的 API。他们的身份验证系统响应以下 cURL 代码示例:
curl -X POST \
-H 'Timekit-App: docs' \
-d '{
"email": "doc.brown@timekit.io",
"password": "DeLorean"
}' \
https://api.timekit.io/v2/auth
这将返回以下 JSON:
{
"data": {
"activated": true,
"email": "doc.brown@timekit.io",
"first_name": "Dr. Emmett",
"img": "http://www.gravatar.com/avatar/7a613e5348d63476276935025",
"last_name": "Brown",
"last_sync": null,
"name": "Dr. Emmett Brown",
"timezone": "America/Los_Angeles",
"token": "UZpl3v3PTP1PRwqIrU0DSVpbJkNKl5gN",
"token_generated_at": null,
"api_token": "FluxCapacitator", // note that this is usually a randomized string and not an actual word
}
}
所以现在我的问题如下: 1) 我在 Rails 框架中的什么地方实现这个? 2) 我如何使用 rest-client 而不是 cURL 来做到这一点? 3) 如何将其与 Devise 集成? 4) 有哪些好的资源可以加深我对自己在这里实际所做工作的理解?
最佳答案
很高兴看到您使用 Timekit(我是核心开发人员之一):)
我们目前没有 ruby gem,我也不是 Ruby 开发人员,但这里有一个快速代码示例,说明如何使用 HTTParty 完成此操作图书馆:
# Global configs for "admin" user
TK_ADMIN_USER = 'my-email@gmail.com'
TK_ADMIN_TOKEN = '12345ABCD'
# Example usage:
# timekit = Timekit.new(TK_ADMIN_USER, TK_ADMIN_TOKEN)
# tk_user = timekit.create_user(account)
# someInternalUser.update(tk_token: tk_user.token)
class Timekit
include HTTParty
base_uri 'https://api.timekit.io'
headers 'Timekit-App' => 'your-app-name'
def initialize(user, password)
@auth = {username: user, password: password}
end
def create_user(account)
options = {
body: {
"email" => account.email,
"first_name" => account.first_name,
"last_name" => account.last_name,
"timezone" => "America/Los_Angeles"
}.to_json,
basic_auth: @auth,
}
self.class.post('/v2/users/', options)
end
def create_calendar(account)
options = {
body: {
name: "Bookings",
description: "Hold bookings for clients."
}.to_json,
basic_auth: @auth
}
self.class.post('/v2/calendars', options)
end
end
https://gist.github.com/laander/83cb7f5dde1f933173c7
一般来说,我们的想法是通过我们的 API 创建用户(只要用户在您的入职注册中注册,您就可以透明地创建用户),然后保存 API 返回的 API token 。之后,您可以模拟该用户执行 API 调用(获取日历、创建事件、查询可用性等)
如果您需要更多实际帮助,请在 timekit.io 上给我们留言!
关于ruby-on-rails - 集成 Rails 4、timekit api、rest-client 和 Devise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35104489/