1
# -*- coding: utf-8 -*-
2
"""
3
    swtr
4
    ~~~~~~
5
6
    http://swtr.us
7
8
    :license: BSD, see LICENSE for more details.
9
"""
10
from __future__ import with_statement
11
from pymongo import Connection
12
from bson.objectid import ObjectId
13
from bson.errors import InvalidId
14
from flask import Flask, request, session, g, redirect, url_for, abort, \
15
     render_template, flash, _app_ctx_stack, make_response, jsonify
16
from urllib import unquote_plus
17
import json
18
import conf
19
# configuration
20
DATABASE = 'alipiBlog'
21
COLLECTION_NAME = 'posts'
22
DEBUG = True
23
SECRET_KEY = conf.SECRET_KEY
24
USERNAME = 'admin'
25
PASSWORD = 'default'
26
DB_PORT = 27017
27
DB_HOST = 'localhost'
28
URL = "http://localhost:5001"
29
# create our little application :)
30
app = Flask(__name__)
31
app.config.from_object(__name__)
32
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
33
34
# Jinja filters
35
app.jinja_env.filters['len'] = len
36
37
38
def validateSweet(payload):
39
    for i in payload:
40
        try:
41
            if len(i['who']) and len(i['what']) and len(i['where']) and\
42
               len(i['how']) and len(i['created']):
43
                pass
44
            else:
45
                return False
46
        except KeyError:
47
            return False
48
    return True
49
50
def getUsers():
51
    db = g.connection[app.config['DATABASE']]
52
    coll = db['sweet_users']
53
    users = []
54
    for i in coll.find():
55
        users.append(i['user'])
56
    return users
57
58
@app.before_request
59
def init_db():
60
    g.connection = Connection(app.config['DB_HOST'], app.config['DB_PORT'])
61
    db = g.connection[app.config['DATABASE']]
62
    g.collection = db[app.config["COLLECTION_NAME"]]
63
64
65
@app.teardown_request
66
def close_db(exception):
67
    g.connection.disconnect()
68
69
70
@app.errorhandler(404)
71
def page_not_found(e):
72
    return render_template('404.html'), 404
73
74
75
@app.errorhandler(500)
76
def internal_error(e):
77
    return render_template('500.html'), 500
78
79
@app.route('/')
80
def show_entries():
81
    res = g.collection.find().sort('_id',direction=-1)
82
    entries = make_list(res)
83
    return render_template('show_entries.html', entries=entries)
84
85
86
@app.route('/add', methods=['POST'])
87
def add_entry():
88
    response = make_response()
89
    response.headers['Access-Control-Allow-Origin'] = '*'
90
    data = {}
91
    data_list = []
92
    try:
93
        payload = json.loads(request.form['data'])
94
    except:
95
        payload = [{'who': request.form['who'], 'what': request.form['what'],
96
               'where': request.form['where'], 'how': request.form['how']}]
97
    valid = validateSweet(payload)
98
    if not valid:
99
        response.status_code = 400
100
        response.data = "Bad or Malformed Request. Please check the validity\
101
        of your request"
102
        return response
103
    print 'swt payload rcvd..'
104
    print payload
105
    for i in payload:
106
        id = g.collection.insert(i)
107
        data['permalink'] = app.config['URL'] + '/posts/' + str(ObjectId(id))
108
        data['id'] = str(ObjectId(id))
109
        data_list.append(data)
110
    response.data = json.dumps(data_list)
111
    print 'swt stored..'
112
    return response
113
114
115
@app.route('/login', methods=['GET', 'POST'])
116
def login():
117
    error = None
118
    if request.method == 'POST':
119
        if request.form['username'] != app.config['USERNAME']:
120
            error = 'Invalid username'
121
        elif request.form['password'] != app.config['PASSWORD']:
122
            error = 'Invalid password'
123
        else:
124
            session['logged_in'] = True
125
            flash('You were logged in')
126
            return redirect(url_for('show_entries'))
127
    return render_template('login.html', error=error)
