af3c1ff by Arvind at 2013-01-07 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, \
de07eb4 by Arvind at 2013-01-09 15
     render_template, flash, _app_ctx_stack, make_response, jsonify
16
from urllib import unquote_plus
17
import json
c70fe3f by Arvind Khadri at 2013-06-19 18
import conf
af3c1ff by Arvind at 2013-01-07 19
# configuration
20
DATABASE = 'alipiBlog'
21
COLLECTION_NAME = 'posts'
22
DEBUG = True
c70fe3f by Arvind Khadri at 2013-06-19 23
SECRET_KEY = conf.SECRET_KEY
af3c1ff by Arvind at 2013-01-07 24
USERNAME = 'admin'
25
PASSWORD = 'default'
26
DB_PORT = 27017
27
DB_HOST = 'localhost'
df78035 by Arvind Khadri at 2013-06-24 28
URL = "http://localhost:5001"
af3c1ff by Arvind at 2013-01-07 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
ee97526 by Anon Ray at 2013-06-27 34
# Jinja filters
35
app.jinja_env.filters['len'] = len
36
af3c1ff by Arvind at 2013-01-07 37
544de4f by Anon Ray at 2013-06-27 38
def validateSweet(payload):
39
    for i in payload:
9f6e341 by Anon Ray at 2013-06-27 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:
544de4f by Anon Ray at 2013-06-27 47
            return False
9f6e341 by Anon Ray at 2013-06-27 48
    return True
544de4f by Anon Ray at 2013-06-27 49
6daf1ab by Anon Ray at 2013-07-09 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
af3c1ff by Arvind at 2013-01-07 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
de07eb4 by Arvind at 2013-01-09 70
@app.errorhandler(404)
af3c1ff by Arvind at 2013-01-07 71
def page_not_found(e):
72
    return render_template('404.html'), 404
73
74
ce32b69 by Arvind at 2013-01-08 75
@app.errorhandler(500)
347ae26 by Arvind at 2013-01-08 76
def internal_error(e):
77
    return render_template('500.html'), 500
78
af3c1ff by Arvind at 2013-01-07 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():
de07eb4 by Arvind at 2013-01-09 88
    response = make_response()
89
    response.headers['Access-Control-Allow-Origin'] = '*'
90
    data = {}
91
    data_list = []
544de4f by Anon Ray at 2013-06-27 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:
1a7990c by Arvind at 2013-04-26 106
        id = g.collection.insert(i)
544de4f by Anon Ray at 2013-06-27 107
        data['permalink'] = app.config['URL'] + '/posts/' + str(ObjectId(id))
1a7990c by Arvind at 2013-04-26 108
        data['id'] = str(ObjectId(id))
de07eb4 by Arvind at 2013-01-09 109
        data_list.append(data)
110
    response.data = json.dumps(data_list)
544de4f by Anon Ray at 2013-06-27 111
    print 'swt stored..'
de07eb4 by Arvind at 2013-01-09 112
    return response
af3c1ff by Arvind at 2013-01-07 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
1a7990c by Arvind at 2013-04-26 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
af3c1ff by Arvind at 2013-01-07 147
@app.route('/posts/<post_id>',methods=['GET'])
148
def show_specific_entry(post_id):
149
    try:
1a7990c by Arvind at 2013-04-26 150
        res = g.collection.find({'_id':ObjectId(post_id)})
af3c1ff by Arvind at 2013-01-07 151
        if(res.count() > 0):
1a7990c by Arvind at 2013-04-26 152
            #entries = make_list(res)
544de4f by Anon Ray at 2013-06-27 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)
af3c1ff by Arvind at 2013-01-07 160
        else:
de07eb4 by Arvind at 2013-01-09 161
            abort(404)
af3c1ff by Arvind at 2013-01-07 162
    except InvalidId:
de07eb4 by Arvind at 2013-01-09 163
        abort(404)
af3c1ff by Arvind at 2013-01-07 164
165
347ae26 by Arvind at 2013-01-08 166
@app.route('/posts/delete/', methods=['POST'])
167
def delete_post():
168
    try:
169
        g.collection.remove({'_id':ObjectId(request.form['post_id'])})
544de4f by Anon Ray at 2013-06-27 170
        return jsonify(status='ok')
347ae26 by Arvind at 2013-01-08 171
    except:
172
        abort(500)
173
af3c1ff by Arvind at 2013-01-07 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
c70fe3f by Arvind Khadri at 2013-06-19 180
@app.route('/serveUser')
181
def serveUser():
df78035 by Arvind Khadri at 2013-06-24 182
    if "logged_in" in session:
6daf1ab by Anon Ray at 2013-07-09 183
        #print session["logged_in"]
df78035 by Arvind Khadri at 2013-06-24 184
        session['key'] = conf.SECRET_KEY
185
        return render_template('user.html')
186
    else:
187
        return render_template('login.html', error=None)
c70fe3f by Arvind Khadri at 2013-06-19 188
6daf1ab by Anon Ray at 2013-07-09 189
@app.route('/user/', methods=['POST', 'GET'])
190
@app.route('/user/<user_id>', methods=['GET'])
191
def user(user_id='all'):
c70fe3f by Arvind Khadri at 2013-06-19 192
    if request.method == 'POST':
193
        response = make_response()
194
        db = g.connection[app.config['DATABASE']]
195
        collection = db['sweet_users']
6daf1ab by Anon Ray at 2013-07-09 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.'
c70fe3f by Arvind Khadri at 2013-06-19 208
        return response
6daf1ab by Anon Ray at 2013-07-09 209
c70fe3f by Arvind Khadri at 2013-06-19 210
    elif request.method == 'GET':
211
        db = g.connection[app.config['DATABASE']]
212
        collection = db['sweet_users']
213
        users = []
6daf1ab by Anon Ray at 2013-07-09 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)
c70fe3f by Arvind Khadri at 2013-06-19 222
        return render_template("users.html", users=users)
223
224
df78035 by Arvind Khadri at 2013-06-24 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:
49ade63 by Anon Ray at 2013-07-03 237
                pass
238
        response.status_code = 403
239
        response.headers['Access-Control-Allow-Origin'] = '*'
240
        return response
df78035 by Arvind Khadri at 2013-06-24 241
    elif request.method == "GET":
242
        return app.send_static_file("sweet-authenticate.js")
243
244
af3c1ff by Arvind at 2013-01-07 245
def make_list(res):
246
    entries = []
247
    for row in res:
1a7990c by Arvind at 2013-04-26 248
        d = row
af3c1ff by Arvind at 2013-01-07 249
        d['id'] = str(row['_id'])
6daf1ab by Anon Ray at 2013-07-09 250
        if d['who'] in getUsers():
251
            d['registered'] = True
af3c1ff by Arvind at 2013-01-07 252
        entries.append(d)
253
    return entries
254
255
if __name__ == '__main__':
1a7990c by Arvind at 2013-04-26 256
    app.run(debug=True, port=5001)