Example #1
0
    def post(self):
        ''' Need custom post here to handle wifisite creation with limited parameters

        '''
        itemform = get_wifisite_form(baseform=True)
        itemform.populate()
        if itemform.validate_on_submit():
            try:
                item = self.get_modal_obj()()
                item.site_from_baseform(itemform)
                item.populate_from_dict(self.get_extrafields_modal())
                item.save()
                #create a landing page along with site
                landingpage = Landingpage()
                landingpage.siteid = item.id
                landingpage.save()

            except SQLAlchemyError as exception:
                db.session.rollback()
                logger.exception('UserID:%s submited form caused exception'\
                        %(current_user.id))
                return jsonify({'status':0,'data':{}, 'msg':_('Error while creating %(name)s'\
                        ,name=self.get_name())})
            return jsonify({'status':1,'data':{}, 'msg':_('Successfully added %(name)s'\
                        ,name=self.get_name())})

        else:
            logger.debug('UserID:%s submited form with errors:%s'\
                         %(current_user.id,get_form_errors(itemform)))
            return jsonify({
                'status': 0,
                'data': {},
                'msg': get_form_errors(itemform)
            })
Example #2
0
def generate_report(siteid, startday, endday):
    '''Create and send report for given site during the specified periodic_task


    '''
    site = Wifisite.query.filter_by(id=siteid).first()
    start_date = startday.format('DD-MM-YYYY')
    end_date = endday.format('DD-MM-YYYY')
    current_app.logger.debug(
        'Going to process report for :%s from :%s to :%s' %
        (site.name, start_date, end_date))
    #get all entries within given period
    entries = Guest.query.filter(
        and_(Guest.siteid == siteid, Guest.demo == 0,
             Guest.created_at >= startday, Guest.created_at <= endday)).all()

    csvList = '\n'.join(','.join(row.to_row()) for row in entries)

    filename = "Report_%s_to_%s.csv" % (start_date, end_date)
    attachment = Attachment(filename=filename,
                            content_type='txt/plain',
                            data=csvList)
    msg = Message(_("Wifi usage report for the period :%s to :%s" %
                    (start_date, end_date)),
                  recipients=[site.client.email, site.reports_list],
                  attachments=[attachment])

    msg.body  = _("Dear %s,\n\n"\
            "\tPlease find the wifi usage report for the period of starting from:%s to %s \n"\
            "\nRegards\n"\
            "Admin"%(site.name,start_date,end_date))
    mail.send(msg)
Example #3
0
    def post(self, siteid):
        item = self.get_modal_obj().query.filter_by(siteid=siteid).first()
        if not item:
            item = self.get_modal_obj()
            item.siteid = siteid
        itemform = self.get_form_obj()
        itemform.populate()
        if itemform.validate_on_submit():
            try:
                item.populate_from_form(itemform)
                item.save()
                item.populate_from_dict(self.get_extrafields_modal())
            except SQLAlchemyError as exception:
                db.session.rollback()
                logger.exception('UserID:%s submited form caused exception'\
                        %(current_user.id))
                return jsonify({'status':0,'data':{}, 'msg':_('Error while updating %(name)s'\
                        ,name=self.get_name())})
            return jsonify({'status':1,'data':{}, 'msg':_('Successfully updated %(name)s'\
                        ,name=self.get_name())})

        else:
            logger.debug('UserID:%s submited form with errors:%s'\
                         %(current_user.id,get_form_errors(itemform)))
            return jsonify({
                'status': 0,
                'data': {},
                'msg': get_form_errors(itemform)
            })
Example #4
0
 def populate(self):
     self.session_limit_control.choices = [(0, _('No Limit')),
                                           (1, _('Daily')),
                                           (2, _('Monthly'))]
     self.relogin_policy.choices = [('always', 'Always'),
                                    ('onetime', 'One Time'),
                                    ('monthly', 'Monthly')]
