views.py 5.14 KB
Newer Older
Mathis Dedial's avatar
Mathis Dedial committed
1
2
3
'''
Contains all views
'''
Sandro Lutz's avatar
Sandro Lutz committed
4
from app import app, ldap
5
from datetime import datetime
Mathis Dedial's avatar
Merge    
Mathis Dedial committed
6
from flask import flash, g, redirect, render_template, request, session, url_for
Mathis Dedial's avatar
Mathis Dedial committed
7
8
9
from sqlalchemy.sql import text
from .mappings import BREAD, PATTY, TOPPINGS, SIDE
from .models import db, Burger, Vote
Sandro Lutz's avatar
Sandro Lutz committed
10

11
@app.route('/')
Sandro Lutz's avatar
Sandro Lutz committed
12
def index():
13
14
15
  '''
  Front page. Shows a list of all burgers 
  '''
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  # Fetch list of burgers with corresponding vote info
  # Could probably also be done with SQLAlchemy but too lazy to look up how
  # TODO: Query has a bug. Only burgers created by the user himself are returned.
  querystring = text('SELECT burger.id AS id, name, description, burger.nethz AS nethz, timestamp, bread, patty, toppings, side, COUNT(vote_1.id) AS vote_count, vote_2.id AS vote_id '
                    'FROM burger '
                    'LEFT JOIN vote AS vote_1 ON vote_1.burger_id=burger.id '
                    'LEFT JOIN vote AS vote_2 ON vote_2.burger_id=burger.id AND vote_2.nethz = :nethz '
                    'ORDER BY vote_count ')
  burger_list = db.engine.execute(querystring, nethz=g.user).fetchall()
  return render_template('vote.html',
                          burger_list=burger_list,
                          bread=BREAD,
                          patty=PATTY,
                          toppings=TOPPINGS,
                          side=SIDE)


@app.route('/vote', methods=['POST'])
Mathis Dedial's avatar
Merge    
Mathis Dedial committed
34
# @ldap.login_required
35
36
37
38
def vote():
  '''
  Handles POST requests for voting
  '''
Mathis Dedial's avatar
Mathis Dedial committed
39
40
41
42
43
  def die(message):
    '''
    Display an error-level flash message and return
    '''
    flash(message, 'error')
Mathis Dedial's avatar
Merge    
Mathis Dedial committed
44
    return redirect(url_for('index'))
Mathis Dedial's avatar
Mathis Dedial committed
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
  # Check if the burger_id is valid
  burger_id = request.form.get('burger_id')
  if not burger_id or not Burger.query.get(burger_id):
    return die('Invalid burger ID')

  # User is casting their vote
  if request.form.get('action') == 'like':
    # Check if the user hasn't already voted for the same burger
    if Vote.query.filter_by(nethz=g.user, burger_id=burger_id).first():
      return die('You have already liked this burger.')
    
    # Add vote
    vote = Vote(
      nethz=g.user,
      burger_id=burger_id,
    )
    db.session.add(vote)
    db.session.commit()
    flash('Thanks for voting!', 'success')

  # User is revoking their vote
  elif request.form.get('action') == 'unlike':
    # Find the vote
    vote = Vote.query.filter_by(nethz=g.user, burger_id=burger_id).first()
Mathis Dedial's avatar
Mathis Dedial committed
70

71
72
73
74
    if vote:
      # Delete the vote
      db.session.delete(vote)
      db.session.commit()
Mathis Dedial's avatar
Mathis Dedial committed
75

76
    flash('Your like has been removed.', 'success')
Mathis Dedial's avatar
Mathis Dedial committed
77

Mathis Dedial's avatar
Merge    
Mathis Dedial committed
78
79
  return redirect(url_for('index'))

80

Sandro Lutz's avatar
Sandro Lutz committed
81
82
83
84
85
86
87
88
89
90
91
92
93
@app.before_request
def load_user():
  '''
  Load user data before any request processing
  '''
  try:
    if session['nethz']:
      g.user = session['nethz']
      return
  except KeyError:
    pass
  g.user = None

Mathis Dedial's avatar
Merge    
Mathis Dedial committed
94

Sandro Lutz's avatar
Sandro Lutz committed
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
@app.route('/login', methods=['GET', 'POST'])
def login():
  '''
  Login page. LDAP-Login only.
  '''
  if g.user:
      return redirect(url_for('index'))
  if request.method == 'POST':
      user = request.form['user']
      passwd = request.form['passwd']
      test = ldap.bind_user(user, passwd)
      if test is None or passwd == '':
        flash('Invalid credentials', 'error')
      else:
        g.user = session['nethz'] = user
        return redirect(url_for('index'))
  return render_template('login.html')

Mathis Dedial's avatar
Merge    
Mathis Dedial committed
113

Sandro Lutz's avatar
Sandro Lutz committed
114
115
116
117
118
119
120
121
122
@app.route('/logout')
def logout():
  '''
  Logout page
  '''
  session.pop('nethz', None)
  g.user = None
  flash('Successfully logged out.')
  return redirect(url_for('index'))
Mathis Dedial's avatar
Mathis Dedial committed
123

124
125

@app.route('/new', methods=['GET', 'POST'])
Sandro Lutz's avatar
Sandro Lutz committed
126
# @ldap.login_required
127
128
129
130
131
132
133
134
135
136
137
138
def create():
  '''
  Burger creator
  '''

  def die(message):
    '''
    Display an error-level flash message and return
    '''
    flash(message, 'error')
    return render_template('creator.html')

139
  # A new burger was submitted
140
  if request.method == 'POST':
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
    # Perform field validation
    bread = request.form.get('bread')
    if not bread:
      return die('Please select a bread for your burger.')
    
    patty = request.form.get('patty')
    if not patty:
      return die('Please select a patty for your burger.')
  
    toppings = request.form.getlist('toppings')
    if not toppings:
      return die('Please select at least one topping for your burger.')
    
    side = request.form.get('side')
    if not side:
      return die('Please select a side for your burger.')

    name = request.form.get('name')
    if not name:
      return die('Please give your burger a name.')

    description = request.form.get('description')
    if not description:
      return die('Please describe your burger in a few short sentences.')

    # Check that the user hasn't already created a burger
    if Burger.query.filter_by(nethz=g.user).first():
      return die('You can only create one burger.')

    # All set, now save the burger in the database
    burger = Burger(
      name=name,
      description=description,
      nethz=g.user,
      timestamp=datetime.now(),
      bread=bread,
      patty=patty,
      toppings=', '.join(toppings),
      side=side,
    )
    db.session.add(burger)
    db.session.commit()

    flash('Congrats on your new burger!', 'success')
Mathis Dedial's avatar
Merge    
Mathis Dedial committed
186
    return redirect(url_for('index'))
187

Sandro Lutz's avatar
Sandro Lutz committed
188
  return render_template('creator.html')