Beispiel #1
0
def set_your_pin(skicall):
    """Given the four characters of a pin, for the current logged in user sets it"""

    # called from responder 8101

    username = skicall.call_data['username']
    user_id = skicall.call_data['user_id']

    pin1 = skicall.call_data['newpin', 'pin1']
    if not pin1 or (len(pin1) != 1):
        raise FailPage('Invalid PIN', widget='newpin')
    pin2 = skicall.call_data['newpin', 'pin2']
    if not pin2 or (len(pin2) != 1):
        raise FailPage('Invalid PIN', widget='newpin')
    pin3 = skicall.call_data['newpin', 'pin3']
    if not pin3 or (len(pin3) != 1):
        raise FailPage('Invalid PIN', widget='newpin')
    pin4 = skicall.call_data['newpin', 'pin4']
    if not pin4 or (len(pin4) != 1):
        raise FailPage('Invalid PIN', widget='newpin')
    if database_ops.set_pin(skicall.project, user_id,
                            [pin1, pin2, pin3, pin4]):
        space_pin = pin1 + ' ' + pin2 + ' ' + pin3 + ' ' + pin4
        skicall.page_data[
            'showadminpin',
            'para_text'] = "New PIN for user %s is %s" % (username, space_pin)
    else:
        raise FailPage('Unable to set new PIN into database', widget='newpin')
Beispiel #2
0
def dumpdatabase(skicall):
    """Creates an encrypted database dump to file backup.bak"""
    # To decrypt the file
    # gpg2 --batch --passphrase "passphrase" -d backup.bak

    # get the database dump
    dump = database_ops.stringdump()
    if dump is None:
        raise FailPage("Unable to obtain backup from the database")
    # create backup file location under static so it can be served
    backupfile = os.path.join(skicall.call_data["projectfiles"],
                              skicall.project, "static", "backup.bak")

    # remove any existing backup file
    if os.path.exists(backupfile):
        os.unlink(backupfile)

    homedir = os.path.join(skicall.call_data["projectfiles"], skicall.project)

    # call gpg2 to encrypt the dump

    args = ["gpg2"]

    args.append("--batch")
    args.append("-c")
    args.append("--homedir")
    args.append(homedir)
    args.append("--passphrase")
    args.append(cfg.get_backup_passphrase())
    args.append("-o")
    args.append(backupfile)
    try:
        subprocess.run(args, input=dump.encode("utf-8"), timeout=2)
    except:
        raise FailPage("Unable to create backup file")
Beispiel #3
0
def make_pin(skicall):
    """Create a PIN for an edited user and set user to Admin role"""

    # called by responders 3160 and 3170

    try:
        edited_user_id = int(skicall.call_data['newadminpin'])
    except:
        raise FailPage('Invalid edited user')

    if edited_user_id == 1:
        raise FailPage('Cannot create random PIN for Admin')

    edited_user = database_ops.get_user_from_id(edited_user_id)
    # edited user should be (username, role, email, member)
    if not edited_user:
        raise FailPage('Invalid user')

    skicall.call_data['edited_user_id'] = edited_user_id
    # generate new pin
    new_pin = database_ops.make_admin(skicall.project, edited_user_id)
    if new_pin:
        space_pin = ' '.join(c for c in new_pin)
        skicall.page_data['showadminpin',
                          'para_text'] = 'New PIN for user %s is %s' % (
                              edited_user[0], space_pin)
    else:
        raise FailPage('Failed database access, unable to set PIN')
Beispiel #4
0
def set_pwr_output01(skicall):
    "Sets database from data submitted via widgfields"
    # Get default value on power up
    if ('output01_default', 'radio_checked') in skicall.call_data:
        default_on_pwr = skicall.call_data[('output01_default',
                                            'radio_checked')]
        if (default_on_pwr
                == 'True') or (default_on_pwr
                               == 'true') or (default_on_pwr is True):
            default_on_pwr = True
        else:
            default_on_pwr = False
    else:
        raise FailPage(message="invalid input")
    # Get the onpower enabled checkbox result
    if ('output01_check', 'checkbox') in skicall.call_data:
        onpower = skicall.call_data[('output01_check', 'checkbox')]
        if (onpower == 'True') or (onpower == 'true') or (onpower is True):
            onpower = True
        else:
            onpower = False
    else:
        raise FailPage(message="invalid input")
    # set result into database
    if not database_ops.set_power_values('output01', default_on_pwr, onpower):
        raise FailPage(message="Error: Failed to write to database.")
