Пример #1
0
def signup():
    if session.get('logged_in'):
        result = users.find_one({'_id': ObjectId(session.get('id'))})
        if result is None:
            session.clear()
        else:
            return redirect(url_for('index'))

    form = SignupForm(request.form)
    if request.method == 'POST' and form.validate():
        # Set the user inputs
        # Force only the initial character in first name to be capitalised
        first_name = (form.firstname.data.lower()).capitalize()

        # Make sure the first letter is capitalised. Don't care about capitalisation on the rest
        last_name = form.lastname.data
        last_name_first_letter = last_name[0].capitalize()
        last_name_remaining_letters = last_name[1:]
        last_name = last_name_first_letter + last_name_remaining_letters

        email = form.email.data
        # Set the default inputs
        ip = request.environ['REMOTE_ADDR']
        account_level = 0

        # Check if the email address already exists
        existing_user = users.find_one(
            {'email': re.compile(email, re.IGNORECASE)})

        if existing_user is not None:
            flash('Account already exists', 'danger')
            return render_template('signup.html', form=form)
        if existing_user is None:
            #hashpass = bcrypt.hashpw(request.form['password'].encode('utf-8'), bcrypt.gensalt())
            hashpass = request.form['password']
            users.insert({
                'first_name': first_name,
                'last_name': last_name,
                'email': email,
                'password': hashpass,
                'last_ip': ip,
                'account_level': account_level,
                'score': 0,
                'badges': []
            })

            # Retrieve the ID of the newly created user
            new_user = users.find_one(
                {'email': re.compile(email, re.IGNORECASE)})
            user_id = new_user['_id']

            print("INFO: New user has been created with email", email)
            flash('Account registered', 'success')
            return redirect(url_for('login'))
    else:
        return render_template('signup.html', form=form)
Пример #2
0
def profile(id=None):
    if id is not None and bson.objectid.ObjectId.is_valid(id):
        user_profile = users.find_one({'_id': ObjectId(id)})
        user_copy = copy.deepcopy(user_profile)
        if user_copy is not None:
            user_copy['_id'] = str(user_profile['_id'])
            print("USER ID " + user_copy['_id'])
            return render_template('profile.html', user_profile=user_copy)
    elif session.get('logged_in'):
        result = users.find_one({'_id': ObjectId(session.get('id'))})
        if result is not None:
            result['_id'] = str(result['_id'])
            result['password'] = str(result['password'])
            return render_template('profile.html', user_profile=result)
    return redirect('/')
Пример #3
0
def get_current_user_id():
    #Find user from given user id in GET arguments
    if session.get('logged_in'):
        result = users.find_one({'_id': ObjectId(session.get('id'))})
        if result is not None:
            result['_id'] = str(result['_id'])
            result['password'] = str(result['password'])
            return jsonify(result)
        else:
            session.clear()
    return ""
Пример #4
0
def login():
    if session.get('logged_in'):
        result = users.find_one({'_id': ObjectId(session.get('id'))})
        if result is None:
            session.clear()
        else:
            return redirect(url_for('index'))

    ip = request.environ['REMOTE_ADDR']
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        email = form.email.data

        result = users.find_one({'email': re.compile(email, re.IGNORECASE)})
        if result is not None:
            #if (bcrypt.checkpw(form.password.data.encode('utf-8'), result['password'])):
            if (form.password.data == result['password']):

                session['logged_in'] = True
                session['email'] = result.get('email')
                session['id'] = str(result.get('_id'))
                session['fullname'] = result.get(
                    'first_name') + " " + result.get('last_name')
                session['account_level'] = result.get('account_level')
                #flash('You are now logged in', 'success')
                print(session.get('email') + " has logged in")
                return redirect(url_for('index'))

            else:
                print("Failed login attempt |", email, "| IP:", ip)
                error = "wrong_password"
                return render_template('login.html', form=form, error=error)
        else:
            error = "wrong_email"
            return render_template('login.html', form=form, error=error)
    return render_template('login.html', form=form)
Пример #5
0
def report_page():
    ## if level 100 then allow access

    all_reports = []
    cursor = reports.find()
    for current in cursor:
        all_reports.append(current)

    if session.get('logged_in'):
        result = users.find_one({'_id': ObjectId(session.get('id'))})
        if result is not None:
            if result['account_level'] == 100:
                return render_template('reports.html', all_reports=all_reports)
    flash("Access denied", "danger")
    return redirect('/')
