Ejemplo n.º 1
0
def thumbs_change():
    print('thumbs change')
    data = request.form
    """Changes queue when thumbs up/down."""
    user = User(session['id'])
    user.save_thumbs_change(data['track_id'], data['change'])
    queue.thumbs_change(data['track_id'],
                        data['change'],
                        decrement=(data['decrement'] == 'true'))
    queue_change()
    return json.dumps({'success': 'acknowledged the upvote/downvote'})
Ejemplo n.º 2
0
 def create_message(from_user_email, to_user_email, message_subject,
                    message_body):
     """
     Add a new message to the datastore
     """
     from_user_ref = User.get_by_key_name(from_user_email)
     to_user_ref = User.get_by_key_name(to_user_email)
     new_message = Message(fromUser=from_user_ref,
                           toUser=to_user_ref,
                           subject=message_subject,
                           body=message_body)
     new_message.put()
Ejemplo n.º 3
0
    def handle_direct_message(self, message, channel_id):
        msg = message['msg'].partition('@' + self.botname)[2].strip() if message["msg"].startswith('@' + self.botname) \
            else message["msg"].strip()
        if len(msg) > 0:
            command = msg.split()[0].lower()
            # arguments = " ".join(msg.split()[1:])
            user = User.from_message(message)
            attachments = message['attachments']
            pass_message = Message(message_id=message["_id"],
                                   text=msg,
                                   chat=Chat(chat_id=channel_id),
                                   user=user,
                                   attachments=attachments,
                                   json=message)

            conversation = self.conversations.get(user.id)
            variants = self.button_variants.get(channel_id)
            pass_message.text = variants.get(
                pass_message.text,
                pass_message.text) if variants else pass_message.text
            if conversation is not None:
                # Зарегистрирован следующий шаг
                f, args, kwargs = conversation
                self.conversations.pop(user.id)
                f(pass_message, *args, **kwargs)
            else:
                # Следующий шаг не найден, обработка как обычно
                for cmd_list in self.commands:
                    if command.lower() in cmd_list[0]:
                        cmd_list[1](pass_message)
                        return

                if not self.handle_auto_answer(message, self.direct_answers,
                                               channel_id):
                    if self.handle_unknown is not None:
                        self.handle_unknown(pass_message)
                    else:
                        self.send_message(
                            '@' + user.username + ' :' +
                            choice(self.unknown_command), channel_id)
        else:
            user = User.from_message(message)
            attachments = message['attachments']
            pass_message = Message(message_id=message["_id"],
                                   text=msg,
                                   chat=Chat(chat_id=channel_id),
                                   user=user,
                                   attachments=attachments,
                                   json=message)
            self.handle_unknown(pass_message)
Ejemplo n.º 4
0
 def create_message(from_user_email,
                    to_user_email,
                    message_subject,
                    message_body):
     """
     Add a new message to the datastore
     """
     from_user_ref = User.get_by_key_name(from_user_email)
     to_user_ref = User.get_by_key_name(to_user_email)
     new_message = Message(fromUser=from_user_ref,
                           toUser=to_user_ref,
                           subject=message_subject,
                           body=message_body)
     new_message.put()
Ejemplo n.º 5
0
def mainIndex():
    user = None
    attempted = False
    sessionUser = ['', '', '']
    deactivated = False
    #Log in user
    if request.method == 'POST':
        attempted = True
        email = request.form['email']
        pwd = request.form['pwd']
        query = pg.logIn(email, pwd)
        if query != None and len(query) > 0:
            #Check for deactivated status.
            if query[3] == 3:
                deactivated = True
                attempted = False
            else:
                user = User(query[0], query[1], query[2], query[3])
                session['userName'] = user.firstname
                session['email'] = user.email
                session['role'] = user.role.value
    #Session Check
    if 'userName' in session:
        sessionUser = [session['userName'], session['email'], session['role']]
    else:
        sessionUser = ['', '']
    return render_template('index.html',
                           sessionUser=sessionUser,
                           attempted=attempted,
                           deactivated=deactivated)
