def test_no_aud(self):
     payload = {
         'user_id': 0
     }
     token = auth.create_jwt(payload, set_audience=False)
     with self.assertRaises(Unauthorized) as cm:
         auth.authenticate_user(token)
     self.assertEqual(cm.exception.description, 'Token invalid')
 def test_expired(self):
     payload = {
         'user_id': 0,
         'exp': datetime(2000, 1, 1)
     }
     token = auth.create_jwt(payload)
     with self.assertRaises(Unauthorized) as cm:
         auth.authenticate_user(token)
     self.assertEqual(cm.exception.description, 'Token is expired')
 def test_invalid_signature(self):
     payload = {
         'user_id': 0,
         'aud': self.client_id
     }
     token = jwt.encode(
         payload,
         'bla'
     )
     with self.assertRaises(Unauthorized) as cm:
         auth.authenticate_user(token)
     self.assertEqual(cm.exception.description, 'Token signature is invalid')
Exemple #4
0
async def login_basic(auth: BasicAuth = Depends(basic_auth)):
    if not auth:
        response = Response(headers={"WWW-Authenticate": "Basic"},
                            status_code=401)
        return response

    try:
        decoded = base64.b64decode(auth).decode("ascii")
        username, _, password = decoded.partition(":")
        user = authenticate_user(users_db, username, password)
        if not user:
            raise HTTPException(status_code=400,
                                detail="Incorrect email or password")

        access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
        access_token = create_access_token(data={"sub": username},
                                           expires_delta=access_token_expires)

        token = jsonable_encoder(access_token)

        response = RedirectResponse(url="/docs")
        response.set_cookie(
            "Authorization",
            value=f"Bearer {token}",
            domain=getenv("WEB_HOSTNAME"),
            httponly=True,
            max_age=1800,
            expires=1800,
        )
        return response

    except Exception:
        response = Response(headers={"WWW-Authenticate": "Basic"},
                            status_code=401)
        return response
 def test_valid_jwt_no_exp(self):
     payload = {
         'user_id': 0,
     }
     token = auth.create_jwt(payload)
     user = auth.authenticate_user(token)
     self.assertEqual(user['user_id'], 0)
Exemple #6
0
    def post(self):
        with locks.global_lock:
            username = self.get_argument('username', None)
            password = self.get_argument('password', None)
            if username is None:
                self.write(
                    render_template('auth_error.html',
                                    error=lc.get('no_username')))
                return
            if password is None:
                self.write(
                    render_template('auth_error.html',
                                    error=lc.get('no_password')))
                return

            try:
                session = auth.authenticate_user(username, password)
            except auth.BaseAuthenticationError as e:
                self.write(
                    render_template('auth_error.html', error=lc.get(e.text)))
                return
            self.set_cookie('session_id',
                            session.id,
                            expires=session.expires_at)
            self.redirect('/')
 def test_valid_jwt(self):
     payload = {
         'user_id': 0,
         'exp': datetime.utcnow() + timedelta(days=1)
     }
     token = auth.create_jwt(payload)
     user = auth.authenticate_user(token)
     self.assertEqual(user['user_id'], 0)
Exemple #8
0
def login():
    data = json.loads(request.data)
    print(data)
    authentication = authenticate_user(data['email'], data['password'])
    if authentication == None:
        return json.dumps({"status": "error"})
    else:
        return json.dumps({"status": "success", "authtoken": authentication})
Exemple #9
0
 def validate_login(request):
     email = request.POST.get('email') or request.GET.get('email')
     password = request.POST.get('password') or request.GET.get('password')
     if request.user.is_authenticated:
         return HttpResponse(json.dumps({'status': -1, 'message': 'User already logged'}))
     if not (password or email):
         return HttpResponse(json.dumps({'status': -1, 'message': 'Empty details entered'}))
     if auth.authenticate_user(email, password):
         return HttpResponse(json.dumps({'status': 1, 'message': 'successful'}))
     return HttpResponse(json.dumps({'status': -1, 'message': 'Please check if your entered correct credentials'}))
Exemple #10
0
async def route_login_access_token(
        form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400,
                            detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(data={"sub": user.username},
                                       expires_delta=access_token_expires)
    return {"access_token": access_token, "token_type": "bearer"}
Exemple #11
0
def login_post():
    username = flask.request.form["username"]
    password = flask.request.form["password"]

    # Link to the TTT React application
    if auth.authenticate_user(username, password):
       return flask.redirect("http://localhost:3000")
    else:
        flask.flash("Whoops, we don't recognize that account! Please try again.")
        return flask.render_template("login.html")
Exemple #12
0
async def user_signin(credentials: SignIn = Depends(),
                      db: Session = Depends(db_session)) -> Token:
    """Authenticate user using specified credentials."""
    user = authenticate_user(db, credentials.username, credentials.password)
    if not user:
        raise HTTPException(status_code=400,
                            detail="Incorrect name or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(data={"login": user.email},
                                       expires_delta=access_token_expires)
    return Token(access_token=access_token, token_type="bearer")
Exemple #13
0
def login_for_access_token(form_data: User, authorize: AuthJWT = Depends()):
    """Check username and password and return a token"""
    user = authenticate_user(users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token = authorize.create_access_token(subject=form_data.username)
    authorize.set_access_cookies(access_token)
    return {"msg": "Successfully login"}
Exemple #14
0
def login():
    if flask.request.method == 'POST':
        username = flask.request.form['username']
        password = flask.request.form['password']
        if not username or not password:
            return flask.render_template('login.html', message='Missing required field')
        elif authenticate_user(username, password):
            flask.session['username'] = flask.request.form['username']
            return flask.render_template('menu.html', username=username)
        else:
            return flask.render_template('login.html', message='Invalid credentials')
    else:
        return flask.render_template('login.html')
Exemple #15
0
def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.email}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}
Exemple #16
0
def main(args):
    if len(args) == 0:
        print("------ Help on Usage -------")
        print(
            "To upload : Client.py put Destination/to/the/src/file  Name_of_the_file_in_the_GFS "
        )
        print("To download: Client.py get Name_of_the_file_in_the_GFS")
        print("To delete: Client.py delete Name_of_the_file_in_the_GFS")
        print(
            "To overwite: Client.py put Destination/to/the/src/file Name_of_the_file_in_the_GFS"
        )
        return

    auth_flag = auth.authenticate_user()
    if auth_flag == -1:
        sys.exit(0)

    try:
        con = rpyc.connect("localhost", port=2131)
        master = con.root.Master()
    except:
        print("Master Server not found ")
        print("launch Master Server and try again")
        return

    init_time = time.time()

    if args[0] == "get":
        get(master, args[1])
    elif args[0] == "put":
        put(master, args[1], args[2])
    elif args[0] == "delete":
        delete(master, args[1])
    elif args[0] == "list":
        list_files(master)
    else:
        print("Incorrect command \n")
        print("------ Help on Usage -------")
        print(
            "To upload : Client.py put Destination/to/the/src/file  Name_of_the_file_in_the_GFS "
        )
        print("To download: Client.py get Name_of_the_file_in_the_GFS")
        print("To delete: Client.py delete Name_of_the_file_in_the_GFS")
        print(
            "To overwite: Client.py put Destination/to/the/src/file Name_of_the_file_in_the_GFS"
        )

    final_time = time.time()
    print(
        f"The time required: {format(final_time - init_time, '0.2f')} seconds")
