<commit_before>#!/usr/bin/env python2
# -*-coding:UTF-8 -*

import ConfigParser
from datetime import datetime
from flask import Flask, current_app
from sqlalchemy import UniqueConstraint
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import UserMixin, AnonymousUserMixin
from flask.ext.scrypt import generate_random_salt, generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from sqlalchemy.dialects.mysql import MEDIUMTEXT

# Parsing Conf File #
configfile = 'config/config.cfg'
cfg = ConfigParser.ConfigParser()
cfg.read(configfile)

# Flask app, bootstrap etc. #
app = Flask(__name__)
app.config['SECRET_KEY'] = cfg.get("Secret", "wtf_secret_key")


db_type = cfg.get('Database', 'type')
db_user = cfg.get('Database', 'user')
db_pwd = cfg.get('Database', 'password')
db_hostname = cfg.get('Database', 'hostname')
db_name = cfg.get('Database', 'db_name')


app.config['SQLALCHEMY_DATABASE_URI'] = db_type + '://' + db_user + ':' + db_pwd + '@' + db_hostname + '/' + db_name
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

db = SQLAlchemy(app)


class Permission():
    DEFAULT = 0x01
    CPE_NOTIFY = 0x02
    ADMINISTER = 0x80


class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    default = db.Column(db.Boolean, default=False, index=True)
    permissions = db.Column(db.Integer)
    users = db.relationship('User', backref='role', lazy='dynamic')

    @staticmethod
    def insert_roles():
        roles = {
                 'User': (Permission.DEFAULT, True),
                 'Validated_User': (Permission.CPE_NOTIFY, False),
                 'Administrator': (0xff, False)
                 }
        for r in roles:
            role = Role.query.filter_by(name=r).first()
            if role is None:
                role = Role(name=r)
            role.permissions = roles[r][0]
            role.default = roles[r][1]
            db.session.add(role)
        db.session.commit()