Beispiel #5
0
def json_confirm_delete_member(skicall):
    "Populates and displays confirm box"
    # Called by responder 3075
    if ('users', 'get_field2_1') in skicall.call_data:
        user_id = int(skicall.call_data['users', 'get_field2_1'])
    else:
        raise FailPage("User ID not given.")
    user = database_ops.get_user_from_id(user_id)
    if user is None:
        raise FailPage("User ID not recognised.")
    if ('users', 'get_field2_2') in skicall.call_data:
        try:
            offset = int(skicall.call_data['users', 'get_field2_2'])
        except:
            offset = 0
    else:
        offset = 0
    skicall.page_data['confirm', 'hide'] = False
    skicall.page_data['confirm',
                      'para_text'] = "Confirm delete user %s" % user[0]
    skicall.page_data['confirm', 'get_field1_1'] = 'member'
    skicall.page_data['confirm', 'get_field1_2'] = str(offset)
    skicall.page_data['confirm', 'get_field2_1'] = 'member'
    skicall.page_data['confirm', 'get_field2_2'] = str(offset)
    skicall.page_data['confirm', 'get_field2_3'] = str(user_id)
Beispiel #6
0
def set_number(skicall):
    "Responds to a submission to set a number vector"
    rconn = skicall.proj_data["rconn"]
    redisserver = skicall.proj_data["redisserver"]
    devicename, propertyindex, sectionindex, propertyname = _check_received_data(
        skicall, 'setnumber')
    # get set of element names for this property
    names = tools.elements(rconn, redisserver, propertyname, devicename)
    if not names:
        raise FailPage("Error parsing data")
    # initially set all element number values to be empty
    valuedict = {nm: '' for nm in names}
    received_data = skicall.submit_dict['received_data']
    if (propertyindex, 'nvinputtable', 'inputdict') in received_data:
        value = received_data[
            propertyindex, 'nvinputtable',
            'inputdict']  # dictionary of base 64 encoded names:values submitted
        for safekey, vl in value.items():
            nm = _fromsafekey(safekey)
            if nm in valuedict:
                valuedict[nm] = vl
            else:
                raise FailPage("Error parsing data")
        data_sent = tools.newnumbervector(rconn, redisserver, propertyname,
                                          devicename, valuedict)
        # print(data_sent)
        if not data_sent:
            raise FailPage("Error sending data")
    else:
        skicall.call_data["status"] = "Unable to parse received data"
        return
    set_state(skicall, sectionindex, "Busy")
    skicall.call_data[
        "status"] = f"Change to property {propertyname} has been submitted"
Beispiel #7
0
def upload(skicall):
    "Uploads a backup file and restores the membership database"

    # Called by responder 3030

    if (('upload', 'action') not in skicall.call_data) or (
            not skicall.call_data['upload', 'action']):
        raise FailPage("Invalid file.", widget='upload')

    homedir = os.path.join(skicall.call_data["projectfiles"], skicall.project)

    uploaded_data = skicall.call_data['upload', 'action']
    args = ["gpg2"]
    args.append("--batch")
    args.append("-d")
    args.append("--homedir")
    args.append(homedir)
    args.append("--passphrase")
    args.append(cfg.get_backup_passphrase())
    try:
        sp = subprocess.run(args,
                            input=uploaded_data,
                            stdout=subprocess.PIPE,
                            timeout=2)
        database_ops.restoredatabase(sp.stdout.decode('utf-8'))
    except:
        raise FailPage('Restore Failed.', widget='upload')
Beispiel #8
0
def secure2_access(skicall):
    """Raises an error if no valid cookie received for secure2 page"""
    received_cookies = skicall.received_cookies
    project = skicall.project + "2"
    if project not in received_cookies:
        raise FailPage(message="You are not logged in")
    if received_cookies[project] != "secure2":
        raise FailPage(message="You are not logged in")
