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