Example #5
0
    def post(self,siteid):
        itemform = self.get_form_obj()
        itemform.populate()
        if itemform.validate_on_submit(): 
            try:
                cnt = 0               
                while cnt < int(itemform.number.data):                         
                    try:
                        item = self.get_modal_obj()()  
                        item.populate_from_form(itemform)          
                        #create voucher
                        item.voucher = '%s%s'%(itemform.batchid.data,
                                        self.create_voucher())
                        #always assign siteid while creation
                        item.siteid = siteid
                        item.populate_from_dict(self.get_extrafields_modal())                         
                        db.session.add(item)
                        db.session.commit()
                    except IntegrityError: #check for unique voucherID
                        db.session.rollback()
                    else:
                        cnt = cnt + 1
            except SQLAlchemyError as exception:
                current_app.logger.exception('UserID:%s submited form caused exception'\
                        %(current_user.id))
                return jsonify({'status':0,'data':{}, 'msg':_('Error while creating %(name)s'\
                        ,name=self.get_name())}) 
            return jsonify({'status':1,'data':{}, 'msg':_('Successfully added %(name)s'\
                        ,name=self.get_name())}) 

        else:
            current_app.logger.debug('UserID:%s submited form with errors:%s'\
                         %(current_user.id,get_form_errors(itemform)))            
            return jsonify({'status':0,'data':{}, 'msg':get_form_errors(itemform)})        
Example #6
0
 def post(self, siteid):
     #upload new file
     try:
         try:
             upload_file = request.files['logofile']
         except BadRequestKeyError:
             try:
                 upload_file = request.files['bgfile']
             except BadRequestKeyError:
                 try:
                     upload_file = request.files['tosfile']
                 except BadRequestKeyError:
                     return jsonify({
                         'status':
                         '0',
                         'msg':
                         _('Unknown file!! only logofile,\
                                     bgfile and tosfile are allowed')
                     })
         if upload_file:
             filetoupload = self.__handleUpload(upload_file)
             if not filetoupload:
                 return jsonify({
                     'status':
                     '0',
                     'msg':
                     _('Error Occured \
                                      while trying to upload file')
                 })
             newfile = self.get_modal_obj()()
             newfile.file_location = filetoupload['filename']
             newfile.file_label = secure_filename(upload_file.filename)
             newfile.siteid = siteid
             try:
                 db.session.add(newfile)
                 db.session.commit()
             except SQLAlchemyError:
                 db.session.rollback()
                 return jsonify({
                     'status':
                     None,
                     'msg':
                     _('Value already \
                             exists in the database for this file ')
                 })
             else:
                 return jsonify({
                     'status': 1,
                     'singleitem': newfile.to_dict(),
                     'msg': _('Uploaded new file')
                 })
     except:
         logger.exception("Fileupload exception")
         return jsonify({
             'status':
             '0',
             'msg':
             _('Error Occured While trying \
             to upload file')
         })
Example #7
0
    def delete(self, siteid, id):
        item = self.get_modal_obj().query.get(id)
        if item:
            try:
                item.delete()
            except SQLAlchemyError as exception:
                logger.exception('UserID:%s submited deletion call exception'\
                        %(current_user.id))
                return jsonify({'status':0,'data':{}, 'msg':_('Error while deleting %(name)s'\
                    ,name=self.get_name())})
            return jsonify({'status':1,'data':{}, 'msg':_('Successfully deleted %(name)s'\
                        ,name=self.get_name())})

        else:
            logger.debug('UserID:%s trying to delete unknown ID:%s of :%s'\
                    %(current_user.id,id,self.get_name()))
            return jsonify({
                'status':
                0,
                'data': {},
                'msg':
                _l('Unknown :%(name)s ID \
                    specified',
                   name=self.get_name())
            })
Example #8
0
    def put(self,id):
        ''' Need custom post here to handle to configure sitekey etc

        '''        
        item = self.get_modal_obj().query.get(id) 
        if item:
            itemform = self.get_form_obj()
            itemform.populate(item)
            if itemform.validate_on_submit(): 
                try:
                    item.populate_from_form(itemform)
                    item.save()
                    item.populate_from_dict(self.get_extrafields_modal())
                except SQLAlchemyError as exception:
                    current_app.logger.exception('UserID:%s submited form caused exception'\
                            %(current_user.id))
                    return jsonify({'status':0,'data':{}, 'msg':_('Error while updating %(name)s'\
                            ,name=self.get_name())}) 
                return jsonify({'status':1,'data':{}, 'msg':_('Successfully updated %(name)s'\
                            ,name=self.get_name())}) 

            else:
                current_app.logger.debug('UserID:%s submited form with errors:%s'\
                             %(current_user.id,get_form_errors(itemform)))            
                return jsonify({'status':0,'data':{}, 'msg':get_form_errors(itemform)}) 
        else:
            current_app.logger.debug('UserID:%s trying to update unknown ID:%s of :%s'\
                    %(current_user.id,id,self.get_name()))
            return jsonify({'status':0,'data':{}, 'msg':_('Unknown :%(name)s ID \
                    specified',name=self.get_name())})
