Ejemplo n.º 1
0
class User(CRUDMixin, SerializerMixin, db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    roles = db.relationship('Role',
                            secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))
    displayname = db.Column(db.String(255))
    last_login_at = db.Column(db.DateTime)
    current_login_at = db.Column(db.DateTime)
    last_login_ip = db.Column(db.String(100))
    current_login_ip = db.Column(db.String(100))
    login_count = db.Column(db.Integer)
    confirmed_at = db.Column(db.DateTime)
    active = db.Column(db.Boolean(), default=1)
    type = db.Column(db.String(50))
    __mapper_args__ = {'polymorphic_identity': 'user', 'polymorphic_on': type}

    #serialiser arguement
    __json_hidden__ = ['password']
    __json_modifiers__ = {
        'last_login_at': FORMAT_DATETIME,
        'current_login_at': FORMAT_DATETIME,
        'confirmed_at': FORMAT_DATETIME
    }

    def populate_from_form(self, form):
        self.email = form.email.data
        self.displayname = form.displayname.data
        if form.password.data:
            self.password = encrypt_password(form.password.data)

    def set_password(self, password):
        self.password = encrypt_password(password)
        db.session.commit()

    def __repr__(self):
        return "<User Name:%s Email:%s>" % (self.displayname, self.email)
Ejemplo n.º 2
0
class Guest(ExportMixin, CRUDMixin, SerializerMixin, db.Model):
    ''' Class to represent guest profile, it will be filled fully/partially 
            depending upon site configuration

    '''
    id = db.Column(db.Integer, primary_key=True)
    siteid = db.Column(db.Integer, db.ForeignKey('wifisite.id'))
    firstname = db.Column(db.String(60))
    lastname = db.Column(db.String(60))
    age = db.Column(db.Integer, index=True)
    gender = db.Column(db.String(10), index=True)
    state = db.Column(db.Integer, index=True)
    fbcheckedin = db.Column(db.Integer, index=True, default=0)
    fbliked = db.Column(db.Integer, index=True, default=0)
    state = db.Column(db.Integer, index=True)
    email = db.Column(db.String(60))
    phonenumber = db.Column(db.String(15))
    agerange = db.Column(db.String(15))
    created_at = db.Column(db.DateTime,
                           default=datetime.datetime.utcnow,
                           index=True)
    apisync = db.Column(db.Integer,
                        index=False)  #Flag to be set after syncing to API
    synchedat = db.Column(db.DateTime, index=True)  #synched time in UTC
    demo = db.Column(db.Boolean(), default=0, index=True)
    newsletter = db.Column(db.Boolean(), default=0, index=True)
    dob = db.Column(db.String(15))
    details = db.Column(JSONEncodedDict(255))  #used for handling extra details
    site        = db.relationship(Wifisite, backref=db.backref("guests", \
                                cascade="all,delete"))

    __export_titles__ = [
        'Firstname', 'Lastname', 'Email', 'Phone Number', 'Age Range', "DOB",
        'Extra', "Created on"
    ]
    __export_public__ = [
        'firstname', 'lastname', 'email', 'phonenumber', 'agerange', 'dob',
        'details', 'created_at'
    ]
    __export_modifiers__ = {
        'created_at': 'format_datetime',
        'details': 'guest_details_to_str'
    }

    def guest_details_to_str(self, key):
        '''Convert detatils, which are like extra info collected into a string format'''
        if self.details:
            return {key: ','.join('{}:{}'.format(k, v) \
                 for k,v in sorted(self.details.items()))}
        else:
            return {}

    def get_device_phonenumber(self):
        for device in self.devices:
            phonenumber = device.get_phonenumber()
            if phonenumber:
                return phonenumber
        return ''

    def get_gender(self):
        if self.gender == 1:
            return 'M'
        elif self.gender == 2:
            return 'F'
        else:
            return 'N/A'

    def populate_from_guest_form(self, form, wifisite):
        details = {}
        if hasattr(form, 'email'):
            self.email = form.email.data
        if hasattr(form, 'firstname'):
            self.firstname = form.firstname.data
        if hasattr(form, 'lastname'):
            self.lastname = form.lastname.data
        if hasattr(form, 'phonenumber'):
            self.phonenumber = form.phonenumber.data
        if hasattr(form, 'dob'):
            self.dob = form.dob.data
        if hasattr(form, 'newsletter'):
            self.newsletter = form.newsletter.data
        if hasattr(form, 'extra1'):
            details.update({form.extra1.label.text: form.extra1.data})
        if hasattr(form, 'extra2'):
            details.update({form.extra2.label.text: form.extra2.data})
        self.details = details

    def populate_from_fb_profile(self, profile, wifisite):
        self.firstname = profile.get('first_name')
        self.lastname = profile.get('last_name')
        self.email = profile.get('email')
        self.gender = profile.get('gender')
        age_range = profile.get('age_range')
        dob = profile.get('birthday')
        if dob:
            #convert MM-DD-YYY to DD-MM-YYYY
            self.dob = arrow.get(dob, 'MM/DD/YYYY').format('DD/MM/YYYY')
        if age_range:
            self.agerange = '%s-%s' % (age_range.get(
                'min', ''), age_range.get('max', ''))

    def get_query(self, siteid, startdate, enddate):

        return Guest.query.filter(
            and_(Guest.siteid == siteid, Guest.demo == 0,
                 Guest.created_at >= startdate.naive,
                 Guest.created_at <= enddate.naive))
