Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logged in state for nautobot-ui #3356

Merged
merged 14 commits into from
Mar 7, 2023
Merged

Conversation

timizuoebideri1
Copy link
Contributor

@timizuoebideri1 timizuoebideri1 commented Feb 23, 2023

Closes: #3242

What's Changed

I simply added an endpoint to retrieve logged in user detail because most of the session base authentication has already been implemented for production (serving react built/complied file).
Because the menu bar design only shows log In or Log Out button without showing any user detail, this endpoint to retrieve logged in user detail is not currently being used to its full potential, but in the future there will be a username place there instead of just a logout icon.

TODO

  • Explanation of Change(s)
  • Added change log fragment(s) (for more information see the documentation)
  • Attached Screenshots, Payload Example
  • Unit, Integration Tests
  • Documentation Updates (when adding/changing features)
  • Example Plugin Updates (when adding/changing features)
  • Outline Remaining Work, Constraints from Design
  • Authenticate using session in react running on node js

Copy link
Member

@bryanculver bryanculver left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timizuoebideri1 in part of #3242 we should be providing a way for the user to log in with the React UI as well. Maybe that's just redirecting to a Django view with a form but I feel that path would be harder to maintain UI-design-wise. We will also have to consider the SSO sign-in flow as well.

@gsnider2195
Copy link
Contributor

Login seems to work for me. We need to create a logout route and see if using the fetch api will work for setting the session cookie on login/logout instead of asking the browser to post directly to Django

@gsnider2195
Copy link
Contributor

Login seems to work for me. We need to create a logout route and see if using the fetch api will work for setting the session cookie on login/logout instead of asking the browser to post directly to Django

Just to clarify we don't need to retrieve any data from the login view from django, only the return code. I'd like to see if we can have the react UI POST the form data to /login and see if the browser intercepts the cookie and sets it

nautobot/core/api/views.py Outdated Show resolved Hide resolved
nautobot/ui/src/components/common/BSNavBar.jsx Outdated Show resolved Hide resolved


const fetcher = (url) => fetch(url, { credentials: "include" }).then((res) => res.json());

