Browse Source

fix(server): Fix shop api session queries when logged in as admin

Michael Bromley 6 years ago
parent
commit
706088ae58

+ 9 - 1
server/src/api/common/request-context.ts

@@ -6,6 +6,7 @@ import { DEFAULT_LANGUAGE_CODE } from '../../common/constants';
 import { Channel } from '../../entity/channel/channel.entity';
 import { AuthenticatedSession } from '../../entity/session/authenticated-session.entity';
 import { Session } from '../../entity/session/session.entity';
+import { User } from '../../entity/user/user.entity';
 
 /**
  * The RequestContext is intended to hold information relevant to the current request, which may be
@@ -54,9 +55,16 @@ export class RequestContext {
     }
 
     get activeUserId(): ID | undefined {
+        const user = this.activeUser;
+        if (user) {
+            return user.id;
+        }
+    }
+
+    get activeUser(): User | undefined {
         if (this.session) {
             if (this.isAuthenticatedSession(this.session)) {
-                return this.session.user.id;
+                return this.session.user;
             }
         }
     }

+ 18 - 3
server/src/api/resolvers/shop/shop-customer.resolver.ts

@@ -22,9 +22,24 @@ export class ShopCustomerResolver {
     @Query()
     @Allow(Permission.Owner)
     async activeCustomer(@Ctx() ctx: RequestContext): Promise<Customer | undefined> {
-        const userId = ctx.activeUserId;
-        if (userId) {
-            return this.customerService.findOneByUserId(userId);
+        const user = ctx.activeUser;
+        if (user) {
+            const customer = await this.customerService.findOneByUserId(user.id);
+            if (customer) {
+                return customer;
+            }
+            // the user is not a Customer, so it must
+            // be an administrator. In this case we need to return
+            // a "dummy" Customer for the admin user.
+            return new Customer({
+                id: user.id,
+                createdAt: user.createdAt,
+                updatedAt: user.updatedAt,
+                firstName: '[admin]',
+                lastName: user.identifier,
+                emailAddress: 'admin@vendure.io',
+                addresses: [],
+            });
         }
     }
 

+ 1 - 1
server/src/service/services/role.service.ts

@@ -98,7 +98,7 @@ export class RoleService {
             await this.create({
                 code: SUPER_ADMIN_ROLE_CODE,
                 description: SUPER_ADMIN_ROLE_DESCRIPTION,
-                permissions: Object.values(Permission),
+                permissions: Object.values(Permission).filter(p => p !== Permission.Owner),
             });
         }
     }