Ejemplo n.º 3
0
class Notification(CRUDMixin, SerializerMixin, db.Model):
    ''' Class to represent notifications.


    '''
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text)
    created_at = db.Column(db.DateTime,
                           default=datetime.datetime.utcnow,
                           index=True)
    viewed = db.Column(db.Boolean(), default=0, index=True)
    viewed_at = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, index=True)
    account_id = db.Column(db.Integer, db.ForeignKey('account.id'))
    notifi_type = db.Column(db.Integer, index=True)
    notifi_id = db.Column(db.String(20), index=True)

    @classmethod
    def get_common_notifications(cls, account_id):
        notifications = Notification.query.filter_by(
            viewed=0, user_id=0, account_id=account_id).all()
        return notifications

    @classmethod
    def get_user_notifications(cls, account_id, user_id):
        notifications = Notification.query.filter_by(
            viewed=0, user_id=user_id, account_id=account_id).all()
        return notifications

    @classmethod
    def mark_as_read(cls, id, account_id):
        notification = Notification.query.filter_by(
            id=id, account_id=account_id).first()
        if not notification:
            return None
        notification.viewed = 1
        notification.viewed_at = arrow.now().naive
        db.session.commit()
        return 1

    @classmethod
    def mark_as_unread(cls, id, account_id):
        notification = Notification.query.filter_by(
            id=id, account_id=account_id).first()
        if not notification:
            return None
        notification.viewed = 0
        notification.viewed_at = None
        db.session.commit()
        return 1

    @classmethod
    def check_notify_added(cls, notifi_id):
        if Notification.query.filter_by(notifi_id=notifi_id).first():
            return True
        return False

    def get_type(self):
        if self.notifi_type == NOTIFI_TYPE_DANGER:
            return 'danger'
        elif self.notifi_type == NOTIFI_TYPE_INFO:
            return 'info'
        elif self.notifi_type == NOTIFI_TYPE_SUCCESS:
            return 'success'
        elif self.notifi_type == NOTIFI_TYPE_WARNING:
            return 'warning'
        else:
            return ''
Ejemplo n.º 4
0
class Voucher(CRUDMixin,SerializerMixin,db.Model):
    id              = db.Column(db.Integer, primary_key=True)
    batchid         = db.Column(db.String(10),index=True)
    voucher         = db.Column(db.String(20),index=True,unique=True)
    notes           = db.Column(db.String(50),index=True)
    duration_type   = db.Column(db.Integer,default=1)
    duration_val    = db.Column(db.BigInteger(),default=3600)
    bytes_t         = db.Column(db.BigInteger(),default=1000)
    speed_dl        = db.Column(db.BigInteger(),default=256)
    speed_ul        = db.Column(db.BigInteger(),default=256)
    used            = db.Column(db.Boolean(),default=False,index=True)
    num_devices     = db.Column(db.Integer,default=1,index=True)
    active          = db.Column(db.Integer,default=1,index=True) 
    siteid          = db.Column(db.Integer, db.ForeignKey('wifisite.id'))
    account_id      = db.Column(db.Integer, db.ForeignKey('account.id'))
    used_at         = db.Column(db.DateTime,index=True)   #used time in UTC,filled once voucher is used
    site            = db.relationship(Wifisite, backref=db.backref("vouchers", \
                                cascade="all,delete"))

    __form_fields_avoid__ = ['id','siteid','account_id','voucher',
                                'used_at','used','active']

    def get_duration(self):
        '''Returns duration in minutes'''
        if self.duration_type == 1:           
            return self.duration_val
        elif self.duration_type == 2:           
            return self.duration_val * 60        
        elif self.duration_type == 3:           
            return self.duration_val * 60 * 24
        else:
            return 0                  

    def get_query(self,siteid,startdate,enddate):
        return Voucher.query.filter_by(siteid=siteid)   

    def check_and_update_validity(self,loginauth,starttime=None):
        '''Check if current device can do login

        '''
        if starttime:
            utcnow = starttime.naive
        else:
            utcnow = arrow.utcnow().naive

        #get currently active auths for this account
        auths = Voucherauth.query.filter(and_(Voucherauth.voucherid==\
                    self.id,Voucherauth.endtime > utcnow)).all()   
        devices = []    
        for auth in auths:
            if auth.is_currently_active():
                devices.append(auth.deviceid)

        
        #check if max number of devices are already connected
        if loginauth.deviceid not in devices and \
            len(devices) >= self.num_devices:
            current_app.logger.warning('Max device limit reached for:%s, not able to login\
                    device:%s'%(self.id,loginauth.deviceid))
            return (None,_('Looks like max allowed devices are already connected'))


        #check timelimit if voucher is already used
        
        if self.used_at:
            usage = arrow.get(utcnow).timestamp - arrow.get(self.used_at).timestamp
            duration = self.get_duration()*60 - usage
            startedat = self.used_at
        else:
            duration = self.get_duration()*60
            self.used_at = utcnow
            self.used = True
            self.save()
            startedat = utcnow


        if not duration > 60:
            current_app.logger.warning('Time limit reached for:%s, not able to login\
                    device:%s'%(self.id,loginauth.deviceid)) 
            return (None,_('Looks like you have reached max time limit'))

        time_available = int(math.floor(duration/60))

        data_available = 0

        if self.bytes_t: # if data limit is specified
            (time_used,data_used) = loginauth.get_usage(startedat)
            if not data_used < self.bytes_t:
                current_app.logger.warning('Max data limit reached for:%s, not able to login\
                    device:%s'%(self.id,loginauth.deviceid))
                return (None,_('Looks like you have reached max data limit'))
            else:
                data_available = self.bytes_t - data_used
        else:
             data_available = 0

        #all good, update login auth and return it
        loginauth.starttime = utcnow
        loginauth.time_limit = time_available
        loginauth.data_limit = data_available
        loginauth.endtime = arrow.get(utcnow).\
                        replace(minutes=time_available).naive              
        loginauth.speed_ul = self.speed_ul
        loginauth.speed_dl = self.speed_dl
        loginauth.save()
        return (True,'')