예제 #1
0
async def get_current_user(
        security_scopes: SecurityScopes,
        token: str = Depends(oauth2_scheme)  # noqa:B008
) -> UserModel:
    """
    Gets user from token.

    Parameters
    ----------
    security_scopes: SecurityScopes
        scopes
    token : str, optional
        jwt token, by default Depends(oauth2_scheme)

    Returns
    -------
    UserMe
        user object

    Raises
    ------
    credentials_exception
        if jwt token is not valid
        if jwt token doesn't has userid
        if user doesn't exists
    """
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = 'Bearer'
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail='Could not validate credentials',
        headers={'WWW-Authenticate': authenticate_value},
    )
    try:
        payload = decode_access_token(token)
        userid = payload.get('sub')
        if userid is None:
            raise credentials_exception
        token_scopes = payload.get('scopes', [])
        token_data = TokenData(id=userid, scopes=token_scopes)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = await get_user({'id': token_data.id})
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail='Not enough permissions',
                headers={'WWW-Authenticate': authenticate_value},
            )
    user = UserModel(**user.dict())
    return user
예제 #2
0
def delete_user():
    data = request.get_json()
    payload = data['data']
    username = payload['username']
    user = UserModel.User(username)
    delete = user.delete(username)
    return {"deleted": delete}
예제 #3
0
def frontend_auth():
    """
    Auth access for front end apps.
    """
    payload = request.get_json()
    username = payload["username"]
    password = payload["password"]

    # print(username)
    # print(password)

    # return {
    #     "username": username,
    #     "password": password
    # }

    _username = UserModel.User(username)
    auth = _username.authenticate(username, password)

    if auth == True:
        token = jwt.encode(
            {
                "user": username,
                "password": password,
                "exp":
                datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
            }, app.config['SECRET_KEY']
        )  #  Expiration is a reserved part of the payload in JWT
        return {'token': token.decode('UTF-8'), 'message': 'authorized'}
    if auth != True:
        return {'message': 'not authorized'}
예제 #4
0
파일: dataset.py 프로젝트: s4madmin/dp-prod
    def decorated(*args, **kwargs):

        token = None

        if 'X-API-KEY' in request.headers:
            token = request.headers['X-API-KEY']

        if not token:
            return {
                'message': 'Token is missing!'
            }, 401  # No need to use dumps, flask-rest-plus converts dict to json.

        payload = jwt.decode(token, app.config['SECRET_KEY'], 'UTF-8')
        username = payload['user']
        password = payload['password']
        _username = UserModel.User(username)
        auth = _username.authenticate(username, password)

        if auth != True:
            return {
                'message':
                'your token is not valid, login again or contact administrator'
            }

        return f(*args, **kwargs)
예제 #5
0
파일: browse.py 프로젝트: s4madmin/dp-prod
def get_all_users():
    _user = user.User("*****@*****.**")
    get_users = _user.userTable()
    df = get_users.reset_index()
    newdf = df.drop(['password'], axis=1)
    _dict = newdf.to_dict("records")

    return {"users": _dict}
예제 #6
0
def add_user():
    data = request.get_json()
    payload = data['data']
    email = payload['email']
    role = payload['role']
    password = payload['password']
    user = UserModel.User(email)
    create = user.create(email, password, role)
    return {"created": create}
예제 #7
0
def user_update():
    data = request.get_json()
    payload = data['data']
    username = payload['username']
    password = payload['password']
    verifyPassword = payload['verifyPassword']
    role = payload['role']
    user = UserModel.User(username)
    update = user.update(username, password, role)
    return {"updated": "true"}
예제 #8
0
    def post(self):
        data = parser.parse_args()
        user_name = data['username']

        if not user_name:
            return {'message': 'User name is required'}, 422

        if user_name.isspace():
            return {'message': 'User name cannot be empty space'}, 422

        # Requirements 6.1.1 and 6.1.2: unique username
        if UserModel.find_by_username(user_name):
            return {
                'message': 'User {} already exists'.format(data['username'])
            }, 422

        # Requirement 6.2.1: encrypts password
        new_user = UserModel(username=data['username'],
                             password=UserModel.generate_hash(
                                 data['password']))

        # Requirement 6.3.0: stores user in database
        try:
            new_user.save_to_db()
            access_token = create_access_token(identity=data['username'])
            refresh_token = create_refresh_token(identity=data['username'])
            return {
                'message': 'User {} was created'.format(data['username']),
                'access_token': access_token,
                'refresh_token': refresh_token
            }, 200
        except:
            return {'message': 'Something went wrong'}, 500
