forked from zifnab06/zifb.in
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
267 lines (217 loc) · 9.36 KB
/
app.py
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
___author__ = 'zifnab'
from flask import Flask, redirect, request, render_template, flash, abort, Response, url_for
from mongoengine import connect
from flask_debugtoolbar import DebugToolbarExtension
from flask_login import LoginManager, login_user, login_required, logout_user, current_user, fresh_login_required
from flask_wtf import Form, RecaptchaField
from wtforms.fields import *
from wtforms.validators import *
from passlib.hash import sha512_crypt
from datetime import datetime, timedelta, date
from pygments import highlight
from pygments.lexers import guess_lexer, get_lexer_by_name, get_all_lexers
from pygments.formatters import HtmlFormatter
from markdown2 import markdown
from simplecrypt import encrypt, decrypt
from binascii import hexlify
from util import random_string
import database
import arrow
import cgi
import string
from hashlib import sha1
from werkzeug.routing import BaseConverter
app = Flask(__name__)
class SHA1Converter(BaseConverter):
def __init__(self, map):
super(SHA1Converter, self).__init__(map)
self.regex = '[A-Za-z0-9]{40}'
app.url_map.converters['sha1'] = SHA1Converter
with app.app_context():
#THIS ROUTE CAN GO WHEREVER THE FUCK IT PLEASES
@app.route('/<string:id>')
@app.route('/<sha1:digest>')
def get(id=None, digest=None):
if id:
paste = database.Paste.objects(name__exact=id).first()
if digest:
paste = database.Paste.objects(digest__exact=digest).first()
if paste is None:
abort(404)
elif paste.expire is not None and arrow.get(paste.expire) < arrow.utcnow():
paste.delete()
abort(404)
else:
return render_paste(paste, title=paste.id)
import auth
from config import local_config
app.config.from_object(local_config)
app.config['DEBUG_TB_PANELS'] = [
'flask_debugtoolbar.panels.versions.VersionDebugPanel',
'flask_debugtoolbar.panels.timer.TimerDebugPanel',
'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
'flask_debugtoolbar.panels.template.TemplateDebugPanel',
'flask_debugtoolbar.panels.logger.LoggingPanel',
'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel',
'flask_debugtoolbar_mongo.panel.MongoDebugPanel'
]
@app.template_filter('prettytime')
def format_datetime(value, format='medium'):
return arrow.get(value).format('YYYY-MM-DD HH:mm')
@app.template_filter('humanize')
def humanize_date(value):
return arrow.get(value).humanize()
db = connect('zifbin')
import admin
toolbar = DebugToolbarExtension(app)
from api import v1
def get_lexers():
yield ('none', 'Automatically Detect')
yield ('markdown', 'markdown')
for lexer in sorted(get_all_lexers()):
yield (lexer[1][0], lexer[0])
class PasteForm(Form):
text = TextAreaField('Paste Here', validators=[Required()])
expiration = SelectField('Expiration', choices=[('0', 'Expires Never'),
('1', 'Expires In Fifteen Minutes'),
('2', 'Expires In Thirty Minutes'),
('3', 'Expires In One Hour'),
('4', 'Expires In Six Hours'),
('5', 'Expires in Twelve Hours'),
('6', 'Expires In One Day')], default='0')
language = SelectField('Language', choices=[i for i in get_lexers()])
class PasteFormNoAuth(PasteForm):
expiration = SelectField('Expiration', choices=[('1', 'Expires In Fifteen Minutes'),
('2', 'Expires In Thirty Minutes'),
('3', 'Expires In One Hour'),
('4', 'Expires In Six Hours'),
('5', 'Expires in Twelve Hours'),
('6', 'Expires In One Day')], default='6')
class ConfirmForm(Form):
confirm = SubmitField('Click here to confirm deletion', validators=[Required()])
@app.route('/', methods=('POST', 'GET'))
@app.route('/new', methods=('POST', 'GET'))
def main():
if current_user.is_authenticated():
form = PasteForm(request.form)
else:
print 'test'
form = PasteFormNoAuth(request.form)
if form.validate_on_submit():
times = {
'0':None,
'1':{'minutes':+15},
'2':{'minutes':+30},
'3':{'hours':+1},
'4':{'hours':+6},
'5':{'hours':+12},
'6':{'days':+1}
}
paste = database.Paste()
paste.paste = form.text.data
paste.digest = sha1(paste.paste.encode('utf-8')).hexdigest()
if (current_user.is_authenticated()):
paste.user = current_user.to_dbref()
#Create a name and make sure it doesn't exist
paste.name = random_string()
collision_check = database.Paste.objects(name__exact=paste.name).first()
while collision_check is not None:
paste.name = random_string()
collision_check = database.Paste.objects(name__exact=paste.name).first()
if form.language.data is not None:
paste.language = form.language.data
else:
paste.language = guess_lexer(form.text.data).name
paste.time = datetime.utcnow()
if times.get(form.expiration.data) is not None:
paste.expire = arrow.utcnow().replace(**times.get(form.expiration.data)).datetime
if times.get(form.expiration.data) is None and not current_user.is_authenticated():
paste.expire = arrow.utcnow.replace(**times.get(6))
paste.save()
return redirect('/{id}'.format(id=paste.name))
return render_template('new_paste.html', form=form)
@app.route('/my')
def my():
if not current_user.is_authenticated():
abort(403)
pastes = database.Paste.objects(user=current_user.to_dbref()).order_by('-expire', '-time')
if pastes.count() == 0:
pastes = None
return render_template("my_pastes.html", pastes=pastes, title="My Pastes")
@app.route('/raw/<string:id>')
@app.route('/raw/<sha1:digest>')
def raw(id=None, digest=None):
if id:
paste = database.Paste.objects(name__exact=id).first()
if digest:
paste = database.Paste.objects(digest__exact=digest).first()
if paste is None:
abort(404)
else:
return Response(paste.paste, mimetype="text/plain")
@app.route('/settings')
@fresh_login_required
def settings():
keys = database.ApiKey.objects(user=current_user.to_dbref())
return render_template('settings.html', keys=keys)
@app.route('/settings/new_api_key', methods=('POST',))
@fresh_login_required
def new_api_key():
key = random_string(size=32)
api_key = database.ApiKey(user=current_user.to_dbref(), key=key)
api_key.save()
return redirect(url_for('settings'))
@app.route('/settings/delete_api_key/<string:key>', methods=('POST',))
@fresh_login_required
def delete_api_key(key):
api_key = database.ApiKey.objects(key=key).first()
print not api_key
print api_key.user == current_user.to_dbref()
if api_key and api_key.user.to_dbref() == current_user.to_dbref():
api_key.delete()
else:
abort(403)
return redirect(url_for('settings'))
@app.route('/<string:id>/delete', methods=('POST',))
def delete(id):
paste = database.Paste.objects(name=id).first()
if not paste:
abort(404)
if paste.user.to_dbref() != current_user.to_dbref():
abort(403)
paste.delete()
return redirect('/my')
def htmlify(string, language=None):
'''
Takes a string, and returns an html encoded string with color formatting
'''
if language is None:
lexer = guess_lexer(string)
else:
try:
lexer = get_lexer_by_name(language)
except:
lexer = guess_lexer(string)
format = HtmlFormatter()
return highlight(string, lexer, format)
def render_paste(paste, title=None):
if not title:
title = paste.id
text = paste.paste
text = text.rstrip('\n')
text += '\n'
lines = len(text.split('\n'))
if paste.language == 'none' or paste.language is None:
paste.language = guess_lexer(text).name
text=htmlify(text, paste.language)
elif paste.language == 'markdown':
text=markdown(cgi.escape(text.replace('!','\\!')))
else:
text=htmlify(text, paste.language)
paste.views += 1
paste.save()
return render_template("paste.html", paste=paste, title=title, text=text, lines=lines)
app.debug = app.config['DEBUG']
def run():
app.run()