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
@app.before_request
51
def init_db():
52
    g.connection = Connection(app.config['DB_HOST'], app.config['DB_PORT'])
53
    db = g.connection[app.config['DATABASE']]
54
    g.collection = db[app.config["COLLECTION_NAME"]]
55
56
57
@app.teardown_request
58
def close_db(exception):
59
    g.connection.disconnect()
60
61
62
@app.errorhandler(404)
63
def page_not_found(e):
64
    return render_template('404.html'), 404
65
66
67
@app.errorhandler(500)
68
def internal_error(e):
69
    return render_template('500.html'), 500
70
71
@app.route('/')
72
def show_entries():
73
    res = g.collection.find().sort('_id',direction=-1)
74
    entries = make_list(res)
75
    return render_template('show_entries.html', entries=entries)
76
77
78
@app.route('/add', methods=['POST'])
79
def add_entry():
80
    response = make_response()
81
    response.headers['Access-Control-Allow-Origin'] = '*'
82
    data = {}
83
    data_list = []
84
    try:
85
        payload = json.loads(request.form['data'])
86
    except:
87
        payload = [{'who': request.form['who'], 'what': request.form['what'],
88
               'where': request.form['where'], 'how': request.form['how']}]
89
    valid = validateSweet(payload)
90
    if not valid:
91
        response.status_code = 400
92
        response.data = "Bad or Malformed Request. Please check the validity\
93
        of your request"
94
        return response
95
    print 'swt payload rcvd..'
96
    print payload
97
    for i in payload:
98
        id = g.collection.insert(i)
99
        data['permalink'] = app.config['URL'] + '/posts/' + str(ObjectId(id))
100
        data['id'] = str(ObjectId(id))
101
        data_list.append(data)
102
    response.data = json.dumps(data_list)
103
    print 'swt stored..'
104
    return response
105
106
107
@app.route('/login', methods=['GET', 'POST'])
108
def login():
109
    error = None
110
    if request.method == 'POST':
111
        if request.form['username'] != app.config['USERNAME']:
112
            error = 'Invalid username'
113
        elif request.form['password'] != app.config['PASSWORD']:
114
            error = 'Invalid password'
115
        else:
116
            session['logged_in'] = True
117
            flash('You were logged in')
118
            return redirect(url_for('show_entries'))
119
    return render_template('login.html', error=error)
120
121
122
@app.route('/query/<post_id>',methods=['GET'])
123
def return_database_entry(post_id):
124
    try:
125
        res = g.collection.find_one({'_id':ObjectId(post_id)})
126
        if(res):
127
            res['blog'] = url_for('show_specific_entry', post_id = str(res['_id']))
128
            del(res['_id'])
129
            return jsonify(res)
130
            # entries = make_list(res)
131
            # return render_template('show_posts.html', entries=res, str=str)
132
        else:
133
            abort(404)
134
    except InvalidId:
135
        abort(404)
136
137
138
139
@app.route('/posts/<post_id>',methods=['GET'])
140
def show_specific_entry(post_id):
141
    try:
142
        res = g.collection.find({'_id':ObjectId(post_id)})
143
        if(res.count() > 0):
144
            #entries = make_list(res)
145
            entries = []
146
            for i in res:
147
                _id = i['_id']
148
                del(i['_id'])
149
                i['id'] = _id
150
                entries.append(i)
151
            return render_template('show_posts.html', entries=entries, str=str)
152
        else:
153
            abort(404)
154
    except InvalidId:
155
        abort(404)
156
157
158
@app.route('/posts/delete/', methods=['POST'])
159
def delete_post():
160
    try:
161
        g.collection.remove({'_id':ObjectId(request.form['post_id'])})
162
        return jsonify(status='ok')
163
    except:
164
        abort(500)
165
166
@app.route('/logout')
167
def logout():
168
    session.pop('logged_in', None)
169
    flash('You were logged out')
170
    return redirect(url_for('show_entries'))
171
172
@app.route('/serveUser')
173
def serveUser():
174
    if "logged_in" in session:
175
        print session["logged_in"]
176
        session['key'] = conf.SECRET_KEY
177
        return render_template('user.html')
178
    else:
179
        return render_template('login.html', error=None)
180
181
@app.route('/user', methods=['POST', "GET"])
182
def user():
183
    if request.method == 'POST':
184
        response = make_response()
185
        db = g.connection[app.config['DATABASE']]
186
        collection = db['sweet_users']
187
        collection.insert({'user':request.form["user"],"key":request.form["key"]})
188
        return response
189
    elif request.method == 'GET':
190
        db = g.connection[app.config['DATABASE']]
191
        collection = db['sweet_users']
192
        users = []
193
        for user in collection.find():
194
            users.append(user['user'])
195
        return render_template("users.html", users=users)
196
197
198
@app.route('/authenticate', methods=['POST','GET'])
199
def authenticate():
200
    if request.method == "POST":
201
        response = make_response()
202
        db = g.connection[app.config['DATABASE']]
203
        collection = db['sweet_users']
204
        for i in collection.find():
205
            if i['user'] == request.form['user'] and i['key'] == request.form['hash']:
206
                response.status_code = 200
207
                response.headers['Access-Control-Allow-Origin'] = '*'
208
                return response
209
            else:
210
                response.status_code = 403
211
                response.headers['Access-Control-Allow-Origin'] = '*'
212
                return response
213
    elif request.method == "GET":
214
        return app.send_static_file("sweet-authenticate.js")
215
216
217
def make_list(res):
218
    entries = []
219
    for row in res:
220
        d = row
221
        d['id'] = str(row['_id'])
222
        # d['text'] = row['text']
223
        # d["title"] = row["title"]
224
        # d["user"] = row["user"]
225
        entries.append(d)
226
    return entries
227
228
if __name__ == '__main__':
229
    app.run(debug=True, port=5001)