示例#1
0
def login():
    """
    Login the user to the server
    :return: user json with id and API key
    """
    user_json = request.json
    username = user_json[UserKeys.USERNAME_KEY]
    password = user_json[UserKeys.HASHED_PASSWORD]

    user = UserService.get_user_by_name(username)
    if user is None:
        abort(404)

    if user[UserKeys.HASHED_PASSWORD] != password:
        abort(404)

    token, refresh_token = create_user_token(str(user.id))

    user_json[ID_KEY] = str(user.id)
    user_json[UserKeys.API_KEY] = token

    UserService.set_refresh_cookie(str(user.id), refresh_token)

    res = make_response(token)
    res.set_cookie("refresh_token", refresh_token, httponly=True)

    return res
示例#2
0
def create_user_token(user_id: str):
    token = jwt.encode(
        {
            "id": user_id,
            "exp": datetime.utcnow() + timedelta(minutes=TOKEN_EXPIRE_TIME)
        }, JWT_SECRET)

    refresh_cookie = jwt.encode(
        {
            "id": user_id,
            "exp": datetime.utcnow() + timedelta(minutes=TOKEN_EXPIRE_TIME)
        }, REFRESH_COOKIE)

    UserService.set_refresh_cookie(user_id, refresh_cookie.decode())

    return token.decode(), refresh_cookie.decode()
示例#3
0
def create_user():
    """
    Creating new User
    :return: the new user json, or 404 if user exist
    """
    user_json = request.json

    try:
        if UserService.is_username_unique(user_json[UserKeys.USERNAME_KEY]):
            UserService.add_user(user_json[UserKeys.USERNAME_KEY],
                                 user_json[UserKeys.HASHED_PASSWORD])
        else:
            return abort(406)
    except KeyError:
        abort(400)

    return {}
示例#4
0
    def __init__(self, parent=None):
        self.__users = None

        self.user_service = UserService(self)

        super(AdminWidget, self).__init__(parent)
        self.button_add_user = QPushButton('Add user')
        self.button_remove_user = QPushButton('Remove user')
        self.user_search_input = QLineEdit()
        self.user_list = QListWidget()
        self.button_logout = QPushButton('Logout')

        self.user_search_input.setPlaceholderText('Search users')
        self.user_list.setMinimumWidth(400)

        left_column = QVBoxLayout()
        left_column.addWidget(self.button_add_user)
        left_column.addWidget(self.button_remove_user)
        left_column.addStretch()
        left_column.addWidget(self.button_logout)

        right_column = QVBoxLayout()
        right_column.addWidget(self.user_search_input)
        right_column.addWidget(self.user_list)

        layout = QHBoxLayout()
        layout.addLayout(left_column)
        layout.addLayout(right_column)

        widget = QWidget()
        widget.setLayout(layout)

        self.addTab(widget, 'Users manager')
        self.addTab(UserWidget(parent), 'Books manager')

        self.button_add_user.clicked.connect(self.add_user)
        self.button_remove_user.clicked.connect(
            lambda: self.user_service.delete_user(
                self.__users[self.user_list.currentRow()]
            )
        )
        self.user_search_input.textChanged.connect(self.refresh)
        self.user_list.currentRowChanged.connect(self.user_choice)
        self.button_logout.clicked.connect(parent.request_logout)
示例#5
0
    def decorated(*args, **kwargs):
        token = None
        if 'Authorization' in request.headers:
            token = request.headers['Authorization']
        if not token:
            return jsonify({'message': 'Token is missing !!'}), 401

        data = jwt.decode(token, JWT_SECRET)
        if UserService.get_user_by_id(data["id"]) is not None or\
                EndpointService.get_endpoint_by_id(data["id"]) is not None:
            return f(*args, **kwargs)

        return jsonify({'message': 'Token is invalid !!'}), 401
示例#6
0
def delete_user(user_id):
    """
    Delete user from the db by id
    :param user_id: the user id to delete
    :return: empty string or 404 on failure
    """
    user = UserService.get_user_by_id(user_id)
    if user is None:
        abort(404)

    user.delete()

    return {}