Example #9
0
    def post(self):
        itemform = self.get_form_obj()
        itemform.populate()
        if itemform.validate_on_submit():
            try:
                item = self.get_modal_obj()
                item.populate_from_form(itemform)
                item.save()
                item.populate_from_dict(self.get_extrafields_modal())
            except IntegrityError as exception:
                logger.exception('UserID:%s submited form caused exception'\
                        %(current_user.id))
                return jsonify({'status':0,'data':{}, 'msg':_('Duplicate exists for the given values of %(name)s'\
                        ,name=self.get_name())})
            except SQLAlchemyError as exception:
                logger.exception('UserID:%s submited form caused exception'\
                        %(current_user.id))
                return jsonify({'status':0,'data':{}, 'msg':_('Error while creating %(name)s'\
                        ,name=self.get_name())})
            return jsonify({'status':1,'data':{}, 'msg':_('Successfully added %(name)s'\
                        ,name=self.get_name())})

        else:
            logger.debug('UserID:%s submited form with errors:%s'\
                         %(current_user.id,get_form_errors(itemform)))
            return jsonify({
                'status': 0,
                'data': {},
                'msg': get_form_errors(itemform)
            })
Example #10
0
class AdminManage(FlaskView):
    decorators = [login_required,admin_required]

    @classy_menu_item('.manage.admin', _('Admins'), order=0,
                        visible_when=admin_menu)
    @classy_menu_item('.manage', _('Manage'), order=1,icon='fa-cogs',
                        visible_when=admin_menu)
    def index(self):
        return render_template('core/admins.html')
Example #11
0
class MailsettingsForm(Form):
    mail_server         = TextField(_('Mail Server'))
    mail_port           = TextField(_('Mail Port'))
    mail_default_sender = TextField(_('Mail Default Sender'))    
    babel_locale        = SelectField(_('Default Language'),
                                choices=[('en','English'),('es','Spanish')])

    def populate(self):
        pass
Example #12
0
class SimpleLandingPageForm(Form):
    pagebgcolor1     = TextField(_('Page Background Color'))
    gridbgcolor     = TextField(_('Grid Background Color'))
    textcolor       = TextField(_('Text Color'))
    textfont        = SelectField('Select Font',coerce=int,default=2)
    def populate(self):
        #Font options
        fonts = [(idx,font) for idx,font in enumerate(font_list)]
        self.textfont.choices = fonts
Example #13
0
class AccountForm(Form):
    unifi_server    = TextField(_('Controller IP'),validators = [Required()])
    unifi_user      = TextField(_('Controller Username'),
                                validators = [Required()])
    unifi_pass      = PasswordField(_('Controller Password'),
                                validators = [Required()])
    unifi_port      = TextField(_('Controller Port'),
                                validators = [Required()])
    unifi_version   = SelectField(_('Controller API version'),
                                choices=[('v4','V4/V5')])

    def populate(self):
        pass
Example #14
0
class VoucherView(FlaskView):


    @classy_menu_item('.voucher.vouchers', _('View'), order=0,
                        visible_when=site_menu)
    @classy_menu_item('.voucher', _('Voucher'), order=7,icon='fa-money',
                        visible_when=site_menu)
    def index(self,siteid):
        decorators = [login_required,validate_site_ownership]

        voucherform = VoucherForm()
        voucherform.populate()
        
        return render_template('vouchers.html',voucherform=voucherform,
                             siteid=siteid)