128
129
130
@app.route('/query/<post_id>',methods=['GET'])
131
def return_database_entry(post_id):
132
    try:
133
        res = g.collection.find_one({'_id':ObjectId(post_id)})
134
        if(res):
135
            res['blog'] = url_for('show_specific_entry', post_id = str(res['_id']))
136
            del(res['_id'])
137
            return jsonify(res)
138
            # entries = make_list(res)
139
            # return render_template('show_posts.html', entries=res, str=str)
140
        else:
141
            abort(404)
142
    except InvalidId:
143
        abort(404)
144
145
146
147
@app.route('/posts/<post_id>',methods=['GET'])
148
def show_specific_entry(post_id):
149
    try:
150
        res = g.collection.find({'_id':ObjectId(post_id)})
151
        if(res.count() > 0):
152
            #entries = make_list(res)
153
            entries = []
154
            for i in res:
155
                _id = i['_id']
156
                del(i['_id'])
157
                i['id'] = _id
158
                entries.append(i)
159
            return render_template('show_posts.html', entries=entries, str=str)
160
        else:
161
            abort(404)
162
    except InvalidId:
163
        abort(404)
164
165
166
@app.route('/posts/delete/', methods=['POST'])
167
def delete_post():
168
    try:
169
        g.collection.remove({'_id':ObjectId(request.form['post_id'])})
170
        return jsonify(status='ok')
171
    except:
172
        abort(500)
173
174
@app.route('/logout')
175
def logout():
176
    session.pop('logged_in', None)
177
    flash('You were logged out')
178
    return redirect(url_for('show_entries'))
179
180
@app.route('/serveUser')
181
def serveUser():
182
    if "logged_in" in session:
183
        #print session["logged_in"]
184
        session['key'] = conf.SECRET_KEY
185
        return render_template('user.html')
186
    else:
187
        return render_template('login.html', error=None)
188
189
@app.route('/user/', methods=['POST', 'GET'])
190
@app.route('/user/<user_id>', methods=['GET'])
191
def user(user_id='all'):
192
    if request.method == 'POST':
193
        response = make_response()
194
        db = g.connection[app.config['DATABASE']]
195
        collection = db['sweet_users']
196
197
        # check if user already exists
198
        if request.form['user'] in getUsers():
199
            #print 'user already exists!'
200
            flash('User already exists!')
201
            return redirect(url_for('serveUser'))
202
203
        # else insert new user
204
        collection.insert({'user': request.form['user'],
205
                           'key': request.form['key']})
206
        response.status_code = 200
207
        response.data = 'User added.'
208
        return response
209
210
    elif request.method == 'GET':
211
        db = g.connection[app.config['DATABASE']]
212
        collection = db['sweet_users']
213
        users = []
214
        if user_id == 'all':
215
            users = getUsers()
216
        else:
217
            user = collection.find_one({'user': user_id})
218
            if user:
219
                users.append(user['user'])
220
            else:
221
                abort(404)
222
        return render_template("users.html", users=users)
223
224
225
@app.route('/authenticate', methods=['POST','GET'])
226
def authenticate():
227
    if request.method == "POST":
228
        response = make_response()
229
        db = g.connection[app.config['DATABASE']]
230
        collection = db['sweet_users']
231
        for i in collection.find():
232
            if i['user'] == request.form['user'] and i['key'] == request.form['hash']:
233
                response.status_code = 200
234
                response.headers['Access-Control-Allow-Origin'] = '*'
235
                return response
236
            else:
237
                pass
238
        response.status_code = 403
239
        response.headers['Access-Control-Allow-Origin'] = '*'
240
        return response
241
    elif request.method == "GET":
242
        return app.send_static_file("sweet-authenticate.js")
243
244
245
def make_list(res):
246
    entries = []
247
    for row in res:
248
        d = row
249
        d['id'] = str(row['_id'])
250
        if d['who'] in getUsers():
251
            d['registered'] = True
252
        entries.append(d)
253
    return entries
254
255
if __name__ == '__main__':
256
    app.run(debug=True, port=5001)