Пример #6
0
def clean():

    current_user = None
    if session.get('logged_in'):
        current_user = users.find_one({'_id': ObjectId(session.get('id'))})
    else:
        flash('Access restricted. Please login first', 'danger')
        return redirect(url_for('login'))

    incident_id = request.args.get('incident_id')
    incident = content.find_one({'_id': ObjectId(incident_id)})

    if (incident['status'] == "Available"):

        # Update the incident
        incident['date_cleaned'] = datetime.datetime.now()
        incident['cleaner'] = current_user['_id']
        incident['status'] = "Complete"
        content.save(incident)
        # -- would also update after image here.. not in this version

        # Give the user points
        current_user['score'] = current_user['score'] + incident['value']
        users.save(current_user)

        # Update the feed
        feedObject = {
            'type': "clean",
            'time': int(round(time.time() * 1000)),
            'user_first_name': current_user['first_name'],
            'incident_id': incident['_id'],
            'user_id': current_user['_id']
        }
        feed.insert(feedObject)

        # Update the trash cleaned tracker
        total = totals.find_one()
        total['total_cleaned'] = total['total_cleaned'] + 1
        totals.save(total)

        flash("Cleaned trash successfully", "success")
        return redirect('/')

    return incident_id
Пример #7
0
def getUsers():
    all_users = []
    #Find user from given user id in GET arguments
    user_id = request.args.get('user')
    #If a specific user is requested
    if user_id:
        result = users.find_one({'_id': ObjectId(user_id)})
        if result:
            result['_id'] = str(result['_id'])
            result['password'] = str(result['password'])
            return jsonify(result)
        else:
            return "[]"
    else:
        for x in users.find():
            x['_id'] = str(x['_id'])
            x['password'] = str(x['password'])
            all_users.append(x)
        return jsonify(all_users)
Пример #8
0
def pins_report():
    incident_id = request.args.get('incident_id')
    if session.get('logged_in'):
        result = users.find_one({'_id': ObjectId(session.get('id'))})
        if result is not None:
            prev_reported = False
            cursor = reports.find({'incident_id': ObjectId(incident_id)})
            for record in cursor:
                if record['reporter'] == result['_id']:
                    prev_reported = True
            if not prev_reported:
                new_report = {
                    'incident_id': ObjectId(incident_id),
                    'reporter': result['_id'],
                    'date': datetime.datetime.now(),
                    'status': "Unresolved"
                }
                reports.insert_one(new_report)
                flash("Reported post successfully", "success")
            else:
                flash("You already reported this post", "danger")
        return redirect('/')

    return incident_id
Пример #9
0
def upload():
    current_user = None
    if session.get('logged_in'):
        current_user = users.find_one({'_id': ObjectId(session.get('id'))})
    else:
        flash('Access restricted. Please login first', 'danger')
        return redirect(url_for('login'))

    upload_form = UploadForm()
    id = str(current_user['_id'])
    if id is not None and bson.objectid.ObjectId.is_valid(id):
        user = users.find_one({'_id': ObjectId(id)})
        if str(current_user['_id']) == id:
            if request.method == 'POST' and upload_form.validate():

                # If a file was provided by the user then upload and store it
                # Then store the name of the new file in the user profile DB
                if upload_form.image.data:
                    image_data = store_uploaded_image(upload_form.image.data,
                                                      str(user['_id']))

                # Create incident dictionary
                incident = {
                    'uploader': ObjectId(id),
                    'image_before': image_data['image_before'],
                    'image_after': "",
                    'status': "Available",
                    'lat': image_data['lat'],
                    'lon': image_data['lon'],
                    'date_taken': image_data['date_taken'],
                    'date_created': datetime.datetime.now(),
                    'date_cleaned': "",
                    'value': 10,
                    'cleaner': "",
                    'incident_type': "Trash"
                }
                if incident['lat'] == 0 and incident['lon'] == 0:
                    # Tell user could not find location, image was not upload
                    # In future this would let them place pin manually for lat and lon
                    flash("Could not retrieve image location from metadata",
                          "danger")
                else:
                    current_user['score'] = current_user['score'] + 2
                    users.save(current_user)
                    incidentID = content.insert(incident)
                    feedObject = {
                        'type': "new_pin",
                        'time': int(round(time.time() * 1000)),
                        'user_first_name': current_user['first_name'],
                        'incident_id': incidentID,
                        'user_id': current_user['_id']
                    }
                    feed.insert(feedObject)
                    flash("Image uploaded successfully", "success")
                return redirect('/')
            elif request.method == 'GET' and user is not None:
                upload_form.image.data = ""
            elif not upload_form.validate():
                flash("File type must be .JPG", "danger")
            return redirect('/')
        else:
            flash("Access restricted. You do not have permission to do that",
                  'danger')
            return redirect(url_for('index'))

    return redirect(url_for('index'))