Example #15
0
        def populate(self,wifisite=None):
            from unifispot.core.models import Client
            clients = Client.query.filter_by(account_id=current_user.account_id).all()
            self.client_id.choices = []
            for client in clients:
                self.client_id.choices.append((client.id,client.displayname))

            self.timezone.choices = [ (tz_name,tz_formated)for tz_offset, tz_name, tz_formated in zones.get_timezones() ]


            if not baseform:
                self.sitekey.choices = []
                #populate sitekey with available options if specific id is specified
                if wifisite and wifisite.backend_type:
                    #try to get available sitekeys
                    try:
                        module_path = current_app.config.get('MODULE_PATH', 'modules')
                        backend_module = ".".join([current_app.name, module_path,
                                                    wifisite.backend_type,'main'])
                        backend = importlib.import_module(backend_module)
                        sitekeys = getattr(backend,'get_sitekeys')(wifisite)
                    except:
                        flash(_('Error while getting sitelist. \
                                        Please check Controller settings'), 'danger')
                        current_app.logger.exception("Exception while trying to get sitekeys for :%s"\
                                        %wifisite.id)
                    else:
                        self.sitekey.choices = sitekeys
Example #16
0
class VoucherDesignView(FlaskView):
    @classy_menu_item('.voucher.design',
                      _('Design'),
                      order=1,
                      visible_when=site_menu)
    def index(self, siteid):
        decorators = [login_required, validate_site_ownership]

        voucherdesignform = VoucherDesignForm()
        voucherdesignform.populate()

        voucherfilesform = VoucherFilesForm()
        fakevoucher = Voucher(bytes_t=100,
                              voucher='1234567890',
                              duration_type=1,
                              duration_val=1,
                              speed_dl=256,
                              speed_ul=100)
        voucherdesign = Voucherdesign.query.filter_by(siteid=siteid).first()

        return render_template('voucher_designer.html',
                               voucherdesignform=voucherdesignform,
                               siteid=siteid,
                               voucherfilesform=voucherfilesform,
                               fakevoucher=fakevoucher,
                               voucherdesign=voucherdesign)
Example #17
0
class AccountManage(FlaskView):
    decorators = [login_required,admin_required]

    @classy_menu_item('.manage.settings', _('UniFi Settings'),visible_when=admin_menu)
    def index(self):
        settingsform = AccountForm()
        return render_template('core/unifi-settings.html',settingsform=settingsform)        
Example #18
0
 def validate(self):
     rv = Form.validate(self)
     if not rv:
         return False
     if self.password and (self.password.data != self.repassword.data):
         self.password.errors.append(_("Entered passwords didn't match"))
         return False
     return True
Example #19
0
def get_form_errors(form):
    """ Return form errors as string """
    form_errors = ""
    for field, errors in form.errors.items():
        for error in errors:
            form_errors = form_errors+ _("Error in the %(fieldname)s field - %(errors)s </br>",\
                 fieldname=getattr(form, field).label.text,errors=error)
    return form_errors
Example #20
0
class UserForm(Form):
    email       = TextField(_('Email'),validators = [Required()])
    displayname = TextField(_('Name'),validators = [Required()])
    password    = PasswordField(_('Password')) 
    repassword  = PasswordField(_('Confirm Password'))
    
    def populate(self):
        pass

    def validate(self):
        rv = Form.validate(self)
        if not rv:
            return False
        if self.password and (self.password.data != self.repassword.data):
            self.password.errors.append(_("Entered passwords didn't match"))
            return False
        return True
Example #21
0
class SiteDashboard(FlaskView):
    decorators = [login_required]


    @classy_menu_item('.sitedash', _('Dashboard'),icon='fa-home',
                            visible_when=site_menu,order=0)
    def index(self,siteid):
        return render_template('core/site-dashboard.html',siteid=siteid)           
Example #22
0
    def post(self):
        testemailform = TestEmailForm()
        if testemailform.validate_on_submit(): 
            try:   
                send_email("TEST EMAIL", body='Spotipo Test', html=None, 
                            recipients=[testemailform.sendto.data])
            except:
                current_app.logger.exception("Exception while sending test email")
                return jsonify({'status':0,'data':{}, 
                            'msg':_('Error while trying to send test email')}) 
            else:
                return jsonify({'status':1,'data':{}, 
                            'msg':_('Test mail send successfully')})

        else:        
            return jsonify({'status':0,'data':{}, 
                            'msg':get_form_errors(testemailform)})