示例#7
0
def validate_cookie():
    cookie = request.cookies.get('refresh_token')
    if not cookie:
        return jsonify({'message': 'Cookie is missing !!'}), 401

    data = jwt.decode(cookie, REFRESH_COOKIE)
    user = UserService.get_user_by_id(data["id"])
    if user is None:
        return jsonify({'message': 'Cookie is invalid !!'}), 401

    if user.refresh == cookie:
        return data["id"]

    return jsonify({'message': 'Cookie is invalid !!'}), 401
示例#8
0
    def post(self):
        username = self.get_argument('username', None)
        password = self.get_argument('password', None)

        if not username or not password:
            self.redirect('/?errorlogin=required')

        account = UserService.verify_user(username, password)

        if not account:
                self.redirect('/?errorlogin=nologin')

        self.set_secure_cookie("_ur", json.dumps(account))
        
        self.redirect('/dashboard')
示例#9
0
def get_user_data(user_id):
    """
    Return the wanted user by id
    :param user_id: the wanted user id
    :return: the user json or 404 if user not found
    """
    user = UserService.get_user_by_id(user_id)
    if user is None:
        abort(404)

    user_json = json.loads(USER_JSON)
    user_json[ID_KEY] = str(user.id)
    user_json[UserKeys.USERNAME_KEY] = user[UserKeys.USERNAME_KEY]

    return user_json
示例#10
0
    def post(self):

        username = self.get_argument('username', None)
        password = self.get_argument('password', None)
        email_address = self.get_argument('email', None)
        company_name= self.get_argument('company_name', None)

        if not username or not password or not email_address or not company_name:
            self.redirect('/?error=required')

        account = UserService.create_user(username, password, email_address, company_name)

        if not account:
            self.redirect('/?error=exists')

        self.set_secure_cookie("_ur", json.dumps(account))

        self.redirect('/dashboard')
示例#11
0
class AdminWidget(QTabWidget):
    def __init__(self, parent=None):
        self.__users = None

        self.user_service = UserService(self)

        super(AdminWidget, self).__init__(parent)
        self.button_add_user = QPushButton('Add user')
        self.button_remove_user = QPushButton('Remove user')
        self.user_search_input = QLineEdit()
        self.user_list = QListWidget()
        self.button_logout = QPushButton('Logout')

        self.user_search_input.setPlaceholderText('Search users')
        self.user_list.setMinimumWidth(400)

        left_column = QVBoxLayout()
        left_column.addWidget(self.button_add_user)
        left_column.addWidget(self.button_remove_user)
        left_column.addStretch()
        left_column.addWidget(self.button_logout)

        right_column = QVBoxLayout()
        right_column.addWidget(self.user_search_input)
        right_column.addWidget(self.user_list)

        layout = QHBoxLayout()
        layout.addLayout(left_column)
        layout.addLayout(right_column)

        widget = QWidget()
        widget.setLayout(layout)

        self.addTab(widget, 'Users manager')
        self.addTab(UserWidget(parent), 'Books manager')

        self.button_add_user.clicked.connect(self.add_user)
        self.button_remove_user.clicked.connect(
            lambda: self.user_service.delete_user(
                self.__users[self.user_list.currentRow()]
            )
        )
        self.user_search_input.textChanged.connect(self.refresh)
        self.user_list.currentRowChanged.connect(self.user_choice)
        self.button_logout.clicked.connect(parent.request_logout)

    @pyqtSlot()
    def refresh(self):
        self.user_list.clear()
        self.search()
        self.user_list.addItems([user['username'] for user in self.__users])

    def search(self):
        self.__users = self.user_service.users
        search = self.user_search_input.text().lower()
        if search is not None:
            self.__users = filter(lambda x: True if x['username'].lower().find(search) > -1 else False, self.__users)
        self.__users = list(self.__users)

    def user_choice(self, index):
        if self.__users[index]['username'] == UserService.username:
            self.button_remove_user.setEnabled(False)
        else:
            self.button_remove_user.setEnabled(True)

    def add_user(self):
        ok, user = AddUserDialog().get_result(self)
        if not ok:
            return
        self.user_service.add_user(user)