Beispiel #1
0
def login(username, password):
    user = User.get_or_none(username=username)
    if user is None:
        return constants.USER_NOT_EXISTS, '用户{}不存在'.format(username), None
    if encrypt.encrypt_password(password) != user.password:
        return constants.PASSWORD_ERROR, '密码错误', None
    return constants.OK, '登录成功', {'token': _generate_jwt_token(username)}
Beispiel #2
0
    def change_password(self, dni, raw_passwd):
        """
        Canvia la contrasenya de l'usuari amb dni passat com a paràmetre

        Entrada:
            dni (string): Dni de l'usuari al que es canvia la contrasenya
            raw_passwd (string): Contrasenya sense encriptar per la que es canviarà
        """
        enc_pass = encrypt.encrypt_password(raw_passwd)
        cursorObj = self.__con.cursor()
        cursorObj.execute("UPDATE users SET passwd = '"+enc_pass+"' WHERE DNI = '"+dni+"'")
        self.__con.commit()
Beispiel #3
0
    def create_user(self, dni, raw_passwd, isAdmin):
        """
        Crea l'usuari amb les dades enviades

        Entrada:
            dni (string): Dni de l'usuari
            raw_passwd (string): Contrasenya sense encriptar de l'usuari
            isAdmin (boolean): Si és admin o no
        """

        cursorObj = self.__con.cursor()
        cursorObj.execute("INSERT INTO users VALUES(?, ?, ?, ?)", (dni, encrypt.encrypt_password(raw_passwd), isAdmin, True))
        self.__con.commit()
Beispiel #4
0
def register(username, password, cellphone, birthday):
    if User.get_or_none(username=username) is not None:
        logging.info('用户{}已存在'.format(username))
        return constants.USER_EXISTS, '用户{}已存在'.format(username), None
    try:
        user = User.create(username=username,
                           password=encrypt.encrypt_password(password),
                           cellphone=cellphone,
                           birthday=birthday)
    except Exception as e:
        logging.error('创建用户{}出错'.format(username), exc_info=True)
        return constants.DATABASE_ERROR, '创建用户{}出错'.format(username), None
    if user is None:
        logging.error('创建用户{}出错'.format(username), exc_info=True)
        return constants.DATABASE_ERROR, '创建用户{}出错'.format(username), None
    return constants.OK, '创建成功'
Beispiel #5
0
def login():
    error_login = None
    error_register = None
    if request.method == 'POST':
        if 'login-submit' in request.form:
            error_register = None
            #passwd = encrypt.encrypt_password(request.form['password'])
            res = g.account.get_user_account(request.form['email'])
            if res != None:
                app.logger.info('res: %s', res)
                if encrypt.validate_password(res[2], request.form['password']):
                    session['logged_in'] = True
                    #app.logger.info('res: %s', res)
                    session['id'] = str(res[0])
                    session['user_name'] = str(res[1])
                    flash('You were logged in')
                    return redirect(url_for('user'))
                else:
                    error_login = '******'
            else:
                #exist = g.account.user_exist(request.form['email'])
                #if not exist:
                #	error_login = '******'
                #else:
                error_login = '******'
        elif 'register-submit' in request.form:
            error_login = None
            if request.form['password'] != request.form['confirm-password']:
                error_register = 'Different password'
            elif g.account.user_exist(request.form['email']):
                error_register = 'Email has been registered'
            else:
                app.logger.info('request passwd: %s', request.form['password'])
                passwd = encrypt.encrypt_password(request.form['password'])
                app.logger.info('passwd: %s', passwd)
                g.account.insert_user_account(request.form['username'], passwd,
                                              request.form['email'])
                _id, _name, _passwd = g.account.get_user_account(
                    request.form['email'])
                session['logged_in'] = True
                session['id'] = str(_id)
                session['user_name'] = str(_name)
                flash('You were logged in')
                return redirect(url_for('user'))
    return render_template('login.html',
                           error_login=error_login,
                           error_register=error_register)