Beispiel #9
0
def submit_add_user(skicall):
    "Adds a user"
    # Called from responder 3011
    newuser = skicall.call_data['newuser', 'input_text']
    if not newuser:
        raise FailPage("The new username is missing.")
    # check newuser does not currently exist in database
    if database_ops.get_user_id(newuser):
        # user id found for this user
        raise FailPage("This username already exits.")
    if skicall.call_data['newrole', 'selectvalue'] == "Admin":
        # role initially set to member, changed to admin when a PIN is input
        newrole = 'MEMBER'
    elif skicall.call_data['newrole', 'selectvalue'] == "Member":
        newrole = 'MEMBER'
    else:
        newrole = "GUEST"
    newmember = skicall.call_data['newmember', 'input_text']
    if not newmember:
        newmember = "0000"
    newemail = skicall.call_data['newemail', 'input_text']
    if not newemail:
        newemail = None
    result = database_ops.adduser(newuser, newrole, newmember, newemail)
    if not result:
        raise FailPage("Unable to add new user")
    new_user_id, password = result
    # user added with new user id
    skicall.call_data['edited_user_id'] = new_user_id
    skicall.page_data['showresult', 'show'] = True
    skicall.page_data[
        'pararesult',
        'para_text'] = "User %s added with password %s" % (newuser, password)
    if (('sendemail', 'checkbox') in skicall.call_data) and (
            skicall.call_data['sendemail', 'checkbox'] == 'send'):
        if newemail:
            message = """You have been registered with %s,
with username %s and password %s
Please log on and change the password as soon as possible.""" % (
                skicall.call_data['org_name'], newuser, password)
            if send_email.sendmail(
                    newemail, "Automated message from %s" %
                (skicall.call_data['org_name'], ), message):
                skicall.page_data[
                    'pararesult',
                    'para_text'] += "\nEmail with password sent to %s" % (
                        newemail, )
            else:
                skicall.page_data[
                    'pararesult',
                    'para_text'] += "\nEmail not sent (failed to contact smtp server)."
        else:
            skicall.page_data[
                'pararesult',
                'para_text'] += "\nEmail not sent (no email address given)."
    if skicall.call_data['newrole', 'selectvalue'] == "Admin":
        # If Admin go to set pin page
        raise GoTo(target=3615, clear_submitted=True, clear_page_data=False)
Beispiel #10
0
def submit_password(skicall):
    "If password not ok, raise FailPage"
    if 'password' not in skicall.call_data:
        raise FailPage("Invalid password!")
    password = skicall.call_data['password']
    if not password:
        raise FailPage("Invalid password!")
    if not check_password(password):
        raise FailPage("Invalid password!")
Beispiel #11
0
def _svgplot(commands):
    "Call gnuplot with commands, returns svg"
    commandstring = "set terminal svg;" + ";".join(commands)
    args = ["gnuplot", "-e", commandstring]
    try:
        result = subprocess.check_output(args, timeout=2)
    except:
        raise FailPage()
    if not result:
        raise FailPage()
    return result
Beispiel #12
0
def edituser(skicall):
    "Sets edited_user_id for fill_edituser_template responder"
    # Called by responder 3110
    if ('users', 'get_field1_1') in skicall.call_data:
        try:
            edited_user_id = int(skicall.call_data['users', 'get_field1_1'])
        except:
            raise FailPage("User ID not recognised.")
    else:
        raise FailPage("User ID not recognised.")
    skicall.call_data['edited_user_id'] = edited_user_id
Beispiel #13
0
def edit_username(skicall):
    "Changes username"
    # Called by responder 3120
    if ('username', 'hidden_field1') in skicall.call_data:
        try:
            edited_user_id = int(skicall.call_data['username',
                                                   'hidden_field1'])
        except:
            raise FailPage("User ID not recognised.")
    else:
        raise FailPage("User ID not recognised.")
    skicall.call_data['edited_user_id'] = edited_user_id
    if edited_user_id == 1:
        raise FailPage("Cannot change name of special Admin user")
    new_username = skicall.call_data['username', 'input_text']
    if not new_username:
        skicall.page_data['username', 'set_input_errored'] = True
        raise FailPage(message="Invalid username")
    user = database_ops.get_user_from_id(edited_user_id)
    if user is None:
        raise FailPage(message="The user has not been recognised")
    # user is (username, role, email, member)
    if user[0] == new_username:
        raise FailPage(message="The username has not changed")
    existinguser = database_ops.get_user_from_username(new_username)
    if existinguser is not None:
        raise FailPage(message="The new username already exists")
    if not database_ops.set_username(edited_user_id, new_username):
        raise FailPage("Database operation failed.")
    # username changed
    skicall.page_data['username', 'set_input_accepted'] = True
    skicall.page_data['showresult', 'show'] = True
    skicall.page_data[
        'pararesult',
        'para_text'] = "Username changed to %s" % (new_username, )