Ejemplo n.º 6
0
def callback():
    # Get authorization code IDP sent back
    form = LoginForm()
    try:
        code = request.args.get("code")
        idp_provider_cfg = get_idp_provider_cfg()
        token_endpoint = idp_provider_cfg["token_endpoint"]
        # Request to get tokens from IDP
        token_url, headers, body = oidcClient.prepare_token_request(
            token_endpoint,
            authorization_response=request.url,
            redirect_url=request.base_url,
            code=code,
        )
        with get_session() as session:
            token_response = session.post(
                token_url,
                headers=headers,
                data=body,
                auth=(config.getClientID(), config.getClientSecret()),
                verify=config.useSSLVerify(),
            )

        # Parse the tokens!
        oidcClient.parse_request_body_response(
            json.dumps(token_response.json()))
        # find and hit the userinfo endpoint
        # from IDP that gives user's profile information,
        # including their preferred username -
        userinfo_endpoint = idp_provider_cfg["userinfo_endpoint"]
        uri, headers, body = oidcClient.add_token(userinfo_endpoint)

        with get_session() as session:
            userinfo_response = session.get(uri,
                                            headers=headers,
                                            data=body,
                                            verify=config.useSSLVerify())

        # Login the user
        preferred_username = userinfo_response.json()["preferred_username"]
        if preferred_username:
            person = User.get(preferred_username, auth_handler)
            defaultFilters.update({
                "blacklistSelect": "on",
                "whitelistSelect": "on",
                "unlistedSelect": "show",
            })
            login_user(person)
            return redirect(url_for("admin.admin_home"))
        else:
            return render_template("login.html",
                                   form=form,
                                   status="auth_again",
                                   show_oidc=config.useOIDC())
    except Exception as err:
        logger.error(f"****OIDC callback exception***** --> {err}")
        return render_template("login.html",
                               form=form,
                               status="auth_again",
                               show_oidc=config.useOIDC())
Ejemplo n.º 7
0
    def post(self):
        """
        login

        Endpoint used for requesting JWT token via a username and password
        """
        if not request.is_json:
            api.abort(400, "Missing JSON in request")

        username = request.json.get("username", None)
        password = request.json.get("password", None)
        if not username:
            api.abort(400, "Missing username parameter in request body")
        if not password:
            api.abort(400, "Missing password parameter in request body")

        user = User.get(username, auth_handler)

        if user is None:
            api.abort(400, "Bad username or password")

        if user is not None and user.authenticate(password):
            access_token = create_access_token(
                identity="user_{}".format(user.id))

            access_jti = get_jti(encoded_token=access_token)

            token_blacklist.set(access_jti, "false", ACCESS_EXPIRES * 1.2)

            ret = {"access_token": access_token}

            return ret

        else:
            api.abort(400, "Bad username or password")
Ejemplo n.º 8
0
def login():

    form = LoginForm()

    if current_user.is_authenticated:
        return redirect(url_for("home.index"))

    if not config.loginRequired():
        person = User.get("_dummy_", auth_handler)
        defaultFilters.update({
            "blacklistSelect": "on",
            "whitelistSelect": "on",
            "unlistedSelect": "show"
        })
        login_user(person)

        return redirect(url_for("admin.admin_home"))

    if form.validate_on_submit():

        # validate username and password
        username = request.form.get("username")
        password = request.form.get("password")
        person = User.get(username, auth_handler)
        if person and person.authenticate(password):
            defaultFilters.update({
                "blacklistSelect": "on",
                "whitelistSelect": "on",
                "unlistedSelect": "show",
            })
            login_user(person)
            return redirect(url_for("admin.admin_home"))
        else:
            return render_template(
                "login.html",
                form=form,
                status="wrong_user_pass",
                show_oidc=config.useOIDC(),
            )
    else:
        return render_template("login.html",
                               form=form,
                               show_oidc=config.useOIDC())
Ejemplo n.º 9
0
def register_interface(name, password):
    user = select_user(name)
    if user:
        return False, '用户已经存在'
    else:
        from lib.User import User
        new_user = User(name, password)
        save_user(new_user)
        user_logger.info('%s 注册了' % name)
        return True, '注册成功'
