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

Login and Register APIs integrated along with some file structure improvements #32

Merged
merged 2 commits into from
Oct 11, 2024

Conversation

this-is-mjk
Copy link
Collaborator

@this-is-mjk this-is-mjk commented Oct 11, 2024

Description

Integration first stage with login and register working

How Has This Been Tested?

locally every function, then the unit test

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • [ x] New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • [x ] My code follows the code style of this project.
  • [x ] My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

Summary by Sourcery

Implement user authentication features including registration and login with server-side integration. Introduce token management and logout services. Refactor dashboard components to use a shared profile card. Enhance error handling and UI feedback during authentication processes.

New Features:

  • Implement user registration and login functionality with server-side integration, including form validation and API calls.
  • Add a profile card component that displays user information retrieved from a JWT token.
  • Introduce a token service for managing JWT tokens, including saving, retrieving, and validating tokens.
  • Add a logout service to handle user logout and navigation to the login page.

Enhancements:

  • Refactor the user and admin dashboard components to use a shared profile card component.
  • Improve error handling in the server-side user controller, including more descriptive error messages and handling for specific HTTP status codes.
  • Enhance the login and registration UI with loading indicators to improve user experience during API calls.

Build:

  • Add the flutter_secure_storage dependency to manage secure storage of JWT tokens.

Tests:

  • Update login page tests to reflect changes in input validation, specifically for integer-based user IDs.

Copy link
Contributor

sourcery-ai bot commented Oct 11, 2024

Reviewer's Guide by Sourcery

This pull request implements login and registration functionality, along with some server-side changes and file restructuring. The changes include new API endpoints for user authentication, token-based authentication, secure token storage, and improvements to the user interface for login and registration. The pull request also introduces role-based routing and dashboard views for different user types.

Sequence diagram for user registration process

sequenceDiagram
    actor User
    participant App as Mobile App
    participant Server
    User->>App: Fill registration form
    App->>Server: POST /user/register
    Server-->>App: Registration success
    App->>User: Show success message
    App->>User: Navigate to picture upload
    User->>App: Upload picture
    App->>Server: POST /upload/picture
    Server-->>App: Picture upload success
    App->>User: Navigate to login
Loading

Sequence diagram for user login process

sequenceDiagram
    actor User
    participant App as Mobile App
    participant Server
    User->>App: Enter credentials
    App->>Server: POST /user/login
    alt Login success
        Server-->>App: Return JWT token
        App->>User: Navigate to dashboard
    else Login failure
        Server-->>App: Error message
        App->>User: Show error message
    end
Loading

Class diagram for updated user authentication

classDiagram
    class TokenService {
        +saveToken(String token)
        +getToken() String?
        +deleteToken()
        +isTokenValid() bool
        +getDecodedToken() Map<String, dynamic>?
    }
    class LogoutService {
        +logoutAndNavigateToLogin(BuildContext context)
    }
    class LoginPageState {
        +_loginUser()
        +_navigateBasedOnRole(String token)
    }
    class RegistrationPageState {
        +_submit()
    }
    TokenService <|-- LogoutService
    LoginPageState --> TokenService
    RegistrationPageState --> TokenService
Loading

File-Level Changes

Change Details Files
Implemented user authentication with JWT
  • Added login functionality with JWT token generation
  • Implemented token storage using FlutterSecureStorage
  • Created TokenService for managing JWT tokens
  • Added token validation and decoding methods
lib/screens/login_page.dart
lib/services/store.dart
server/controllers/userController.js
Implemented user registration
  • Added registration form with input validation
  • Created API endpoint for user registration
  • Implemented password hashing for secure storage
lib/screens/registration.dart
server/controllers/userController.js
Implemented role-based routing and dashboards
  • Created separate dashboard views for admin and regular users
  • Implemented dynamic routing based on user role
  • Added logout functionality with proper token cleanup
lib/screens/user_dashboard.dart
lib/screens/admin_dashboard.dart
lib/main.dart
lib/services/logout.dart
Improved server-side authentication and error handling
  • Added middleware for token authentication
  • Implemented proper error responses for authentication failures
  • Added token expiration handling
server/middlewares/authenticate.js
server/routes/userRoutes.js
Refactored and restructured the codebase
  • Moved common components to separate files
  • Updated import statements to reflect new file structure
  • Renamed files for consistency
lib/components/drawer.dart
lib/components/profile_card.dart
lib/screens/capture_pic.dart
lib/screens/location_page.dart

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @this-is-mjk - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider improving error handling consistency across the application, especially in API calls and user interactions.
  • For future PRs, try to break down large changes into smaller, more focused pull requests to facilitate easier review and reduce the risk of introducing bugs.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

lib/screens/registration.dart Show resolved Hide resolved
@@ -15,6 +16,9 @@ exports.authenticateToken = (req, res, next) => {
req.userId = decoded.user.userId;
next();
} catch (err) {
if (err.name === "TokenExpiredError") {
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion: Improve authentication error handling

Consider adding more specific error handling for different types of authentication errors. This could include distinguishing between expired tokens, invalid signatures, and other potential JWT verification failures.

    if (err.name === "TokenExpiredError") {
      return res.status(401).json({ message: "Token expired" });
    } else if (err.name === "JsonWebTokenError") {
      return res.status(401).json({ message: "Invalid token" });
    } else if (err.name === "NotBeforeError") {
      return res.status(401).json({ message: "Token not active" });
    }

}
});

try {
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (complexity): Consider refactoring the input validation in the markAttendance function to reduce complexity.

The markAttendance function has indeed become more complex with the addition of nested conditional statements for parameter validation. While input validation is crucial, we can simplify this structure to improve readability and maintainability without losing functionality. Consider refactoring the validation logic using object destructuring with default values and a single validation check:

const markAttendance = async (req, res) => {
  console.log("Mark User Attendance got hit!");
  const { id = '', lat = '', log = '', locationName = '' } = req.body;

  try {
    if (!id || !lat || !log || !locationName || isNaN(parseFloat(lat)) || isNaN(parseFloat(log))) {
      return res.status(400).json({
        success: false,
        error: {
          code: "INVALID_PARAMETERS",
          message: "Please provide valid id, lat, log, and locationName",
        },
      });
    }

    // Rest of the function remains unchanged
    const location = await prisma.location.create({
      // ...
    });

    // ...
  } catch (err) {
    console.error(err.message);
    res.status(500).send("Server Error");
  }
};

This refactoring achieves the following:

  1. Uses object destructuring with default empty strings, simplifying the initial parameter extraction.
  2. Combines all validation checks into a single if statement, reducing nesting and improving readability.
  3. Merges the "missing parameters" and "invalid coordinates" checks into one error response, simplifying the error handling logic.

These changes maintain the added validation while reducing the overall complexity of the function.

@its-me-yps its-me-yps merged commit a677b38 into pclubiitk:main Oct 11, 2024
1 check passed
@its-me-yps its-me-yps changed the title login and register done, along with some required changes in server, and some more file structuring Login and Register APIs integrated along with some file structure improvements Oct 11, 2024
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.

2 participants