Beispiel #14
0
def add_message(skicall):
    "Adds a message"

    # called by responder 3002

    try:
        message = skicall.call_data['setstatus', 'input_text']
        username = skicall.call_data['username']
    except:
        raise FailPage('Invalid settings.')

    if database_ops.set_message(username, message):
        skicall.page_data['messageresult', 'para_text'] = "Message set."
    else:
        raise FailPage("Database access failure")
Beispiel #15
0
def set_cookie(skicall):
    """set cookie for login access"""

    # After a user has tried to login and his password successfully checked then
    # this function is called from responder 5502 which is of type 'SetCookies'
    # a cookie is generated, set into the database and sent to the user browser
    # so future access is immediate when a received cookie is compared with the database cookie

    # set a cookie for cookie key 'project2'
    project = skicall.project
    user_id = skicall.call_data['user_id']
    # generate a cookie string
    ck_string = uuid.uuid4().hex
    ck_key = project + "2"
    cki = cookies.SimpleCookie()
    cki[ck_key] = ck_string
    # twelve hours expirey time
    cki[ck_key]['max-age'] = 43200
    # set root project path
    url_dict = skicall.projectpaths()
    cki[ck_key]['path'] = url_dict[project]
    # and set the cookie string into database
    status = redis_ops.set_cookie(ck_string, user_id,
                                  skicall.call_data.get("rconn_1"))
    if not status:
        raise FailPage(message="Unable to access redis database")
    return cki
Beispiel #16
0
def server_settings(skicall):
    """Populates the server settings page"""

    # called by responder 3020

    ##### SMTP settings
    smtpserver = database_ops.get_emailserver()
    if not smtpserver:
        raise FailPage('Database access failure.')
    emailserver, no_reply, starttls = smtpserver
    if emailserver:
        skicall.page_data['emailserver', 'input_text'] = emailserver
    if no_reply:
        skicall.page_data['no_reply', 'input_text'] = no_reply
    if starttls:
        skicall.page_data['starttls', 'checked'] = True
    else:
        skicall.page_data['starttls', 'checked'] = False
    userpass = database_ops.get_emailuserpass()
    if not userpass:
        emailusername = ''
        emailpassword = ''
    else:
        emailusername, emailpassword = userpass
    if emailusername:
        skicall.page_data['emailuser', 'input_text'] = emailusername
    if emailpassword:
        skicall.page_data['emailpassword', 'input_text'] = emailpassword