Ejemplo n.º 10
0
def admin():
    status = ["default", "none"]
    if Configuration.loginRequired():
        if not current_user.is_authenticated():
            return render_template('login.html', status=status)
        else:
            return render_template('admin.html', status=status, stats=adminStats())
    else:
        person = User.get("_dummy_")
        login_user(person)
        return render_template('admin.html', status=status, stats=adminStats())
Ejemplo n.º 11
0
def admin():
    status = ["default", "none"]
    if Configuration.loginRequired():
        if not current_user.is_authenticated():
            return render_template('login.html', status=status)
        else:
            return render_template('admin.html', status=status, stats=adminStats())
    else:
        person = User.get("_dummy_")
        login_user(person)
        return render_template('admin.html', status=status, stats=adminStats())
Ejemplo n.º 12
0
def login_check():
    # validate username and password
    username = request.form.get('username')
    password = request.form.get('password')
    person = User.get(username)
    try:
        if person and pbkdf2_sha256.verify(password, person.password):
            login_user(person)
            return render_template('admin.html', status=["logged_in", "success"], stats=adminStats())
        else:
            return render_template('login.html', status=["wrong_combination", "warning"])
    except:
        return render_template('login.html', status=["outdated_database", "error"])
Ejemplo n.º 13
0
def login_check():
    # validate username and password
    username = request.form.get('username')
    password = request.form.get('password')
    person = User.get(username)
    try:
        if person and pbkdf2_sha256.verify(password, person.password):
            login_user(person)
            return render_template('admin.html', status=["logged_in", "success"], stats=adminStats())
        else:
            return render_template('login.html', status=["wrong_combination", "warning"])
    except:
        return render_template('login.html', status=["outdated_database", "error"])
Ejemplo n.º 14
0
def login_check():
    # validate username and password
    username = request.form.get('username')
    password = request.form.get('password')
    person = User.get(username)
    try:
        if person and pbkdf2_sha256.verify(password, person.password):
            login_user(person)
            return render_template('admin.html', status="logged_in", **adminInfo())
        else:
            return render_template('login.html', status="wrong_user_pass")
    except:
        return render_template('login.html', status="outdated_database")
Ejemplo n.º 15
0
def login_check():
    # validate username and password
    username = request.form.get('username')
    password = request.form.get('password')
    person = User.get(username)
    try:
        if person and pbkdf2_sha256.verify(password, person.password):
            login_user(person)
            return render_template('admin.html', status="logged_in", **adminInfo())
        else:
            return render_template('login.html', status="wrong_user_pass")
    except:
        return render_template('login.html', status="outdated_database")
Ejemplo n.º 16
0
 def login_check(self):
   # validate username and password
   username = request.form.get('username')
   password = request.form.get('password')
   person = User.get(username, self.auth_handler)
   try:
     if person and person.authenticate(password):
       login_user(person)
       return render_template('admin.html', status="logged_in", **self.adminInfo())
     else:
       return render_template('login.html', status="wrong_user_pass")
   except Exception as e:
     print(e)
     return render_template('login.html', status="outdated_database")
Ejemplo n.º 17
0
def admin():
    if Configuration.loginRequired():
        if not current_user.is_authenticated():
            return render_template('login.html')
    else:
        person = User.get("_dummy_")
        login_user(person)
    output = None
    if os.path.isfile(Configuration.getUpdateLogFile()):
        with open(Configuration.getUpdateLogFile()) as updateFile:
            separator="==========================\n"
            output=updateFile.read().split(separator)[-2:]
            output=separator+separator.join(output)
    return render_template('admin.html', status="default", stats=adminStats(), updateOutput=filterUpdateField(output))
Ejemplo n.º 18
0
 def login_check(self):
     # validate username and password
     username = request.form.get('username')
     password = request.form.get('password')
     person = User.get(username, self.auth_handler)
     try:
         if person and person.authenticate(password):
             login_user(person)
             return redirect('admin')
         else:
             return render_template('login.html', status="wrong_user_pass")
     except Exception as e:
         print(e)
         return render_template('login.html', status="outdated_database")