예제 #9
0
def api_login():
    """

    This handles logging into the dataportal. 
    The method will check that the user information is valid
    and store the user session information.

    After the user is logged in a JWT token is returned. 
    The token can then be used on any subsequent requests. 

    The API will auto-verify that the token is valid.
    Token expiry will be set to 30mins by default, after which the user will need to login again. 

    """
    username = request.form['login']
    password = request.form['password']

    """
    Handle auth:
    """

    auth = UserModel
    _hash = auth.hash_password(password)
    _verify = auth.verify_password(password, _hash) # Will return true/false is the password doesnt already exist. 
    loggedIn =  str(_verify)

    _username = UserModel.User(username)
    session["user"] = username
    session["loggedIn"] = True

    role = _username.role(username)
    session["role"] = role

    if role == 'admin':
        session["admin"] = True
    else:
        session["admin"] = False

    auth = _username.authenticate(username, password)

    """
    Handle conditional redirect:
    """

    if auth == True:
        if session["user"] == username:
            if session["loggedIn"] == True:
                admin = session["admin"]
                token = jwt.encode({"user": username, "password": password, "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])  #  Expiration is a reserved part of the payload in JWT
                return redirect(url_for('home.home', auth=auth, admin=admin, token=token.decode('UTF-8')))
    if auth != True:
        return redirect('/login_error')
예제 #10
0
    def post(self):
        data = parser.parse_args()
        current_user = UserModel.find_by_username(data['username'])

        # Requirement 7.1.0: informs user of invalid credentials
        if not current_user:
            return {
                'message': 'User {} doesn\'t exist'.format(data['username'])
            }, 404

        if UserModel.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(identity=data['username'])
            refresh_token = create_refresh_token(identity=data['username'])

            # Requirement 8.0.0 and 8.2.1: successful login generates access token and refresh token
            return {
                'message': 'Logged in as {}'.format(current_user.username),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        # Requirement 7.1.0: informs user of invalid credentials
        else:
            return {'message': 'Wrong credentials'}, 401
예제 #11
0
def api_jwt_token_generated():
    """
    Generates the jwt_token. 
    """
    
    username = request.form['username']
    password = request.form['password']

    _username = UserModel.User(username)
    auth = _username.authenticate(username, password)

    if auth == True:
        token = jwt.encode({"user": username, "password": password, "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])  #  Expiration is a reserved part of the payload in JWT
        return {'token': token.decode('UTF-8')}
    if auth != True:
        return {'message': 'not authorized'}
예제 #12
0
def assignAnnotator():
    """
    Assigns a user to a dataset for annotation. 
    """

    cursor = collection.find({})

    data = request.get_json()
    payload = data['data']
    dataset_id = payload['dataset_id']
    username = payload['username']
    password = payload['password']

    _username = UserModel.User(username)
    auth = _username.authenticate(username, password)

    if auth == True:
        document = collection.find_one({'dataset_id': dataset_id})
        if document["annotator"] == "":
            try:
                myquery = {"dataset_id": dataset_id}
                newvalues = {
                    "$set": {
                        "annotator": username,
                        "can_annotate": True
                    }
                }
                collection.update_one(myquery, newvalues)
                """
                Below code: future iteration for recording actions with the governance table. 
                """
                # message = username + " " + "added to dataset" + " " + dataset_id
                # today = date.today()
                # governanceCollection.insert({"name" : username, "role" : role, "notes" : message, "date" : today })

                return username + " " + "is now annotating this dataset."
                # collection.update({"dataset_id": dataset_id}, {"$set": {"annotator": username, "can_annotate": true}}, upsert=False)
            except:
                return "An exception occurred"
        else:
            return "An annotator is already assigned to this dataset. To request a transfer, please contact the system administrator: [email protected]"

    else:
        return "User does not exist"
예제 #13
0
 def get(self):
     return UserModel.return_all()