Beispiel #6
0
def login():
	error_login = None
	error_register = None
	if request.method == 'POST':
		if 'login-submit' in request.form:
			error_register = None
			#passwd = encrypt.encrypt_password(request.form['password'])
			res = g.account.get_user_account(request.form['email'])
			if res != None:
				app.logger.info('res: %s', res)
				if encrypt.validate_password(res[2], request.form['password']):
					session['logged_in'] = True
					#app.logger.info('res: %s', res)
					session['id'] = str(res[0])
					session['user_name'] = str(res[1])
					flash('You were logged in')
					return redirect(url_for('user'))
				else:
					error_login = '******'
			else:
				#exist = g.account.user_exist(request.form['email'])
				#if not exist:
				#	error_login = '******'
				#else:
				error_login = '******'	
		elif 'register-submit' in request.form:
			error_login = None
			if request.form['password'] != request.form['confirm-password']:
				error_register = 'Different password'
			elif g.account.user_exist(request.form['email']):
				error_register = 'Email has been registered'
			else:
				app.logger.info('request passwd: %s', request.form['password'])
				passwd = encrypt.encrypt_password(request.form['password'])
				app.logger.info('passwd: %s', passwd)
				g.account.insert_user_account(request.form['username'], passwd, request.form['email'])
				_id, _name, _passwd = g.account.get_user_account(request.form['email'])
				session['logged_in'] = True
				session['id'] = str(_id)
				session['user_name'] = str(_name)
				flash('You were logged in')
				return redirect(url_for('user'))
	return render_template('login.html', error_login=error_login, error_register=error_register)
Beispiel #7
0
def authenticate(user, conn):
    data = conn.recv(BLOCK_SIZE).decode("utf-8")
    data = json.loads(data)
    password = data.get("password", None)

    if password == -1:
        print(f'Authenticated user {user} as USER.')
        return False
    else:
        password = encrypt_password(password)
        correct_password = get_from_database({"type": "password"})['password']

        if password == correct_password:
            accept = {"type": "auth", "password": 1}
            conn.send(bytes(json.dumps(accept), encoding="utf-8"))
            print(f'Authenticated user {user} as ADMIN.')
            return True
        else:
            accept = {"type": "auth", "password": -1}
            conn.send(bytes(json.dumps(accept), encoding="utf-8"))
            print(f'Authenticated user {user} as USER. (Wrong admin password)')
            return False
Beispiel #8
0
def authenticate():
    print("Enter admin password, otherwise press ENTER:")
    data = input()
    if data == '':
        auth_data = {"type": "auth", "password": -1}
        client_socket.send(bytes(json.dumps(auth_data), encoding="utf-8"))
        print("You are now entering USER mode")
        return False
    else:
        data = encrypt_password(data)
        auth_data = {"type": "auth", "password": data}  ##chtck
        client_socket.send(bytes(json.dumps(auth_data), encoding="utf-8"))

        # expecting {auth, 1} if success or {auth, -1} if deny
        data = client_socket.recv(BLOCK_SIZE).decode('utf-8')
        data = json.loads(data)
        flag = data.get("password", None)

        if flag == 1:
            print("You are now entering ADMIN mode")
            return True
        else:
            print("Wrong admin password. Entering user mode.")
            return False
def user():
    error = None
    if request.method == 'POST':
        user = current_user
        if user is None or not validate_password(user.password,
                                                 request.form['password']):
            error = '账号或密码错误'
        else:
            try:
                if request.form['new_password_again'] != request.form[
                        'new_password']:
                    error = '两次输入的新密码不一致'
            except:
                error = '请填写所有项目'
            else:
                change = db.session.query(User).filter_by(
                    username=user.username).first()
                change.password = encrypt_password(
                    request.form['new_password'])
                db.session.add(change)
                db.session.commit()
                logout_user()
                return redirect('/')
    return render_template('user.html', error=error)