Beispiel #17
0
def set_blob(skicall):
    "Responds to a submission to upload a blob"
    rconn = skicall.proj_data["rconn"]
    redisserver = skicall.proj_data["redisserver"]
    # device name should already be set in ident_data with skicall.call_data["device"]
    rxdata = skicall.call_data['upblob', 'hidden_field1']
    data = _fromsafekey(rxdata)
    propertyname, sectionindex, elementname = data.split("\n")
    devicename = skicall.call_data["device"]
    rxfile = skicall.call_data['upblob', "action"]
    lenrxfile = len(rxfile)
    fpath = skicall.call_data['upblob', "submitbutton"]
    fextension = Path(
        fpath
    ).suffixes  #  fextension is something like ['.tar'] or ['tar', '.gz']
    fext = ''
    for f in fextension:
        fext += f
    if skicall.call_data['zipbox', "checkbox"] == "zipfile":
        # zip the file and add .gz extension
        rxfile = gzip.compress(rxfile)
        fext = fext + ".gz"
    data_sent = tools.newblobvector(rconn, redisserver, propertyname,
                                    devicename, [{
                                        'name': elementname,
                                        'size': lenrxfile,
                                        'format': fext,
                                        'value': rxfile
                                    }])
    if not data_sent:
        raise FailPage("Error sending data")
    set_state(skicall, sectionindex, "Busy")
    skicall.call_data["status"] = f"""The file has been submitted:
def submit_data(skicall):
    "This function is called when a Responder wishes to submit data for processing in some manner"
    if skicall.submit_list[0] == 'index':
        _options(skicall)
    elif skicall.submit_list[0] == 'test1':
        _test1(skicall)
    elif skicall.submit_list[0] == 'test2':
        raise FailPage("This error is shown in the DropDown1 error paragraph")
    return
Beispiel #19
0
def _check_received_data(skicall, setstring):
    """setstring should be one of 'settext', 'setswitch', 'setnumber'
       Returns devicename, propertyindex, sectionindex, propertyname
       where devicename is the device
             propertyindex is, for example, 'property_4'
             sectionindex is, for example, '4'
             propertyname is the property"""

    if skicall.ident_data:
        devicename = skicall.call_data["device"]
    else:
        raise FailPage("Unknown device")

    received_data = skicall.submit_dict['received_data']

    # example of  received_data
    #
    # {
    # ('property_4', 'settext', 'sectionindex'): '4',
    # ('property_4', 'settext', 'propertyname'): 'DEVICE_PORT',
    # ('property_4', 'tvtexttable', 'inputdict'): {'PORT': '/dev/ttyUSB0'}
    # }

    try:
        keys = list(received_data.keys())
        propertyindex = keys[0][0]
        p, sectionindex = propertyindex.split("_")
    except:
        raise FailPage("Invalid data")

    if p != "property":
        raise FailPage("Invalid data")

    if (propertyindex, setstring, 'sectionindex') not in received_data:
        raise FailPage("Invalid data")

    # sectionindex should be equal to the provided sectionindex
    if received_data[(propertyindex, setstring,
                      'sectionindex')] != sectionindex:
        raise FailPage("Invalid data")

    propertyname = received_data[propertyindex, setstring, 'propertyname']

    return devicename, propertyindex, sectionindex, propertyname
Beispiel #20
0
def make_password(skicall):
    "Generates and sets a password for edited user"
    # Called by responder 3135
    if ('newpassword', 'hidden_field1') in skicall.call_data:
        try:
            edited_user_id = int(skicall.call_data['newpassword',
                                                   'hidden_field1'])
        except:
            raise FailPage("User ID not recognised.")
    else:
        raise FailPage("User ID not recognised.")
    skicall.call_data['edited_user_id'] = edited_user_id
    if edited_user_id == 1:
        raise FailPage("Cannot change password of special Admin user")
    new_password = database_ops.new_password(edited_user_id)
    if not new_password:
        raise FailPage("Database operation failed.")
    # password changed
    skicall.page_data['showresult', 'show'] = True
    skicall.page_data[
        'pararesult',
        'para_text'] = "New password created for this user, and set to %s" % (
            new_password, )
    user_email = database_ops.get_email(edited_user_id)
    if user_email and (
        ('emailpassword', 'checkbox') in skicall.call_data) and (
            skicall.call_data['emailpassword', 'checkbox'] == 'emailpassword'):
        message = """A new password has been created for access to %s,
      Password:  %s