export default function BSNavBar() {
const { data, error } = useSWR("/api/get-menu/", fetcher)
const [ isLoggedIn, setIsLoggedIn] = useState(false)
const logout = () => {
axios.get("/api/users/tokens/logout/")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not using useSWR cause this is an operation that would only be done once, and I don't really need the benefits of useSWR here

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to use three different methods for fetch? The only reason I used useSWR is because it's recommended by CRA but if Axios is better we could align on that

@timizuoebideri1 timizuoebideri1 marked this pull request as ready for review March 2, 2023 14:21
@bryanculver bryanculver self-assigned this Mar 3, 2023
nautobot/users/api/views.py Outdated Show resolved Hide resolved
nautobot/users/api/serializers.py Outdated Show resolved Hide resolved
nautobot/ui/src/components/common/BSNavBar.jsx Outdated Show resolved Hide resolved
const { data, error } = useSWR("/api/get-menu/", fetcher)
const [ isLoggedIn, setIsLoggedIn] = useState(false)
useEffect(() => {
// Check if `nautobot-user` exist in localStorage; if found set setIsLoggedIn to true else false
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀

Copy link
Contributor

@HanlinMiao HanlinMiao left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

Comment on lines 72 to 84
@action(methods=["POST"], detail=False, permission_classes=[AllowAny])
def authenticate(self, request):
serializer = serializers.UserLoginSerializer(data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
user = serializer.validated_data["user"]
login(request, user=user)
return Response(status=200)

@action(methods=["GET"], detail=False, permission_classes=[AllowAny])
def logout(self, request):
logout(request)
return Response(status=200)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason we can't just POST to the existing login views? We'll also need to handle the SSO route as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would need a csrf token to be placed in the form, just guessed that's not "API" way of doing things,
But illd try it out

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just attempted it, and I ran into this issue: The status codes 302[OK] and 200[Failure] indicate whether a request was successful or not, but there is no method to manage 302 in "axios."

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed this locally... eww...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Last feedback item: Is there a reason we need to set permission_classes=[AllowAny]?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For logout, that is a mistake, for login yes

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this because it's nested under the tokenviewset?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, can you toss in a TODO to potentially move elsewhere? We either create a user login viewset or fix the weird error codes in the default path.

# Conflicts:
#	nautobot/ui/src/components/common/BSNavBar.jsx
@timizuoebideri1 timizuoebideri1 merged commit b6a04b1 into next-ui-2.0 Mar 7, 2023
@timizuoebideri1 timizuoebideri1 deleted the set_is_logedin_state branch March 7, 2023 22:08
bryanculver added a commit that referenced this pull request Apr 25, 2023
* create list templete

* create add form view templete

* refactor and create NautobotInput Component

* move sites/ to dcim/sites/

* move react back one folder

* move react back one folder

* new changes

* new changes

* get model fields

* copy react files from plugin into nautobot frontend

* fix menu

* Work in progress on table

* json api

* Add get table fields

* fix table header

* Use absolte path

* slugify python

* Field groups

* Account for status and tags

* add react to example plugin

* push all code

* nautobot.2319 React UI components update

* add docker-compose.nodejs.yml to run an nginx reverse proxy for nautobot and nodejs

* remove unused ui prototype

* update to work with nextjs

* Revert "remove unused ui prototype"

This reverts commit 7bccab7.

* make react work?

* add object detail view

* remove comment

* remove comments

* add links to object detail view

* fix region

* Implement basic module federation for webpack

- Publishes `nautobot` module as `remoteEntry.js`
- Implemented webpack `config-overrides.js` using `react-app-rewired` as a dev dependency

* remove nextjs ui

* remove plugin file copy

* optimize dev docker environment

* Update react app build output paths

Output js to static/reactjs
Output css to static/reactcss

* use global router

* add postbuild script to move files to nautobot

* add navmenu headers

* convert prototype to nextjs

* fix some imports

* update to use cross site api calls

* remove nginx config

* update nautobot dev server to use uwsgi instead of runserver

* consolidate frontend pages, update django routing for react

* add plugin full width html fragment support

* fix detail page layout

* add plugin routes

* expose django's login/logout routes

* YEET

* Fixing some lints and bugs.

- Removed bad import in router
- Fixed linting errors for unused imports
- Fixed URL route on table item
- Improved Docker compose file to mount node_modules as a separate volume

* fix permissions issue on docker-compose in linux

* fix linux docker nodejs permissions (really)

* Make detail view generic

* stashing

* add paginator for list view

* yolo

* fix nautobot brand image, add some better looking icons

* stashing

* stashing

* replace react views with base.html that's derived from the react app's index.html

* Something broke but this is progress

* CustomViews and Plugin Components

* fix bug in detail view when json key name starts with underscore

* basic management command to generate ui

* tweaks

* Tweaks and update

* fixes and starts

* update dockerfile to match next

* update poetry lockfile

* linting and minor bug fixes

* clean up imports

* fix bug

* added nginx container in nodejs.yml and made nodejs serve up /static/js/bundle.js (#3057)

Co-authored-by: Hanlin Miao <hanlinmiao@Hanlins-MBP-2.home>

* fix runserver database exhaustion with nginx

* increase keepalive timeout on nginx connection

* Revert "increase keepalive timeout on nginx connection"

This reverts commit d3aabdd.

* increase keepalive timeout on nginx connection

* clean up api for plugin react components

* add web_url to all valid serializers

* remove debug logging

* add login view

* fix js error

* Implemented generic create view for React app.

- Requires the nested serialization changes.
- Implemented nested serialization using `?depth=`
    - Revert nested serializer and `brief=True` pattern
    - Replace it with `depth=?` arguments to views and rendering forms from JSON schema using `drf-react-template-framework`
    - Commented out all `brief=` and associated code
- Updated `RegionSerializer` to have `parent` field fallback to default.

* First pass at #3204 (#3252)

* Some low-hanging fruit fixes to get us closer back to next

* next-ui-2.0 cleanup and commenting (#3285)

* Remove unused code added to example_plugin

* Add a bunch of TODO comments

* More TODO comments

* Black

* Flake8

* Markdownlint

* Pylint

* Removing some more stuff that's not needed at present

* Revert a few things back to baseline

* One more deletion

* Fixes to example_plugin and example_plugin_with_view_override

* Update comments and address a couple of TODOs

* More TODO updates

* web_url fixup

* Added a `nautobot-server build_ui` command (#3306)

- This command does the following from the `nautobot/ui` directory
  - Generates the `app_imports.js` file from any installed plugins
  - Runs `npm install` when `--npm-install` is passed
  - Runs `npm run build`
- This command is now also called by `nautobot-server post_upgrade`, which calls it with `--npm-install`
- Updated the `config-overrides.js` to not hash JS or CSS files so that their raw filename can be stored in static files and referenced using `{% static %}` (e.g. `{% static 'js/main.js %}`) without having to overload the `base.html` template for the web UI
- Updated `nautobot/core/templates/base.html` to link directly to the static files for JS and CSS that get pulled in from the UI build environment by `nautobot-server collectstatic` 
- Parameterized the API key needed for now to read from `NAUTOBOT_API_TOKEN` environment variable
- `app_imports.js` now renders with relative paths vs. absolute paths making commits that happen compatible across Docker-local and production use-cases.
- Restored the `/plugins/` route and the `InstalledPlugins.jsx` module
- The `build` command runs `npm` silently by default to hide the debug/warn/error messages unless `-v 2` or `-v 3` are passed.
- There is some `console.log` output that is now not displayed unless `NAUTOBOT_DEBUG` environment variable is set. The `build_ui` command will also set this if verbosity is desired.
- Implemented a new `invoke version` task to align versions of core with UI apps.
  - Will bump both `pyproject.toml` and `package.json` to keep them in sync.
  - If no argument is provided, displays the versions instead.
- Also added `NAUTOBOT_UI_DIR` into `nautobot.core.settings` so that it can be easily reused
- Moved `nautobot_ui` to `nautobot/ui`
- `nautobot/ui` is now included in the package build
- Added a basic README file back to `nautobot/ui`
- Renamed all UI references of "plugin" to "app"

After using `build_ui` it's possible to serve the entire application using Django now without requiring `node`. Of course for development `node` will still be desirable due to live rendering.

* setState for islogged in

* Revert "setState for islogged in"

This reverts commit 596d9c1.

* remove ourrunserver reference in docker compose (#3366)

* UI 2.0 remove nginx container (#3367)

* Initial removal of react-bootstrap and addition of nautobot-ui

* Clean up devDependencies

* Simplify tasks.py

* Updates from feedback

* Add node_modules ignore

* move 'api/' ui related urls under 'api/ui/' (#3385)

* move 'api/' ui related urls under 'api/ui/'

* flake8

* address PR feedback

* exclude get-menu api endpoint from OpenAPI schema and add documentation for UI-related API endpoints

* flake8

* mdlint

* elaborate UI-related endpoints documentation

* update mkdocs.yml

---------

Co-authored-by: Hanlin Miao <hanlinmiao@Hanlins-MBP-2.home>

* Logged in state for nautobot-ui (#3356)

* Update from fix nautobot/nautobot-ui#9

* Black

* Hadolint

* More hadolint

* UI docker dev environment tweaks (#3408)

* Don't copy node_modules and UI build when rebuilding docker image

* Capture npm output and print it in case of failures

* Create docker volume for node_modules, change container startup, update docs

* nautobot-ui is public now; can use node:18-slim

* Add TODO comments

* Add unittest for all react components (#3404)

* Add test for component common

* common test case

* Done testing core

* Add test for BSTableItem Component

* Add partial views test

* Add test for views

* add doc

* run ui unittest

* Apply suggestions from code review

Co-authored-by: Hanlin Miao <46973263+HanlinMiao@users.noreply.github.com>

* fix markdown

* update ReadMe

* Update nautobot/ui/README.md

Co-authored-by: Bryan Culver <31187+bryanculver@users.noreply.github.com>

* Merge conflicts

* Update README.md

---------

Co-authored-by: Hanlin Miao <46973263+HanlinMiao@users.noreply.github.com>
Co-authored-by: Bryan Culver <31187+bryanculver@users.noreply.github.com>
Co-authored-by: Bryan Culver <bryan.culver@networktocode.com>

* UI 2.0 Cleanup (#3444)

* Provide a way to refresh CSRF without shortcutting CSRF protections

* Session endpoint

* Stashing to switch between computers

* more stashing

* yeeet

* This is going to be a lot

* Updates

* Updates from feedback

* Black & flake8

* Fix indention

* Remove top-level package lock

* Revert bad merge

* UI 2.0: Cleanup Router Links, Import Font as Source (#3482)

* Cleanup Router Links

* Move font to built-in instead of served via Google Fonts.

* Remove unneccessary import

* UI 2.0: Introduce Prettier, Use ESLint for Formatting and Linting (#3531)

* Move to craco (#3546)

Fix Jest testing

Remove should be ignored paths file as this is autogenerated

Scope creep avoid get tests passing so we can demonstrate it's working.

Prettier...

Add base paths for testing

No cached example, just copy the template in CI

Mock would prefer a file exists for app_imports.js

* Add New UI Toggle (#3615)

* Add New UI Toggle

* Add changelog fragment.

* Prettier

* Fix corrupted package-lock.json (#3618)

* Fix corrupted package-lock.json

* Add changelog fragment.

* Remove duplicate package for nautbot-ui

* Get tests passing for UI 2.0 (#3632)

* Get tests passing for UI 2.0

* Add changelog fragment.

* Updates from feedback

* Exception handling

* Fix CI step merge

* Pylint

* Fix changes from next

* UI 2.0 Implement GenericView component (#3626)

* [UI 2.0] Implement GenericView component

* [UI 2.0] Add missing objectData prop to GenericView in ObjectRetrieve view

* [UI 2.0] Remove Current route is ... debug message

* Move popover to it's own component.

---------

Co-authored-by: Bryan Culver <bryan.culver@networktocode.com>
Co-authored-by: Bryan Culver <me@bryanculver.com>

* 👟

---------

Co-authored-by: Timizuo <timizuoebideri@gmail.com>
Co-authored-by: Chris Thant <chris.thant@networktocode.com>
Co-authored-by: Gary Snider <gary.snider@networktocode.com>
Co-authored-by: jathanism <jathan@gmail.com>
Co-authored-by: Hanlin Miao <46973263+HanlinMiao@users.noreply.github.com>
Co-authored-by: Hanlin Miao <hanlinmiao@Hanlins-MBP-2.home>
Co-authored-by: Glenn Matthews <glenn.matthews@networktocode.com>
Co-authored-by: Gary Snider <75227981+gsnider2195@users.noreply.github.com>
Co-authored-by: Timizuo <94907097+timizuoebideri1@users.noreply.github.com>
Co-authored-by: Norbert Mieczkowski <117445994+norbert-mieczkowski-codilime@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

UI 2.0: Authentication (session, cookies, etc) to be able to hit both the API and UI
4 participants