Ejemplo n.º 19
0
def admin():
    if Configuration.loginRequired():
        if not current_user.is_authenticated():
            return render_template('login.html')
    else:
        person = User.get("_dummy_", auth_handler)
        login_user(person)
    output = None
    if os.path.isfile(Configuration.getUpdateLogFile()):
        with open(Configuration.getUpdateLogFile()) as updateFile:
            separator = "==========================\n"
            output = updateFile.read().split(separator)[-2:]
            output = separator + separator.join(output)
    return render_template('admin.html', status="default", **adminInfo(output))
Ejemplo n.º 20
0
 def login_check(self):
     # validate username and password
     username = request.form.get("username")
     password = request.form.get("password")
     person = User.get(username, self.auth_handler)
     try:
         if person and person.authenticate(password):
             login_user(person)
             return render_template("admin.html",
                                    status="logged_in",
                                    **self.adminInfo())
         else:
             return render_template("login.html", status="wrong_user_pass")
     except Exception as e:
         print(e)
         return render_template("login.html", status="outdated_database")
Ejemplo n.º 21
0
    def registerUser(self, name):
        """Creates and registers user with the given name.

        This is a weird implementation since users cannot exist outside
        of this protocol.
        But, eh ¯\\\\\_(ツ)\\_/¯

        Parameters:
        ----------
        name : String

        Returns:
        --------
        None
        """
        user = User(name)
        self.__users.append(user)
Ejemplo n.º 22
0
def admin():
    status = ["default", "none"]
    if Configuration.loginRequired():
        if not current_user.is_authenticated():
            return render_template('login.html', status=status)
    else:
        person = User.get("_dummy_")
        login_user(person)
    output = None
    if os.path.isfile(Configuration.getUpdateLogFile()):
        with open(Configuration.getUpdateLogFile()) as updateFile:
            separator = "==========================\n"
            output = updateFile.read().split(separator)[-2:]
            output = separator + separator.join(output)
    return render_template('admin.html',
                           status=status,
                           stats=adminStats(),
                           updateOutput=filterUpdateField(output))
Ejemplo n.º 23
0
    def getUsers(self, verbose=False):
        self._users = []
        self._readFiles()

        sudoFileObject = StringIO(self.files["sudoers"])
        sp = SudoersParser()
        sp.parseFile(sudoFileObject)

        # TODO: clean up, use one variable
        for ul in self.files["passwd"].split("\n"):
            username = ""
            username = ul.split(":")[0]
            userID = ul.split(":")[2]
            userGecos = ul.split(":")[4]
            userPrimaryGroupID = ul.split(":")[3]
            userShell = ul.split(":")[6]
            userLocked = self.isUserLocked(username)

            if verbose:
                logging.warning("Working on user {0}".format(username))

            # Get groups
            groups = []
            for gl in self.files["group"].split("\n"):
                groupName = gl.split(":")[0]
                groupID = gl.split(":")[2]
                groupUsers = gl.split(":")[3]
                if userPrimaryGroupID == groupID or groupUsers.find(
                        username) != -1:
                    groups.append(groupName)

            # Get sudo permissions
            userSudoPerms = sp.getCommands(username)
            # TODO: put this in a separate function, to get all OS group privileges in sudoers file
            for group in groups:
                for sudoline in self.files["sudoers"].split("\n"):
                    if re.search("^%{0} \S*".format(group), sudoline):
                        userSudoPerms.append(sudoline)
            user = User(userID, username, userGecos, userLocked, groups,
                        userSudoPerms)
            self._users.append(user)
        return self._users
Ejemplo n.º 24
0
 def admin(self):
     if Configuration.loginRequired():
         if not current_user.is_authenticated():
             return render_template('login.html')
     else:
         person = User.get("_dummy_", self.auth_handler)
         login_user(person)
     output = None
     master = db.isMasterAccount(current_user.get_id())
     checked = ct.checkCronJobExists('cve_search')
     if os.path.isfile(Configuration.getUpdateLogFile()):
         with open(Configuration.getUpdateLogFile()) as updateFile:
             separator = "==========================\n"
             output = updateFile.read().split(separator)[-2:]
             output = separator + separator.join(output)
     return render_template('admin.html',
                            status="default",
                            master=master,
                            checked=checked,
                            **self.adminInfo(output))