Example #23
0
class GuestDataManage(FlaskView):
    decorators = [login_required]

    @classy_menu_item('.guestdata', _('Guests'),icon='fa-users',
                            visible_when=site_menu,order=3)
    def index(self,siteid):
        wifisite = Wifisite.query.get(siteid)
        return render_template('core/site-guestdata.html',siteid=siteid,
                                wifisite=wifisite) 
Example #24
0
 def get(self,id):        
     item = self.get_modal_obj()().query.get(id)    
     if item:
         return jsonify({'status':1,'data':item.to_dict()})   
     else:
         current_app.logger.debug('UserID:%s trying to access unknown ID:%s of :%s'\
                 %(current_user.id,id,self.get_name()))
         return jsonify({'status':0,'data':{}, 'msg':_('Unknown :%(name)s ID specified'\
                 ,name=self.get_name())})
Example #25
0
        def decorated_function(*args, **kwargs):
            wifisite    =  kwargs.get('wifisite')
            guesttrack  =  kwargs.get('guesttrack')
            guestdevice =  kwargs.get('guestdevice')
            loginconfig =  kwargs.get(lconfigstr)
            #get the function name used 
            fname = f.func_name
            #get and validated emailauth
            loginauth = AuthModel.query.filter_by(siteid=wifisite.id,
                            deviceid=guestdevice.id).first()
            if not loginauth:
                guestlog_debug('in :%s empty %s, creating default one'%(fname,
                            AuthModel),wifisite,guesttrack)
                loginauth = AuthModel(siteid=wifisite.id,deviceid=guestdevice.id,
                                        account_id=wifisite.account_id)
                loginauth.demo = guesttrack.demo
                loginauth.save()
            elif loginauth.is_blocked():
                flash(_("Looks like you have been blocked from using WiFi"),'danger')
                landingpage = Landingpage.query.filter_by(siteid=wifisite.id).first()
                return render_template('guest/%s/base_landing.html'%wifisite.template,\
                        wifisite=wifisite,landingpage=landingpage,trackid=guesttrack.trackid)                 
            elif guesttrack.is_not_demo() and \
                        loginauth.login_completed(loginconfig) and \
                        guest_auto_relogin_allowed(loginauth,loginconfig):
                if loginconfig.is_limited():
                    #email auth from a previous session,
                    #check if its valid still
                    starttime = loginconfig.get_limit_starttime()               

                    expired_url =url_for('unifispot.modules.%s.guest_override'%modname,
                                    trackid=guesttrack.trackid)

                    if not validate_loginauth_usage(wifisite,guesttrack,
                                loginconfig,loginauth,starttime):
                        return redirect(expired_url)
                else:
                    loginauth.time_limit = 480
                    loginauth.data_limit = 1000

                loginauth.state = LOGINAUTH_REPEATED
                loginauth.reset()
                loginauth.save()
                #update guesttrack   
                guesttrack.state        = GUESTTRACK_POSTRELOGIN
                guesttrack.loginauthid  = loginauth.id 
                guesttrack.updatestat(logintypestr,1)
                guesttrack.updatestat('relogin',1)
                guesttrack.save()

                guestlog_debug('%s guest   relogin '%modname,
                                    wifisite,guesttrack)
                return redirect_guest(wifisite,guesttrack)
                
            kwargs['loginauth'] = loginauth
            return f(*args, **kwargs)
Example #26
0
    def put(self, siteid, id):
        item = self.get_modal_obj()().query.get(id)
        if item:
            itemform = self.get_form_obj()
            itemform.populate()
            if itemform.validate_on_submit():
                try:
                    item.populate_from_form(itemform)
                    item.save()
                    item.populate_from_dict(self.get_extrafields_modal())
                except IntegrityError as exception:
                    logger.exception('UserID:%s submited form caused exception'\
                            %(current_user.id))
                    return jsonify({'status':0,'data':{}, 'msg':_('Duplicate exists for the given values of %(name)s'\
                            ,name=self.get_name())})
                except SQLAlchemyError as exception:
                    logger.exception('UserID:%s submited form caused exception'\
                            %(current_user.id))
                    return jsonify({'status':0,'data':{}, 'msg':_('Error while updating %(name)s'\
                            ,name=self.get_name())})
                return jsonify({'status':1,'data':{}, 'msg':_('Successfully updated %(name)s'\
                            ,name=self.get_name())})

            else:
                logger.debug('UserID:%s submited form with errors:%s'\
                             %(current_user.id,get_form_errors(itemform)))
                return jsonify({
                    'status': 0,
                    'data': {},
                    'msg': get_form_errors(itemform)
                })
        else:
            logger.debug('UserID:%s trying to update unknown ID:%s of :%s'\
                    %(current_user.id,id,self.get_name()))
            return jsonify({
                'status':
                0,
                'data': {},
                'msg':
                _l('Unknown :%(name)s ID \
                    specified',
                   name=self.get_name())
            })
