-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.rb
104 lines (91 loc) · 2.16 KB
/
github.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
require 'sinatra'
require './main'
require './errors'
require 'json'
require 'sinatra/cross_origin'
require 'http'
configure do
enable :cross_origin
end
after do
ActiveRecord::Base.connection.close
end
def get_user_by_token(token)
response = HTTP.get(URI("#{USER_INFO_URL}?token=#{token}"))
begin
json = JSON.parse(response)
if json['status'] == 'ok'
json
else
nil
end
rescue JSON::JSONError
raise 'auth returns garbage'
end
end
post '/api/v1/register' do
begin
token, gh_uname, gh_token =
params.fetch_values('token', 'github_user_name', 'github_token')
rescue KeyError
er 'parameter error'
end
# get user_id from token,
# create or update existing one
uid = get_user_by_token(token)['id']
token_stub = MessageSourceTokenStub.create(
source: :github,
user_id: uid,
content: "#{gh_uname}:#{gh_token}")
er 'database error' unless token_stub
Thread.new { `./ruby github_worker.rb` }
{ status: :ok }.to_json
end
delete '/api/v1/register' do
begin
uid, token = params.fetch_values('id', 'token')
er 'parameter error' unless uid && token
stub = MessageSourceTokenStub.find_by_user_id(uid)
if stub&.destroy
{ status: :ok }.to_json
else
er 'wrong id'
end
rescue
er 'wrong parameter'
end
end
get '/api/v1/check_registered' do
begin
token = params.fetch_values('token').first
user = get_user_by_token(token)
uid = user['id']
rescue KeyError
er 'parameter error'
end
# get user_id from token,
# create or update existing one
result = MessageSourceTokenStub.where(
source: :github,
user_id: uid)
if result.size > 0
{ status: :ok, registered: true }.to_json
else
{ status: :ok, registered: false }.to_json
end
end
get '/api/v1/messages' do
uid = params['id']
token = params['token']
github_token = 'get github token with some method'
messages = []
(1..10).to_a.sample.times do
messages << { title: "title is #{Math.rand(1234566).to_s}", user_id: uid }
end
{
status: :ok,
id: uid,
source: 'github',
messages: messages
}.to_json
end