All files / app/models/membership membership-service.ts

87.84% Statements 65/74
83.33% Branches 20/24
100% Functions 5/5
87.84% Lines 65/74

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 2671x             1x             1x 1x         1x         1x         1x                                                                   61x 61x 61x     61x 2x     59x             59x 9x       9x 9x           8x   1x   1x   1x                 58x     58x                                     14x 14x     14x 2x     12x       12x 12x           9x   3x 3x 3x             9x 3x   3x       6x   6x 3x   3x     3x 3x                   2x 2x   2x                                 1x 1x     1x   1x 1x 1x                     1x   1x                                   17x 17x   17x 17x 17x 10x   7x 6x   1x       1x           1x  
import {
  MembershipId,
  MembershipRepository,
  Membership,
  GroupService,
  MembershipQueryOptions,
} from '@models';
import {
  MembershipNotFoundError,
  CannotChangeOwnerMembershipError,
  NotAdminOfGroupError,
  NotMemberOfGroupError,
  InternalError,
} from '@errors';
import debug from 'debug';
import {bindUser} from '@util/user-bound-logging';
 
/**
 * Logging method.
 */
const log = debug('group-car:membership:service');
 
/**
 * Logging method for errors.
 */
const error = debug('group-car:membership:service:error');
 
/**
 * Service for complex membership operations.
 */