Example #27
0
class MailOptionsManage(FlaskView):
    decorators = [login_required,admin_required]

    @classy_menu_item('.manage.options', _('General Settings'),
                                visible_when=admin_menu)
    def index(self):
        mailsettingsform = MailsettingsForm()
        testemailform = TestEmailForm()
        return render_template('core/mailsettings.html',
                        mailsettingsform=mailsettingsform,testemailform=testemailform)        
Example #28
0
class WifisiteManage(FlaskView):
    decorators = [login_required,admin_required,validate_site_ownership]

    @classy_menu_item('.settings', _('Settings'),icon='fa-cogs',
                            visible_when=admin_site_menu,order=1)
    def index(self,siteid):
        wifisite = Wifisite.query.get(siteid)
        siteform = get_wifisite_form()
        siteform.populate(wifisite)
        return render_template('core/site-settings.html',siteid=siteid,
                                siteform=siteform)        
Example #29
0
def get_multilanding_html(wifisite,guesttrack):
    '''This method needs to be added to all login plugins
        Called by redirec_guest when rendering multi landing page
        return HTML for buttons or otherwise that needs to be rendered
        on the multilanding.html page

    '''
    loginurl = url_for('unifispot.modules.facebook.guest_login',
                            trackid=guesttrack.trackid)
    return '''<p> 
                <a class="btn btn-block btn-social btn-facebook" href="%s?from_multilanding=1" id="facebook-login">
                <span class="fa fa-facebook"></span><strong>'''%loginurl+_('Login with Facebook')+ ''' </strong>
Example #30
0
def guest_login(trackid,
                guesttrack,
                wifisite,
                guestdevice,
                voucherconfig,
                voucherauth,
                voucherid=None):
    ''' Function to called if the site is configured with payment login    
    
    '''
    #show the configured landing page
    voucher_form = generate_voucherform(voucherconfig)
    if voucher_form.validate_on_submit():
        voucher = Voucher.query.filter(
            and_(Voucher.siteid == wifisite.id,
                 Voucher.voucher == voucher_form.voucher.data)).first()
        if voucher:
            #check and update validity of paymentaccount
            (status, msg) = voucher.check_and_update_validity(voucherauth)
            if status:
                #assign a guest based on form
                newguest = assign_guest_entry(wifisite,
                                              guesttrack,
                                              form=voucher_form)
                #update guesttrack
                guesttrack.state = GUESTTRACK_POSTLOGIN
                guesttrack.loginauthid = voucherauth.id
                guesttrack.updatestat('auth_voucher', 1)
                guesttrack.save()
                #update guestdevice
                guestdevice.guestid = newguest.id
                guestdevice.save()
                #update guest
                newguest.demo = guesttrack.demo
                newguest.devices.append(guestdevice)
                newguest.save()
                guestlog_debug('voucher_login  new guest track ID:%s'%\
                                newguest.id,wifisite,guesttrack)
                return redirect_guest(wifisite, guesttrack)
            else:
                flash(msg, 'danger')
                guestlog_warn('in voucher.guest_login limit expired', wifisite,
                              guesttrack)
        else:
            #transaction failed! display msg
            flash(_('Wrong voucher entry'), 'danger')
            guestlog_warn('in voucher.guest_login wrong voucher id', wifisite,
                          guesttrack)

    landingpage = Landingpage.query.filter_by(siteid=wifisite.id).first()
    return render_template('guest/%s/voucher_landing.html'%wifisite.template,\
            wifisite=wifisite,landingpage=landingpage,voucher_form=voucher_form,
            trackid=trackid)