Beispiel #10
0
    def editsetting(self):

        section_name = self.leServer.currentText()

        if self.webUrlModified:

            self.webUrlModified = False

            url = self.leUrl.text().split(":")

            protocol = url[0]

            consoleUrl = url[1].replace("/", "").strip()

            portBaseUrl = url[2].split("/")

            port = portBaseUrl[0]

            baseurl = ""
            if len(portBaseUrl) > 1:
                baseurl = "/" + portBaseUrl[1] + "/"

            self.parser.set(section_name, 'protocol', protocol)
            self.parser.set(section_name, 'console.url', consoleUrl)
            self.parser.set(section_name, 'console.port', port)
            self.parser.set(section_name, 'console.baseurl', baseurl)

        if self.amqpUrlModified:

            self.amqpUrlModified = False

            url = self.le1Url.text().split(":")
            protocol = url[0]
            amqpUrl = url[1].replace("/", "").strip()
            amqpPort = url[2]

            self.parser.set(section_name, 'amqp.protocol', protocol)
            self.parser.set(section_name, 'amqp.url', amqpUrl)
            self.parser.set(section_name, 'amqp.port', amqpPort)

        if self.userIdModified:
            self.userIdModified = False
            self.parser.set(section_name, 'username',
                            self.leUserId.text().strip())

        if self.passkeyFileModified:
            self.passkeyFileModified = False
            self.parser.set(section_name, 'passkey.file',
                            self.lePassKey.text().strip())

        if self.passwordModified:
            self.passwordModified = False

            passwd = self.lePassword.text()
            #passKeyFile = "{fpath}{file}".format(fpath = self.filePath, file=self.parser.get(section_name, 'passkey.file'))
            passKeyFile = self.lePassKey.text()

            encPass = ""
            if len(passKeyFile) != 0 and len(passwd) != 0:
                encPass = encrypt.encrypt_password(passKeyFile, passwd)

            self.parser.set(section_name, 'password', encPass)

        if self.vhostModified:
            self.vhostModified = False
            self.parser.set(section_name, 'vhost', self.leVhost.text())

        if self.certNameModified:
            self.certNameModified = False
            self.parser.set(section_name, 'certificateName',
                            self.leCertificateName.text())

        if self.passkeyCertFileModified:
            self.passkeyCertFileModified = False
            self.parser.set(section_name, 'passkeycert.file',
                            self.leCertificatePassKey.text().strip())

        if self.certPassModified:
            self.certPassModified = False

            passwd = self.leCertificatePassword.text()
            #passKeyFile = "{fpath}{file}".format(fpath = self.filePath, file=self.parser.get(section_name, 'passkeycert.file'))
            #passKeyFile = ".{file}".format(file=self.parser.get(section_name, 'passkeycert.file'))
            passKeyFile = self.leCertificatePassKey.text()

            encPass = ""
            if len(passKeyFile) != 0 and len(passwd) != 0:
                encPass = encrypt.encrypt_password(passKeyFile, passwd)

            self.parser.set(section_name, 'certificatePassword', encPass)

        with open(self.inifile, 'w') as configfile:
            self.parser.write(configfile)

        self.refresh()

        #index = self.leServer.findText(section_name, Qt.MatchFixedString)
        #if index >= 0:
        #    self.leServer.setCurrentIndex(index)


        MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Configuration entry updated!", \
                                   "Server: {section} update in File: {file} sucessfully.".format(section=section_name, file=self.inifile))
Beispiel #11
0
    def buttonClicked(self):
        button = self.sender()
        #print(button.objectName())

        if not button: return

        buttonObjectName = button.objectName()

        if buttonObjectName == "add_setting":

            section_name = self.leAddServer.text()

            self.parser.add_section(section_name)

            self.parser.set(section_name, 'protocol',
                            self.wprotocolCombo.currentText().strip())
            self.parser.set(section_name, 'console.url',
                            self.whost.text().strip())
            self.parser.set(section_name, 'console.port',
                            self.wport.text().strip())
            self.parser.set(section_name, 'console.baseurl',
                            self.wbaseurl.text().strip())

            self.parser.set(section_name, 'amqp.protocol',
                            self.amqpCombo.currentText().strip())
            self.parser.set(section_name, 'amqp.url',
                            self.amqphost.text().strip())
            self.parser.set(section_name, 'amqp.port',
                            self.amqpport.text().strip())

            self.parser.set(section_name, 'username',
                            self.leUserId.text().strip())

            passKeyFile = self.lePassKey.text().strip()
            self.parser.set(section_name, 'passkey.file', passKeyFile)

            passwd = self.lePassword.text()
            encPass = ""
            if len(passKeyFile) != 0 and len(passwd) != 0:
                encPass = encrypt.encrypt_password(passKeyFile, passwd)
            self.parser.set(section_name, 'password', encPass)

            self.parser.set(section_name, 'vhost', self.leVhost.text().strip())
            self.parser.set(section_name, 'certificateName',
                            self.leCertificateName.text().strip())

            certPasskeyFile = self.leCertificatePassKey.text().strip()
            self.parser.set(section_name, 'passkeycert.file', certPasskeyFile)

            certpasswd = self.leCertificatePassword.text()
            encCertPass = ""
            if len(certPasskeyFile) != 0 and len(certpasswd) != 0:
                encCertPass = encrypt.encrypt_password(certPasskeyFile,
                                                       certpasswd)
            self.parser.set(section_name, 'certificatePassword', encCertPass)

            with open(self.inifile, 'w') as configfile:
                self.parser.write(configfile)

            #self.refresh()

            MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Configuration entry added!", \
                                   "Server: {section} added to File: {file} sucessfully.".format(section=section_name, file=self.inifile))

            self.resetWidget()
        elif buttonObjectName == "edit_setting":
            pass
        elif buttonObjectName == "cancel_setting":
            self.resetWidget()