Please log on and change the password as soon as possible.""" % (
            skicall.call_data['org_name'], new_password)
        if send_email.sendmail(
                user_email, "Automated message from %s" %
            (skicall.call_data['org_name'], ), message):
            skicall.page_data[
                'pararesult',
                'para_text'] += "\nEmail with password sent to %s" % (
                    user_email, )
        else:
            skicall.page_data[
                'pararesult',
                'para_text'] += "\nEmail not sent (failed to contact smtp server)."
Beispiel #21
0
def retrieve_widgets_list(skicall):
    "this call is to retrieve data for listing widgets in a module"

    call_data = skicall.call_data
    page_data = skicall.page_data

    if 'module' in call_data:
        module_name = call_data['module']
    else:
        raise FailPage("Module not identified")

    modules_tuple = editwidget.widget_modules()

    if module_name not in modules_tuple:
        raise FailPage("Module not identified")

    # set module into call_data
    call_data['module'] = module_name

    call_data['headtext'] = module_name
    page_data[('moduledesc',
               'textblock_ref')] = 'widgets.' + module_name + '.module'

    # table of widgets

    # col 0 is the visible text to place in the link,
    # col 1 is the get field of the link
    # col 2 is the get field of the link
    # col 3 is the reference string of a textblock to appear in the column adjacent to the link
    # col 4 is text to appear if the reference cannot be found in the database
    # col 5 normally empty string, if set to text it will replace the textblock

    widget_list = editwidget.widgets_in_module(module_name)
    contents = []
    for widget in widget_list:
        ref = ".".join(("widgets", module_name, widget.classname))
        notfound = 'Textblock reference %s not found' % ref
        classname = widget.classname
        contents.append([classname, classname, module_name, ref, notfound, ''])

    page_data[("widgets", "link_table")] = contents
Beispiel #22
0
def check_login(skicall):
    """The user fills in the username and password widgets on the login template page and
         then submits the data to the responder which calls this function.
         This checks username and password against the member database and raises failpage
         if username and password are not ok, if ok populates call_data"""

    # Called by responder id 5002

    skicall.call_data['loggedin'] = False
    skicall.call_data['authenticated'] = False

    username = skicall.call_data['login', 'input_text1']
    password = skicall.call_data['login', 'input_text2']
    str_rnd = skicall.call_data['login', 'hidden_field1']

    # check hidden random number is still valid
    if not str_rnd:
        raise FailPage(message="Invalid input")
    try:
        int_rnd = int(str_rnd)
    except:
        raise FailPage(message="Invalid input")

    rnd = redis_ops.two_min_numbers(rndset=0,
                                    rconn=skicall.call_data.get("rconn_0"))
    # rnd is a tuple of two valid random numbers
    # rnd[0] for the current 2 minute time slot
    # rnd[1] for the previous 2 minute time slot
    # int_rnd must be one of these to be valid
    if rnd[0] is None:
        raise ServerError(message="Database access failure")
    if int_rnd not in rnd:
        raise FailPage(message="Login page expired, please try again.")

    if not username:
        raise FailPage(message="Login fail: missing username", widget='login')
    if not password:
        raise FailPage(message="Login fail: missing password", widget='login')
    if not database_ops.check_password(username, password):
        raise FailPage(message="Login fail: invalid username-password",
                       widget='login')

    # password ok, get user information
    user = database_ops.get_user_from_username(username)
    # user is a tuple of (user_id, role, email, member) or None if the username is not found

    if user is None:
        # something wrong, unable to get user information
        raise FailPage(message="Login Fail: unable to retrieve user details",
                       widget='login')

    # login ok, populate call_data and return
    skicall.call_data['user_id'] = user[0]
    skicall.call_data['role'] = user[1]
    skicall.call_data['username'] = username
    skicall.call_data['loggedin'] = True
Beispiel #23
0
def set_password(skicall):
    """Check password given, and set it into the database"""
    oldpassword = skicall.call_data['oldpassword', 'input_text']
    newpassword1 = skicall.call_data['newpassword1', 'input_text']
    newpassword2 = skicall.call_data['newpassword2', 'input_text']
    if (not oldpassword) or (not newpassword1) or (not newpassword2):
        raise FailPage(
            message="Missing data, all fields are required. Please try again.",
            widget='accesspassword')
    if newpassword1 != newpassword2:
        raise FailPage(
            message="The new password fields are not equal. Please try again.",
            widget='accesspassword')
    if oldpassword == newpassword1:
        raise FailPage(
            message=
            "The new and current passwords must be different. Please try again.",
            widget='accesspassword')
    if len(newpassword1) < 4:
        raise FailPage(
            message="Four characters or more please. Please try again.",
            widget='accesspassword')
    if not login.check_password(oldpassword):
        raise FailPage(message="Invalid current password. Please try again.",
                       widget='accesspassword')
    # password ok, now set it
    user = database_ops.get_access_user()
    if not database_ops.set_password(user, newpassword1):
        raise FailPage(message="Sorry, database access failure.",
                       widget='accesspassword')
    skicall.page_data['passwordset', 'show_para'] = True
Beispiel #24
0
def edit_member_number(skicall):
    "Sets membership number and edited_user_id for fill_edituser_template responder"
    # Called by responder 3125
    if ('member', 'hidden_field1') in skicall.call_data:
        try:
            edited_user_id = int(skicall.call_data['member', 'hidden_field1'])
        except:
            raise FailPage("User ID not recognised.")
    else:
        raise FailPage("User ID not recognised.")
    skicall.call_data['edited_user_id'] = edited_user_id
    if edited_user_id == 1:
        raise FailPage("Cannot change membership number of special Admin user")
    new_member_number = skicall.call_data['member', 'input_text']
    user = database_ops.get_user_from_id(edited_user_id)
    if user is None:
        raise FailPage(message="The user has not been recognised")
    # user is (username, role, email, member)
    if user[3] == new_member_number:
        raise FailPage(message="The membership number has not changed")
    if not database_ops.set_membership_number(edited_user_id,
                                              new_member_number):
        raise FailPage("Database operation failed.")
    # membership number changed
    skicall.page_data['member', 'set_input_accepted'] = True
    skicall.page_data['showresult', 'show'] = True
    skicall.page_data['pararesult',
                      'para_text'] = "Membership number changed to %s" % (
                          new_member_number, )
Beispiel #25
0
def edit_email(skicall):
    "Sets email and edited_user_id for fill_edituser_template responder"
    # Called by responder 3130
    if ('email', 'hidden_field1') in skicall.call_data:
        try:
            edited_user_id = int(skicall.call_data['email', 'hidden_field1'])
        except:
            raise FailPage("User ID not recognised.")
    else:
        raise FailPage("User ID not recognised.")
    skicall.call_data['edited_user_id'] = edited_user_id
    if edited_user_id == 1:
        raise FailPage("Cannot change email of special Admin user")
    new_email = skicall.call_data['email', 'input_text']
    user = database_ops.get_user_from_id(edited_user_id)
    if user is None:
        raise FailPage(message="The user has not been recognised")
    # user is (username, role, email, member)
    if user[2] == new_email:
        raise FailPage(message="The email address has not changed")
    if not database_ops.set_email(edited_user_id, new_email):
        raise FailPage("Database operation failed.")
    # email changed
    skicall.page_data['email', 'set_input_accepted'] = True
    skicall.page_data['showresult', 'show'] = True
    if new_email:
        skicall.page_data['pararesult',
                          'para_text'] = "Email changed to %s" % (new_email, )
    else:
        skicall.page_data['pararesult', 'para_text'] = "No email set"
Beispiel #26
0
def fill_generate_pin_template(skicall):
    """Fills the template page to generate a PIN for an edited user, this page is called when a user role
          is changed to Admin"""

    # called by responder 3615

    if not 'edited_user_id' in skicall.call_data:
        raise FailPage('Invalid user')
    edited_user_id = skicall.call_data['edited_user_id']

    if edited_user_id == 1:
        raise FailPage('This function is not available for this user.')

    edited_user = database_ops.get_user_from_id(edited_user_id)
    # edited user should be (username, role, email, member)
    if not edited_user:
        raise FailPage('Invalid user')

    skicall.page_data['pagetop',
                      'para_text'] = "Set Administrative access PIN for %s" % (
                          edited_user[0], )
    skicall.page_data['newadminpin', 'get_field1'] = str(edited_user_id)
Beispiel #27
0
def fill_edituser_template(skicall):
    "Populates the edituser template page"
    # Called by responder 3605
    edited_user_id = skicall.call_data['edited_user_id']
    str_edited_user_id = str(edited_user_id)
    user = database_ops.get_user_from_id(edited_user_id)
    # user is (username, role, email, member)
    if user is None:
        raise FailPage("User ID not recognised.")
    skicall.page_data['usertitle', 'para_text'] = "User %s" % (user[0], )
    # role
    skicall.page_data['role', 'option_list'] = ['Member', 'Admin', 'Guest']
    skicall.page_data['role', 'hidden_field1'] = str_edited_user_id
    if user[1] == "ADMIN":
        skicall.page_data['role', 'selectvalue'] = 'Admin'
        skicall.page_data['current_role', 'para_text'] = 'Current role: Admin'
    elif user[1] == "MEMBER":
        skicall.page_data['role', 'selectvalue'] = 'Member'
        skicall.page_data['current_role', 'para_text'] = 'Current role: Member'
    else:
        skicall.page_data['role', 'selectvalue'] = 'Guest'
        skicall.page_data['current_role', 'para_text'] = 'Current role: Guest'
    if edited_user_id == skicall.call_data['user_id']:
        skicall.page_data['role', 'disabled'] = True
    # username
    skicall.page_data['username', 'input_text'] = user[0]
    skicall.page_data['username', 'hidden_field1'] = str_edited_user_id
    # membership number
    if user[3]:
        skicall.page_data['member', 'input_text'] = user[3]
        skicall.page_data[
            'current_member',
            'para_text'] = 'Current membership number: %s' % (user[3], )
    else:
        skicall.page_data['member', 'input_text'] = ''
        skicall.page_data['current_member',
                          'para_text'] = 'Current membership number:'
    skicall.page_data['member', 'hidden_field1'] = str_edited_user_id
    # email
    if user[2]:
        skicall.page_data['email', 'input_text'] = user[2]
        skicall.page_data['current_email',
                          'para_text'] = 'Current email: %s' % (user[2], )
        skicall.page_data['emailpassword', 'checked'] = True
    else:
        skicall.page_data['email', 'input_text'] = ''
        skicall.page_data['current_email', 'para_text'] = 'Current email:'
        skicall.page_data['emailpassword', 'checked'] = False
    skicall.page_data['email', 'hidden_field1'] = str_edited_user_id
    # generate new password
    skicall.page_data['newpassword', 'hidden_field1'] = str_edited_user_id
Beispiel #28
0
def confirm_delete_user(skicall):
    "Populates and displays confirm box"
    # Called by responder 3060
    if ('users', 'get_field2_1') in skicall.call_data:
        user_id = int(skicall.call_data['users', 'get_field2_1'])
    else:
        raise FailPage("User ID not given.")
    user = database_ops.get_user_from_id(user_id)
    if user is None:
        raise FailPage("User ID not recognised.")
    if ('users', 'get_field2_2') in skicall.call_data:
        offset = int(skicall.call_data['users', 'get_field2_2'])
    else:
        offset = 0
    show_edit_users_page(skicall.page_data, offset=offset, names=True)
    skicall.page_data['confirm', 'hide'] = False
    skicall.page_data['confirm',
                      'para_text'] = "Confirm delete user %s" % user[0]
    skicall.page_data['confirm', 'get_field1_1'] = 'username'
    skicall.page_data['confirm', 'get_field1_2'] = str(offset)
    skicall.page_data['confirm', 'get_field2_1'] = 'username'
    skicall.page_data['confirm', 'get_field2_2'] = str(offset)
    skicall.page_data['confirm', 'get_field2_3'] = str(user_id)
Beispiel #29
0
def set_server_email_settings(skicall):
    """Sets the smtp settings in the database"""

    # called by responder 3021

    try:
        emailuser = skicall.call_data['emailuser', 'input_text']
        emailpassword = skicall.call_data['emailpassword', 'input_text']
        emailserver = skicall.call_data['emailserver', 'input_text']
        no_reply = skicall.call_data['no_reply', 'input_text']
        starttls = skicall.call_data['starttls', 'checkbox']
    except:
        raise FailPage('Invalid settings.', widget='emailsettings')
    if starttls == 'checked':
        starttls = True
    else:
        starttls = False
    if database_ops.set_emailserver(emailuser, emailpassword, emailserver,
                                    no_reply, starttls):
        skicall.page_data['emailsettings', 'show_para'] = True
    else:
        raise FailPage('Unable to set smtp server settings into database',
                       widget='emailsettings')
def submit_data(skicall):
    "This function is called when a Responder wishes to submit data for processing in some manner"
    if skicall.ident_list[-1] == (PROJECT, 10):
        # this call is to checklogin from the login page
        skicall.call_data['authenticate'] = False
        username = skicall.proj_data["username"]
        if (("login", "input_text1") in skicall.call_data) and (
                skicall.call_data["login", "input_text1"] == username):
            if ("login", "input_text2") in skicall.call_data:
                password = skicall.call_data["login", "input_text2"]
                hashed = _hash_password(username, password)
                if hashed == skicall.proj_data["password"]:
                    skicall.call_data['authenticate'] = True
        if skicall.call_data['authenticate']:
            return
        else:
            raise FailPage("Invalid input")
    if skicall.ident_list[-1] == (PROJECT, 20):
        # this call is to populate the showfiles page
        serverpath = pathlib.Path(BLOBS)
        serverfiles = [f.name for f in serverpath.iterdir() if f.is_file()]
        if not serverfiles:
            skicall.page_data['nothingfound', 'show'] = True
            skicall.page_data['filelinks', 'show'] = False
            return
        skicall.page_data['nothingfound', 'show'] = False
        skicall.page_data['filelinks', 'show'] = True

        # The widget has links formed from a list of lists
        # 0 : The url, label or ident of the target page of the link
        # 1 : The displayed text of the link
        # 2 : If True, ident is appended to link even if there is no get field
        # 3 : The get field data to send with the link

        serverfiles.sort(reverse=True)
        filelinks = []
        for sf in serverfiles:
            # create a link to urlfolder/sf
            filelinks.append(["images/" + sf, sf, False, ""])
        skicall.page_data['filelinks', 'nav_links'] = filelinks
        return
    if skicall.ident_list[-1] == (PROJECT, 30):
        # this call is to log out
        skicall.call_data['logout'] = True
    return