<commit_before>import os
from datetime import datetime, timedelta
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base

from hashlib import sha256 as sha

Base = declarative_base()

class User(Base):
    class NotLoggedIn(Exception):
        def __init__(self, msg):
            self.msg = msg
        
        def __repr__(self):
            return self.msg
    
    __tablename__ = 'users'
    user_id = sqlalchemy.Column(
            sqlalchemy.String, 
            primary_key=True, 
            unique=True
        )
    ldap_id = sqlalchemy.Column(sqlalchemy.String, nullable=False)
    password = sqlalchemy.Column(sqlalchemy.String, nullable=False)
    banned = sqlalchemy.Column(sqlalchemy.Boolean, nullable=False)
    gets_mail = sqlalchemy.Column(sqlalchemy.Boolean, nullable=False)
    salt = sqlalchemy.Column(sqlalchemy.String, nullable=False)
    
    def __init__(self, user_id, ldap_id, password, banned = False, gets_mail = False, salt = None):
        self.__dict__['db'] = DBConn()
        self.user_id = user_id
        self.ldap_id = ldap_id
        if salt == None:
            self.salt = ''.join(map(lambda x:'./12345678890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[ord(x)%65], os.urandom(64)))
            self.password = password
        else:
            self.salt = salt
            self.password = (password,)
        self.banned = banned
        self.gets_mail = gets_mail
        
    def __setattr__(self, attr, value):
        if attr != 'password':
            if attr == 'banned' or attr == 'gets_mail':
                if value == 0 or value == None or value == False:
                    self.__dict__[attr] = False
                else:
                    self.__dict__[attr] = True
            else:
                self.__dict__[attr] = value
        else:
            if isinstance(value, str):
                self.__dict__[attr] = self._get_pwhash(value)
            else:
                self.__dict__[attr] = value[0]
    
    def __repr__(self):
        return "<User('%s','%s','%s','%s','%s')>" % \
                (self.user_id, self.password, str(self.banned),
                 str(self.gets_mail), self.salt)
    
    def _get_pwhash(self, password):
        hash = sha()
        hash.update(password)
        hash.update(self.salt)
        return hash.hexdigest()
    
    def validate_password(self,password):
        return self.password == self._get_pwhash(password)
    
    def login(self,irc_id,password):
        if self.validate_password(password):
            db = DBConn()
            db_session = db.get_session()
            login = db_session.query(Login).filter(Login.irc_id == irc_id).first()
            if login == None:
                login = Login(irc_id,datetime.now()+timedelta(1))
                self.logins.append(login)
            else:
                login.expires = datetime.now()+timedelta(1)
            db_session.commit()
            db_session.close()
            self.session.commit()
            self.session.close()
            return True
        else:
            return False
    
    def add_post(self,status):
        db = DBConn()
        db_session = db.get_session()
        self.posts.append(Post(status))
        db_session.commit()
        db_session.close()
        self.session.commit()
        self.session.close()
    
    @staticmethod
    def get_by_user_id(user_id):
        db = DBConn()
        db_session = db.get_session()
        user = db_session.query(User). \
                filter(User.user_id == user_id).first()
        user.session = db_session
        return user
    
    @staticmethod
    def get_by_irc_id(irc_id):
        db = DBConn()
        db_session = db.get_session()
        user = db_session.query(User). \
                select_from(sqlalchemy.orm.join(User, Login)). \
                filter(Login.irc_id == irc_id).first()
        user.session = db_session
        if user == None:
            raise User.NotLoggedIn("You must identify to use this command.")
        return user

class Post(Base):
    __tablename__ = 'posts'<commit_msg>Avert NoneType exception if user is not logged in<commit_after>import os
from datetime import datetime, timedelta
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base

from hashlib import sha256 as sha

Base = declarative_base()

class User(Base):
    class NotLoggedIn(Exception):
        def __init__(self, msg):
            self.msg = msg
        
        def __repr__(self):
            return self.msg
    
    __tablename__ = 'users'
    user_id = sqlalchemy.Column(
            sqlalchemy.String, 
            primary_key=True, 
            unique=True
        )
    ldap_id = sqlalchemy.Column(sqlalchemy.String, nullable=False)
    password = sqlalchemy.Column(sqlalchemy.String, nullable=False)
    banned = sqlalchemy.Column(sqlalchemy.Boolean, nullable=False)
    gets_mail = sqlalchemy.Column(sqlalchemy.Boolean, nullable=False)
    salt = sqlalchemy.Column(sqlalchemy.String, nullable=False)
    
    def __init__(self, user_id, ldap_id, password, banned = False, gets_mail = False, salt = None):
        self.__dict__['db'] = DBConn()
        self.user_id = user_id
        self.ldap_id = ldap_id
        if salt == None:
            self.salt = ''.join(map(lambda x:'./12345678890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[ord(x)%65], os.urandom(64)))
            self.password = password
        else:
            self.salt = salt
            self.password = (password,)
        self.banned = banned
        self.gets_mail = gets_mail
        
    def __setattr__(self, attr, value):
        if attr != 'password':
            if attr == 'banned' or attr == 'gets_mail':
                if value == 0 or value == None or value == False:
                    self.__dict__[attr] = False
                else:
                    self.__dict__[attr] = True
            else:
                self.__dict__[attr] = value
        else:
            if isinstance(value, str):
                self.__dict__[attr] = self._get_pwhash(value)
            else:
                self.__dict__[attr] = value[0]
    
    def __repr__(self):
        return "<User('%s','%s','%s','%s','%s')>" % \
                (self.user_id, self.password, str(self.banned),
                 str(self.gets_mail), self.salt)
    
    def _get_pwhash(self, password):
        hash = sha()
        hash.update(password)
        hash.update(self.salt)
        return hash.hexdigest()
    
    def validate_password(self,password):
        return self.password == self._get_pwhash(password)
    
    def login(self,irc_id,password):
        if self.validate_password(password):
            db = DBConn()
            db_session = db.get_session()
            login = db_session.query(Login).filter(Login.irc_id == irc_id).first()
            if login == None:
                login = Login(irc_id,datetime.now()+timedelta(1))
                self.logins.append(login)
            else:
                login.expires = datetime.now()+timedelta(1)
            db_session.commit()
            db_session.close()
            self.session.commit()
            self.session.close()
            return True
        else:
            return False
    
    def add_post(self,status):
        db = DBConn()
        db_session = db.get_session()
        self.posts.append(Post(status))
        db_session.commit()
        db_session.close()
        self.session.commit()
        self.session.close()
    
    @staticmethod
    def get_by_user_id(user_id):
        db = DBConn()
        db_session = db.get_session()
        user = db_session.query(User). \
                filter(User.user_id == user_id).first()
        user.session = db_session
        return user
    
    @staticmethod
    def get_by_irc_id(irc_id):
        db = DBConn()
        db_session = db.get_session()
        user = db_session.query(User). \
                select_from(sqlalchemy.orm.join(User, Login)). \
                filter(Login.irc_id == irc_id).first()
        if user == None:
            raise User.NotLoggedIn("You must identify to use this command.")
        user.session = db_session
        return user

class Post(Base):
    __tablename__ = 'posts'
{'fraction_non_alphanumeric': 0.10809500727096462, 'fraction_numerical': 0.005332040717401842, 'mean_word_length': 1.9464476972509819, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, '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': '383486', 'n_tokens_mistral': 2591, 'n_tokens_neox': 2476, 'n_words': 487}