<commit_before># Copyright 2014 Huawei Technologies Co. Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Define all the RestfulAPI entry points."""
import logging
import netaddr
import re
import simplejson as json
import sys

from flask import flash
from flask import redirect
from flask import render_template
from flask import request
from flask import session as app_session
from flask import url_for

from flask.ext.restful import Resource
from sqlalchemy.sql import and_
from sqlalchemy.sql import or_

from compass.api import app
from compass.api import auth
from compass.api import errors
from compass.api import login_manager
from compass.api import util
from compass.db import database
from compass.db.model import Adapter
from compass.db.model import Cluster as ModelCluster
from compass.db.model import ClusterHost as ModelClusterHost
from compass.db.model import ClusterState
from compass.db.model import HostState
from compass.db.model import Machine as ModelMachine
from compass.db.model import Role
from compass.db.model import Switch as ModelSwitch
from compass.db.model import SwitchConfig
from compass.db.model import User as ModelUser
from compass.tasks.client import celery

from flask.ext.login import current_user
from flask.ext.login import login_required
from flask.ext.login import login_user
from flask.ext.login import logout_user

from flask.ext.wtf import Form
from wtforms.fields import BooleanField
from wtforms.fields import PasswordField
from wtforms.fields import TextField
from wtforms.validators import Required


@login_manager.header_loader
def load_user_from_token(token):
    """Return a user object from token."""
    duration = app.config['REMEMBER_COOKIE_DURATION']
    max_age = 0
    if sys.version_info > (2, 6):
        max_age = duration.total_seconds()
    else:
        max_age = (duration.microseconds + (
            duration.seconds + duration.days * 24 * 3600) * 1e6) / 1e6

    user_id = auth.get_user_info_from_token(token, max_age)
    if not user_id:
        logging.info("No user can be found from the token!")
        return None

    user = User.query.filter_by(id=user_id)
    return user


@login_manager.user_loader
def load_user(user_id):
    """Load user from user ID."""
    return ModelUser.query.get(user_id)


@app.route('/restricted')
def restricted():
    return render_template('restricted.jinja')


@app.errorhandler(403)
def forbidden_403(exception):
    """Unathenticated user page."""
    return render_template('forbidden.jinja'), 403


@app.route('/logout')
@login_required
def logout():
    """User logout."""
    logout_user()
    flash('You have logged out!')
    return redirect(url_for('index'))


@app.route('/')
def index():
    """Index page."""
    return render_template('index.jinja')


@app.route('/token', methods=['POST'])
def get_token():
    """Get token from email and passowrd after user authentication."""
    data = json.loads(request.data)
    email = data['email']
    password = data['password']

    user = auth.authenticate_user(email, password)
    if not user:
        error_msg = "User cannot be found or email and password do not match!"
        return errors.handle_invalid_user_info(
            errors.ObjectDoesNotExist(error_msg)
        )

    token = user.get_auth_token()
    login_user(user)

    return util.make_json_response(
        200, {"status": "OK", "token": token}
    )


class LoginForm(Form):
    """Define login form."""
    email = TextField('Email', validators=[Required()])
    password = PasswordField('Password', validators=[Required()])
    remember = BooleanField('Remember me', default=False)


@app.route("/login", methods=['GET', 'POST'])
def login():
    """User login."""
    if current_user.is_authenticated():
        return redirect(url_for('index'))
    else:
        form = LoginForm()
        if form.validate_on_submit():
            email = form.email.data
            password = form.password.data

            user = auth.authenticate_user(email, password)
            if not user:<commit_msg>Use latest validator provided by wtforms<commit_after># Copyright 2014 Huawei Technologies Co. Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Define all the RestfulAPI entry points."""
import logging
import netaddr
import re
import simplejson as json
import sys

from flask import flash
from flask import redirect
from flask import render_template
from flask import request
from flask import session as app_session
from flask import url_for

from flask.ext.restful import Resource
from sqlalchemy.sql import and_
from sqlalchemy.sql import or_

from compass.api import app
from compass.api import auth
from compass.api import errors
from compass.api import login_manager
from compass.api import util
from compass.db import database
from compass.db.model import Adapter
from compass.db.model import Cluster as ModelCluster
from compass.db.model import ClusterHost as ModelClusterHost
from compass.db.model import ClusterState
from compass.db.model import HostState
from compass.db.model import Machine as ModelMachine
from compass.db.model import Role
from compass.db.model import Switch as ModelSwitch
from compass.db.model import SwitchConfig
from compass.db.model import User as ModelUser
from compass.tasks.client import celery

from flask.ext.login import current_user
from flask.ext.login import login_required
from flask.ext.login import login_user
from flask.ext.login import logout_user

from flask.ext.wtf import Form
from wtforms.fields import BooleanField
from wtforms.fields import PasswordField
from wtforms.fields import TextField
from wtforms.validators import DataRequired


@login_manager.header_loader
def load_user_from_token(token):
    """Return a user object from token."""
    duration = app.config['REMEMBER_COOKIE_DURATION']
    max_age = 0
    if sys.version_info > (2, 6):
        max_age = duration.total_seconds()
    else:
        max_age = (duration.microseconds + (
            duration.seconds + duration.days * 24 * 3600) * 1e6) / 1e6

    user_id = auth.get_user_info_from_token(token, max_age)
    if not user_id:
        logging.info("No user can be found from the token!")
        return None

    user = User.query.filter_by(id=user_id)
    return user


@login_manager.user_loader
def load_user(user_id):
    """Load user from user ID."""
    return ModelUser.query.get(user_id)


@app.route('/restricted')
def restricted():
    return render_template('restricted.jinja')


@app.errorhandler(403)
def forbidden_403(exception):
    """Unathenticated user page."""
    return render_template('forbidden.jinja'), 403


@app.route('/logout')
@login_required
def logout():
    """User logout."""
    logout_user()
    flash('You have logged out!')
    return redirect(url_for('index'))


@app.route('/')
def index():
    """Index page."""
    return render_template('index.jinja')


@app.route('/token', methods=['POST'])
def get_token():
    """Get token from email and passowrd after user authentication."""
    data = json.loads(request.data)
    email = data['email']
    password = data['password']

    user = auth.authenticate_user(email, password)
    if not user:
        error_msg = "User cannot be found or email and password do not match!"
        return errors.handle_invalid_user_info(
            errors.ObjectDoesNotExist(error_msg)
        )

    token = user.get_auth_token()
    login_user(user)

    return util.make_json_response(
        200, {"status": "OK", "token": token}
    )


class LoginForm(Form):
    """Define login form."""
    email = TextField('Email', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember = BooleanField('Remember me', default=False)


@app.route("/login", methods=['GET', 'POST'])
def login():
    """User login."""
    if current_user.is_authenticated():
        return redirect(url_for('index'))
    else:
        form = LoginForm()
        if form.validate_on_submit():
            email = form.email.data
            password = form.password.data

            user = auth.authenticate_user(email, password)
            if not user:
{'fraction_non_alphanumeric': 0.09408161032709769, 'fraction_numerical': 0.007220216606498195, 'mean_word_length': 3.894004282655246, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4779228', 'n_tokens_mistral': 2678, 'n_tokens_neox': 2522, 'n_words': 882}