export const MembershipService = {
  /**
   * Retrieves a membership by its ID.
   *
   * Before retrieving the membership, the method makes sure that `currentUser`
   * is authorized to access the membership. A user is authorized if one of
   * two conditions are true.
   *
   *  - `currentUser.id === id.userId`: The user accesses their own memberships
   *  - `currentUser` is member of the group specified in `id`
   *
   * The reasoning behind this is that a user should only be able to get
   * memberships which concern them and not be able to check memberships
   * between every user and group. This would infringe on the privacy of
   * other users.
   *
   * @param currentUser - Currently logged-in user
   * @param id          - ID to search for
   * @param options     - Options for the repository queries
   *
   * @throws {@link NotMemberOfGroupError}
   * If `currentUser.id !== id.userId` and the logged-in user is not
   * a member of the given group
   *
   * @throws {@link MembershipNotFoundError}
   * *Rethrown from `MembershipRepository.findById()`*. Is thrown if the
   * logged-in user is authorized to access the membership,
   * but it doesn't exist
   */
  async findById(
      currentUser: Express.User,
      id: MembershipId,
      options?: Partial<MembershipQueryOptions>,
  ): Promise<Membership> {
    const userId = currentUser.id;
    const userLog = bindUser(log, userId);
    const userError = bindUser(error, userId);
 
    // Check if parameter has correct type
    if (typeof userId !== 'number') {
      throw new TypeError('Id of current user has to be a number');
    }
 
    userLog('Find membership with %o', id);
 
    /*
     * Check if logged-in user is the specified user.
     * If yes, skip the membership check for the logged-in user.
     * If no, check if the logged-in user is a member of the group.
     */
    if (userId !== id.userId) {
      userLog('Not user of membership. ' +
      'Check if member of group');
 
      // Check if the logged-in user is member of that group
      try {
        await MembershipRepository.findById(
            {
              userId: userId,
              groupId: id.groupId,
            },
        );
        userLog('Is member of group referenced in membership');
      } catch (err) {
        Eif (err instanceof MembershipNotFoundError) {
          // Logged-in user is not a member, throw an UnauthorizedError
          userError('Not member of group referenced ' +
          'in membership $o', id);
          throw new NotMemberOfGroupError();
        } else {
          // Something else went wrong, rethrow the error
          userError('Unexpected error', err);
          throw err;
        }
      }
    }
 
    userLog('Can access membership %o', id);
 
    // Call the repository method
    return MembershipRepository.findById(id, options);
  },
 
  /**
   * Updates whether the specified user is an admin
   * of the specified group.
   * @param currentUser - Currently logged-in user
   * @param id          - The id of the membership which should be updated
   * @param isAdmin     - Whether the user should be admin of the group
   *
   * @throws {@link UnauthorizedError} if the currently logged-in
   * user is neither the user for which the admin permission should
   * be changed nor an admin of the referenced group.
   */
  async changeAdminPermission(
      currentUser: Express.User,
      id: MembershipId,
      isAdmin: boolean,
  ): Promise<Membership> {
    const userLog = bindUser(log, currentUser.id);
    const userError = bindUser(error, currentUser.id);
 
    // Check if parameter has correct type
    if (typeof currentUser.id !== 'number') {
      throw new TypeError('Id of current user has to be a number');
    }
 
    userLog('Change admin of membership %o', id);
 
    // Check if current user is an admin of the group
    let currentMembership;
    try {
      currentMembership = await this.findById(
          currentUser, {
            userId: currentUser.id,
            groupId: id.groupId,
          },
      );
      userLog('Is member of group %d', id.groupId);
    } catch (err) {
      Eif (err instanceof MembershipNotFoundError) {
        userError('Is not member of group %d', id.groupId);
        throw new NotMemberOfGroupError();
      } else {
        userError('Unknown error', err);
        throw err;
      }
    }
 
    if (!currentMembership.isAdmin) {
      userError('Is not admin of group %d. ' +
      'Can\'t give or take admin', id.groupId);
      throw new NotAdminOfGroupError();
    }
 
    // Check if user is owner of group
    const group = await GroupService.findById(currentUser, id.groupId);
 
    if (group.ownerId == id.userId || group.Owner?.id === id.userId) {
      userError('Can\'t change admin of ' +
      'owner of group %d', id.groupId);
      throw new CannotChangeOwnerMembershipError();
    }
 
    userLog('Change admin permission');
    return MembershipRepository.changeAdminPermission(id, isAdmin);
  },
 
  /**
   * Gets all memberships of the currently logged-in user.
   * @param currentUser - The currently logged-in user.
   */
  async findAllForUser(
      currentUser: Express.User,
  ): Promise<Membership[]> {
    const userLog = bindUser(log, currentUser.id);
    userLog('Requests to get all their membership');
 
    return MembershipRepository.findAllForUser(
        currentUser.id,
        {
          withUserData: true,
        },
    );
  },
 
  /**
   * Gets all memberships for the specified group.
   * @param currentUser - The currently logged in user
   * @param groupId     - The id of the group
   */
  async findAllForGroup(
      currentUser: Express.User,
      groupId: number,
  ): Promise<Membership[]> {
    const userLog = bindUser(log, currentUser.id);
    const userError = bindUser(error, currentUser.id);
 
    // Check if user is member of group
    userLog('Request to find all memberships for group %d', groupId);
 
    try {
      await MembershipRepository.findById({userId: currentUser.id, groupId});
      userLog('User is a member of group %d', groupId);
    } catch (e) {
      if (e instanceof MembershipNotFoundError) {
        userError('Is not a member of group %d', groupId);
        throw new NotMemberOfGroupError();
      } else {
        userError('Unexpected error while checking membership: %s', e);
        throw e;
      }
    }
 
    userLog('Get all memberships for group %d', groupId);
 
    return MembershipRepository.findAllForGroup(
        groupId,
        {
          withUserData: true,
        },
    );
  },
 
  /**
   * Checks if the current user is a member
   * of the specified group.
   * @param currentUser - The currently logged-in user
   * @param groupId     - The if of the group.
   */
  async isMember(
      currentUser: Express.User,
      groupId: number,
  ): Promise<boolean> {
    const userLog = bindUser(log, currentUser.id);
    const userError = bindUser(error, currentUser.id);
 
    userLog('Requests to check if they are a member of group %d', groupId);
    try {
      await MembershipRepository.findById({groupId, userId: currentUser.id});
      return true;
    } catch (e) {
      if (e instanceof MembershipNotFoundError) {
        return false;
      } else {
        userError(
            'Unexpected error while checking membership for group %d',
            groupId,
        );
        throw new InternalError('Couldn\'t check membership');
      }
    }
  },
};
 
export default MembershipService;