def login_auth(n_clicks,email,pw):
    '''
    check credentials
    if correct, authenticate the session
    otherwise, authenticate the session and send user to login
    '''
    if n_clicks is None or n_clicks==0:
        return no_update,no_update
    credentials = {'user':email,"password":pw}
    if authenticate_user(credentials):
        session['authed'] = True
        return '/home',''
    session['authed'] = False
    return no_update,dbc.Alert('Incorrect credentials.',color='danger',dismissable=True)
Exemple #18
0
 def login(request):
     if request.method == "POST":
         form = LoginForm(request.POST)
         if form.is_valid():
             email = form.cleaned_data.get('email')
             password = form.cleaned_data.get('password')
             if not auth.does_account_exist(email):
                 return render(request, "oops.html", {'error_code': 100, 'message': 'Account does not exist'})
             user = auth.authenticate_user(email, password)
             if user:
                 auth.login(request, user)
                 return HttpResponseRedirect('/home')
             return HttpResponse(json.dumps({'status': -200, 'message': 'authentication error'}))
         else:
             return HttpResponse('<h1>Invalid form submitted</h1<')
     return HttpResponseRedirect('/')
Exemple #19
0
def login_auth(n_clicks, user, pw):
    '''
    check credentials
    if correct, authenticate the session
    otherwise, authenticate the session and send user to login
    '''
    if n_clicks is None or n_clicks == 0:
        return no_update, no_update
    credentials = {'user': user, "password": pw}
    if authenticate_user(credentials):
        session['authed'] = True
        session['isadmin'] = True if authenticate_admin_user(credentials) else False
        session['user'] = credentials['user']
        session['session_id'] = shortuuid.uuid()
        add_user_session_info(session['user'], 'login', session['session_id'])
        return '/home', ''
    session['authed'] = False
    session['isadmin'] = False
    session['user'] = ''
    session['session_id'] = ''
    return no_update, dbc.Alert('Incorrect credentials.', color='danger', dismissable=True)
Exemple #20
0
def login():
    if 'user' in session:
        flash(ALREADY_LOGGED_IN)
        return redirect(url_for('dashboard'))

    # Logging in
    if request.method == 'POST':
        user = request.form['user']
        pwd = request.form['pwd']

        # Login attempt
        result, passed = auth.authenticate_user(user, pwd)

        if result: # Success
            session['user'] = user
            flash(passed)
            #redirect(url_for('dashboard'))
            return redirect('dashboard')

        else: # Failure
            flash(passed)
            return render_template("login.html")
    else:
        return render_template("login.html")
 def test_invalid_signature(self):
     payload = {"user_id": 0, "aud": self.client_id}
     token = jwt.encode(payload, "bla")
     with self.assertRaises(Unauthorized) as cm:
         auth.authenticate_user(token)
     self.assertEqual(cm.exception.description, "Token signature is invalid")
Exemple #22
0
async def route_login_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect email or password")
    access_token = create_access_token(data={"username": form_data.username})
    return {"id": user.id, "access_token": access_token, "token_type": "bearer"}
 def test_valid_jwt_no_exp(self):
     payload = {"user_id": 0}
     token = auth.create_jwt(payload)
     user = auth.authenticate_user(token)
     self.assertEqual(user["user_id"], 0)
 def test_valid_jwt(self):
     payload = {"user_id": 0, "exp": datetime.utcnow() + timedelta(days=1)}
     token = auth.create_jwt(payload)
     user = auth.authenticate_user(token)
     self.assertEqual(user["user_id"], 0)
 def test_expired(self):
     payload = {"user_id": 0, "exp": datetime(2000, 1, 1)}
     token = auth.create_jwt(payload)
     with self.assertRaises(Unauthorized) as cm:
         auth.authenticate_user(token)
     self.assertEqual(cm.exception.description, "Token is expired")
 def test_invalid_aud(self):
     payload = {"user_id": 0, "aud": "bla"}
     token = auth.create_jwt(payload, set_audience=False)
     with self.assertRaises(Unauthorized) as cm:
         auth.authenticate_user(token)
     self.assertEqual(cm.exception.description, "Incorrect audience")