class Notification(db.Model):
    __tablename__ = 'notifications'
    id = db.Column(db.Integer, primary_key=True)
    fulltxt = db.Column(db.Boolean, default=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    vendor = db.Column(db.String(64), index=True, nullable=False)
    product = db.Column(db.String(64), index=True, nullable=False)
    version = db.Column(db.String(64), nullable=False)
    __table_args__ = (UniqueConstraint('user_id', 'vendor', 'product', 'version'),)


class FullTextNotification(db.Model):
    __tablename__ = 'fulltextnotifications'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    fullnotif = db.Column(db.String(64), index=True, nullable=False)
    __table_args__ = (UniqueConstraint('user_id', 'fullnotif'),)


class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(512))
    password_salt = db.Column(db.String(128))
    affiliation = db.Column(db.String(64), nullable=True)
    pgp = db.Column(MEDIUMTEXT, nullable=True)
    fingerprint = db.Column(db.String(64), nullable=True)
    confirmed = db.Column(db.Boolean, default=False)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    notification = db.relationship('Notification', backref='user', cascade="all, delete-orphan")

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        if self.role is None:
            if self.email == current_app.config['PORTAL_ADMIN']:
                self.role = Role.query.filter_by(permissions=0xff).first()
                self.confirmed = "1"
            if self.role is None:
                self.role = Role.query.filter_by(default=True).first()

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_salt = generate_random_salt()
        self.password_hash = generate_password_hash(password, self.password_salt)

    def verify_password(self, password):
        return check_password_hash(password, self.password_hash, self.password_salt)

    def generate_confirmation_token(self, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'confirm': self.id})

    def confirm(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False

        user = User.query.get_or_404(data.get('confirm'))
        user.confirmed = True
        db.session.add(user)
        db.session.commit()
        return True

    def ping(self):
        self.last_seen = datetime.utcnow()
        db.session.add(self)

    def generate_reset_token(self, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'reset': self.id})

    def reset_password(self, token, <PASSWORD>_password):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False
        if data.get('reset') != self.id:
            return False
        self.password = <PASSWORD>
        db.session.add(self)
        return True

    def generate_email_change_token(self, new_email, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'change_email': self.id, 'new_email': new_email})

    def change_email(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:<commit_msg>Fixing bug about reseting password The new password was never commited<commit_after>#!/usr/bin/env python2
# -*-coding:UTF-8 -*

import ConfigParser
from datetime import datetime
from flask import Flask, current_app
from sqlalchemy import UniqueConstraint
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import UserMixin, AnonymousUserMixin
from flask.ext.scrypt import generate_random_salt, generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from sqlalchemy.dialects.mysql import MEDIUMTEXT

# Parsing Conf File #
configfile = 'config/config.cfg'
cfg = ConfigParser.ConfigParser()
cfg.read(configfile)

# Flask app, bootstrap etc. #
app = Flask(__name__)
app.config['SECRET_KEY'] = cfg.get("Secret", "wtf_secret_key")


db_type = cfg.get('Database', 'type')
db_user = cfg.get('Database', 'user')
db_pwd = cfg.get('Database', 'password')
db_hostname = cfg.get('Database', 'hostname')
db_name = cfg.get('Database', 'db_name')


app.config['SQLALCHEMY_DATABASE_URI'] = db_type + '://' + db_user + ':' + db_pwd + '@' + db_hostname + '/' + db_name
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

db = SQLAlchemy(app)


class Permission():
    DEFAULT = 0x01
    CPE_NOTIFY = 0x02
    ADMINISTER = 0x80


class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    default = db.Column(db.Boolean, default=False, index=True)
    permissions = db.Column(db.Integer)
    users = db.relationship('User', backref='role', lazy='dynamic')

    @staticmethod
    def insert_roles():
        roles = {
                 'User': (Permission.DEFAULT, True),
                 'Validated_User': (Permission.CPE_NOTIFY, False),
                 'Administrator': (0xff, False)
                 }
        for r in roles:
            role = Role.query.filter_by(name=r).first()
            if role is None:
                role = Role(name=r)
            role.permissions = roles[r][0]
            role.default = roles[r][1]
            db.session.add(role)
        db.session.commit()


class Notification(db.Model):
    __tablename__ = 'notifications'
    id = db.Column(db.Integer, primary_key=True)
    fulltxt = db.Column(db.Boolean, default=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    vendor = db.Column(db.String(64), index=True, nullable=False)
    product = db.Column(db.String(64), index=True, nullable=False)
    version = db.Column(db.String(64), nullable=False)
    __table_args__ = (UniqueConstraint('user_id', 'vendor', 'product', 'version'),)


class FullTextNotification(db.Model):
    __tablename__ = 'fulltextnotifications'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    fullnotif = db.Column(db.String(64), index=True, nullable=False)
    __table_args__ = (UniqueConstraint('user_id', 'fullnotif'),)


class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(512))
    password_salt = db.Column(db.String(128))
    affiliation = db.Column(db.String(64), nullable=True)
    pgp = db.Column(MEDIUMTEXT, nullable=True)
    fingerprint = db.Column(db.String(64), nullable=True)
    confirmed = db.Column(db.Boolean, default=False)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    notification = db.relationship('Notification', backref='user', cascade="all, delete-orphan")

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        if self.role is None:
            if self.email == current_app.config['PORTAL_ADMIN']:
                self.role = Role.query.filter_by(permissions=0xff).first()
                self.confirmed = "1"
            if self.role is None:
                self.role = Role.query.filter_by(default=True).first()

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_salt = generate_random_salt()
        self.password_hash = generate_password_hash(password, self.password_salt)

    def verify_password(self, password):
        return check_password_hash(password, self.password_hash, self.password_salt)

    def generate_confirmation_token(self, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'confirm': self.id})

    def confirm(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False

        user = User.query.get_or_404(data.get('confirm'))
        user.confirmed = True
        db.session.add(user)
        db.session.commit()
        return True

    def ping(self):
        self.last_seen = datetime.utcnow()
        db.session.add(self)

    def generate_reset_token(self, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'reset': self.id})

    def reset_password(self, token, <PASSWORD>):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False
        if data.get('reset') != self.id:
            return False
        self.password = <PASSWORD>
        db.session.add(self)
        db.session.commit()
        return True

    def generate_email_change_token(self, new_email, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'change_email': self.id, 'new_email': new_email})

    def change_email(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
{'fraction_non_alphanumeric': 0.12983790936156137, 'fraction_numerical': 0.009096923585841878, 'mean_word_length': 3.2943892045454546, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '4387654', 'n_tokens_mistral': 3994, 'n_tokens_neox': 3821, 'n_words': 740}