Ejemplo n.º 25
0
def UserLogin(get_user, get_pass):
    '''用户登录'''
    #注册用户类
    user = User(get_user)
    # 检查用户是否注册
    if user.getUserID() == None:
        return "账号未注册,请注册"
    # 验证用户密码
    print(get_user, get_pass)
    if user.getUserPasswd() == get_pass:
        user.uploadUserinfo()
        # 如果登录成功返回user对象
        return user()
    else:
        raise ValueError("密码错误")
Ejemplo n.º 26
0
    def handle_command_character_message(self, message, channel_id):
        msg = message['msg'].lstrip(self.command_character)

        command = msg.split()[0].lower()
        arguments = " ".join(msg.split()[1:])
        user = message['u']['username']
        attachments = message['attachments']
        pass_message = Message(message_id=message["_id"],
                               text=msg,
                               chat=Chat(chat_id=channel_id),
                               user=User.from_message(message),
                               attachments=attachments,
                               json=message)
        for cmd_list in self.commands:
            if command.lower() in cmd_list[0]:
                cmd_list[1](pass_message)
                return

        if not self.handle_auto_answer(message, self.direct_answers,
                                       channel_id):
            self.send_message('@' + user + ' :' + choice(self.unknown_command),
                              channel_id)
Ejemplo n.º 27
0
 def load_user(self, id):
     return User.get(id, self.auth_handler)
Ejemplo n.º 28
0
def load_user(id):
    return User.get(id, auth_handler)
Ejemplo n.º 29
0
def load_user(id):
    return User.get(id)
Ejemplo n.º 30
0
 def load_user(self, id):
   return User.get(id, self.auth_handler)
Ejemplo n.º 31
0
import pandas as pd
from flask import Flask, request, session, redirect, url_for, escape, render_template, send_file
import xlrd, os, uuid, pdfkit
from openpyxl.workbook import Workbook

from lib.errors import *
from lib.User import User
from lib.tableKeys import keys as tableKeys

app = Flask(__name__,
            static_url_path='',
            static_folder='templates/',
            template_folder='templates/')
app.secret_key = "some"

user = User()


@app.route('/', methods=['GET'])
def home():
    if 'user' in session:
        return user.index()
    else:
        return redirect(url_for('login'))


@app.route('/blank', methods=['GET'])
def blank():
    try:
        return user.blank()
    except LinkError:
Ejemplo n.º 32
0
def load_user(id):
    return User.get(id)
Ejemplo n.º 33
0
def load_user(id):
    return User.get(id, auth_handler)
Ejemplo n.º 34
0
    key_type_dic = DZMon.find(userid=user.getUserID(), cloum=collo_DZ)
    print(key_type_dic)
    btnSta = dict()
    keylist = [
        keyid for keyid in item.keys() if keyid > 10100 and keyid < 10200
    ]
    for keyid in keylist:
        try:
            if key_type_dic[collo_DZ][str(keyid)] > 1:
                btnSta.update({
                    keyid:
                    (True,
                     key_type_dic[collo_DZ][str(keyid)] + 10 - int(time()))
                })
            else:
                btnSta.update({keyid: False})
        except KeyError:
            btnSta.update({keyid: False})
        except TypeError:
            btnSta.update({keyid: False})

    print(btnSta, ores)
    return ores, btnSta


if __name__ == "__main__":
    user = User(userid=2)
    print(duanZao(user, key_type=10101))

    # 查询 指定钥匙的是锻造情况
Ejemplo n.º 35
0
def connect():
    try:
        user = User(session['id'])
        return json.dumps(user.get_data()['thumbs_tracks'])
    except AttributeError:
        return json.dumps({'error': 'no data for this user yet'})