-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
94 lines (75 loc) · 2.56 KB
/
api.py
File metadata and controls
94 lines (75 loc) · 2.56 KB
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
from collections import namedtuple
from functools import wraps
import os
import time
from flask import Flask, abort, jsonify, make_response, request, Response
from backend import get_sheet, convert_time
COMMAND = '/dw'
SLACK_DW_CMD_TOKEN = os.environ.get('SLACK_DW_CMD_TOKEN')
SLACK_DW_USER = os.environ.get('SLACK_DW_USER')
SLACK_DW_PW = os.environ.get('SLACK_DW_PW')
Entry = namedtuple('entry', 'user time seconds activity')
wks = get_sheet()
app = Flask(__name__)
def check_auth(username, password):
"""http://flask.pocoo.org/snippets/8/
This function is called to check if a username /
password combination is valid.
"""
return username == SLACK_DW_USER and password == SLACK_DW_PW
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}
)
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@app.errorhandler(400)
def not_found(error):
return make_response(jsonify({'error': 'Bad request'}), 400)
@app.route('/api/v1.0/entries', methods=['GET'])
@requires_auth
def get_items():
entries = [i[:4] for i in (list(wks)[1:])]
return jsonify({'entries': entries})
@app.route('/api/v1.0/entries', methods=['POST'])
def post_entry():
if not request.form or 'token' not in request.form:
print('No token provided')
abort(400)
token = request.form.get('token')
if token != SLACK_DW_CMD_TOKEN:
print('Wrong slack token')
abort(400)
cmd = request.form.get('command')
user = request.form.get('user_name')
text = request.form.get('text')
channel_name = request.form.get('channel_name')
if not cmd == COMMAND:
print('Wrong command')
abort(400)
now = int(time.time())
try:
seconds = convert_time(text)
except ValueError as err:
print('Exception converting time: ', err)
abort(400)
text_fields = text.split(' ', 1)
if len(text_fields) > 1:
activity = ' '.join(text_fields[1:])
else:
activity = channel_name
row = [user, now, seconds, activity]
wks.append_row(start='A1', values=row)
entry = Entry(*row)
return jsonify(entry), 201
if __name__ == '__main__':
app.run(debug=True)