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

feat(core) Config to disable Anonymous session creation #2990

Closed
wants to merge 1 commit into from
Closed

feat(core) Config to disable Anonymous session creation #2990

wants to merge 1 commit into from

Conversation

arrrrny
Copy link
Contributor

@arrrrny arrrrny commented Aug 1, 2024

Description

Added config to disable Anonymous session creation. This allows only authenticated users to add to cart. It helps preventing bot/scrapers to make operations on shop-api, allows only authenticated users to view products etc.

Default is false

Breaking changes

No

Checklist

📌 Always:

  • I have set a clear title
  • My PR is small and contains a single feature
  • I have checked my own PR

👍 Most of the time:

  • I have added or updated test cases
  • I have updated the README if needed

I have read the CLA Document and I hereby sign the CLA

…ted users to add to cart. This helps preventing bot/scrapers to make operations on shop-api, allows only authenticated users to view products etc.
Copy link

vercel bot commented Aug 1, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
docs ✅ Ready (Inspect) Visit Preview Aug 1, 2024 10:10am

@michaelbromley
Copy link
Member

Hi,

Thanks for the suggestion. Before going with adding another config value, I'd like to explore how this can be done using middleware and thus not requiring a new config property (I bias towards only adding new config props when absolutely necessary).

Here's a suggestion you can try. I didn't test it yet but I think this or something very similar should work:

// src/plugins/disable-anonymous-access/api/middleware.ts

import { Injectable, NestMiddleware } from '@nestjs/common'
import {
  CachedSession,
  ConfigService,
  SessionService,
  extractSessionToken,
} from '@vendure/core'
import { NextFunction, Request, Response } from 'express'

@Injectable()
export class DisableAnonymousAccessMiddleware implements NestMiddleware {
  constructor(
    private sessionService: SessionService,
    private configService: ConfigService,
  ) {}

  async use(req: Request, res: Response, next: NextFunction) {
    const isLoggedIn = await this.isLoggedIn(req)
    if (!isLoggedIn) {
      return res.status(403).send('Forbidden')
    }
    next()
  }

  private async isLoggedIn(req: Request): Promise<boolean> {
    const session = await this.getSession(req)
    return !!session?.user
  }

  private async getSession(req: Request): Promise<CachedSession | undefined> {
    const { tokenMethod } = this.configService.authOptions
    const sessionToken = extractSessionToken(req, tokenMethod)
    return sessionToken
      ? await this.sessionService.getSessionFromToken(sessionToken)
      : undefined
  }
}
// src/plugins/disable-anonymous-access/disable-anonymous-access.plugin.ts

import { MiddlewareConsumer, NestModule } from '@nestjs/common'
import { PluginCommonModule, VendurePlugin } from '@vendure/core'
import { DisableAnonymousAccessMiddleware } from './api/middleware'

@VendurePlugin({
  // ... omitted
})
export class DisableAnonymousAccessPlugin implements NestModule {

  configure(consumer: MiddlewareConsumer) {
    consumer.apply(DisableAnonymousAccessMiddleware).forRoutes('shop-api')
  }
}

@arrrrny
Copy link
Contributor Author

arrrrny commented Aug 5, 2024

I agree with that. I am launching UserCheckout plugin today which I must have this feature conjuction with that. Let me see if I can make it with a plugin. other than that I did not see any side effects of this. I spent last 3 days on Vendure Auth and User checkout learnt a lot.

@arrrrny
Copy link
Contributor Author

arrrrny commented Aug 5, 2024

Main hickup I had with the system that Permission.Authenticated does not aspply to users system wide. It is tied to roles Customer and Admins. Any external auth shoul implement its role and Push Autheticated to that role which I will do that on firebase. User entity is not much of a thing without being a customer.

@arrrrny
Copy link
Contributor Author

arrrrny commented Aug 5, 2024

There is a catch 22, it needs to access to authenticate method and middleware blocks all. I figured it out by parsing body and allowing methods as public

@arrrrny arrrrny closed this Aug 5, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Aug 5, 2024
@michaelbromley
Copy link
Member

Great thanks for sharing your solution as a plugin too!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants