views.py 5.32 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
  # 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.
Sandro Lutz's avatar
Sandro Lutz committed
19
20
21
22
23
24
25
  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 ' 
                  'GROUP BY burger.id '
                  'ORDER BY vote_count DESC')
26
27
28
29
30
31
32
33
34
35
  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
36
# @ldap.login_required
37
38
39
40
def vote():
  '''
  Handles POST requests for voting
  '''
Mathis Dedial's avatar
Mathis Dedial committed
41
42
43
44
45
  def die(message):
    '''
    Display an error-level flash message and return
    '''
    flash(message, 'error')
Mathis Dedial's avatar
Merge    
Mathis Dedial committed
46
    return redirect(url_for('index'))
Mathis Dedial's avatar
Mathis Dedial committed
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
  # 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
72

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

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

Mathis Dedial's avatar
Merge    
Mathis Dedial committed
80
81
  return redirect(url_for('index'))

82

Sandro Lutz's avatar
Sandro Lutz committed
83
84
85
86
87
88
89
90
91
92
93
94
# @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
Sandro Lutz's avatar
Sandro Lutz committed
95

Mathis Dedial's avatar
Merge    
Mathis Dedial committed
96

Sandro Lutz's avatar
Sandro Lutz committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
@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
115

Sandro Lutz's avatar
Sandro Lutz committed
116
117
118
119
120
121
122
123
124
@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
125

126
127

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

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

141
  # A new burger was submitted
142
  if request.method == 'POST':
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
    # 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():
171
172
173
      # In this case, send the user back to the voting page
      flash('You can only create one burger.', 'error')
      return redirect(url_for('index'))
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189

    # 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
190
    return redirect(url_for('index'))
191

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