RocketChat/Rocket.Chat

View on GitHub
apps/meteor/app/api/server/api.ts

Summary

Maintainability
F
1 wk
Test Coverage

File api.ts has 902 lines of code (exceeds 250 allowed). Consider refactoring.
Open

import type { IMethodConnection, IUser, IRoom } from '@rocket.chat/core-typings';
import { Logger } from '@rocket.chat/logger';
import { Users } from '@rocket.chat/models';
import { Random } from '@rocket.chat/random';
import type { JoinPathPattern, Method } from '@rocket.chat/rest-typings';
Severity: Major
Found in apps/meteor/app/api/server/api.ts - About 2 days to fix

    Function addRoute has 166 lines of code (exceeds 25 allowed). Consider refactoring.
    Open

        public addRoute<
            TSubPathPattern extends string,
            TPathPattern extends JoinPathPattern<TBasePath, TSubPathPattern>,
            TOptions extends Options,
        >(subpaths: TSubPathPattern[], options: TOptions, endpoints?: Operations<TPathPattern, TOptions>): void {
    Severity: Major
    Found in apps/meteor/app/api/server/api.ts - About 6 hrs to fix

      Function _initAuth has 157 lines of code (exceeds 25 allowed). Consider refactoring.
      Open

          protected _initAuth(): void {
              const loginCompatibility = (bodyParams: Record<string, any>, request: Request): Record<string, any> => {
                  // Grab the username or email that the user is logging in with
                  const { user, username, email, password, code: bodyCode } = bodyParams;
                  let usernameToLDAPLogin = '';
      Severity: Major
      Found in apps/meteor/app/api/server/api.ts - About 6 hrs to fix

        Function _initAuth has a Cognitive Complexity of 34 (exceeds 5 allowed). Consider refactoring.
        Open

            protected _initAuth(): void {
                const loginCompatibility = (bodyParams: Record<string, any>, request: Request): Record<string, any> => {
                    // Grab the username or email that the user is logging in with
                    const { user, username, email, password, code: bodyCode } = bodyParams;
                    let usernameToLDAPLogin = '';
        Severity: Minor
        Found in apps/meteor/app/api/server/api.ts - About 5 hrs to fix

        Cognitive Complexity

        Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

        A method's cognitive complexity is based on a few simple rules:

        • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
        • Code is considered more complex for each "break in the linear flow of the code"
        • Code is considered more complex when "flow breaking structures are nested"

        Further reading

        Function _internalRouteActionHandler has 124 lines of code (exceeds 25 allowed). Consider refactoring.
        Open

                            async function _internalRouteActionHandler() {
                                const rocketchatRestApiEnd = metrics.rocketchatRestApi.startTimer({
                                    method,
                                    version,
                                    ...(prometheusAPIUserAgent && { user_agent: this.request.headers['user-agent'] }),
        Severity: Major
        Found in apps/meteor/app/api/server/api.ts - About 4 hrs to fix

          APIClass has 22 functions (exceeds 20 allowed). Consider refactoring.
          Open

          export class APIClass<TBasePath extends string = ''> extends Restivus {
              protected apiPath?: string;
          
              public authMethods: ((...args: any[]) => any)[];
          
          
          Severity: Minor
          Found in apps/meteor/app/api/server/api.ts - About 2 hrs to fix

            Function post has 50 lines of code (exceeds 25 allowed). Consider refactoring.
            Open

                            async post() {
                                const request = this.request as unknown as Request;
                                const args = loginCompatibility(this.bodyParams, request);
            
                                const invocation = new DDPCommon.MethodInvocation({
            Severity: Minor
            Found in apps/meteor/app/api/server/api.ts - About 2 hrs to fix

              Function loginCompatibility has 49 lines of code (exceeds 25 allowed). Consider refactoring.
              Open

                      const loginCompatibility = (bodyParams: Record<string, any>, request: Request): Record<string, any> => {
                          // Grab the username or email that the user is logging in with
                          const { user, username, email, password, code: bodyCode } = bodyParams;
                          let usernameToLDAPLogin = '';
              
              
              Severity: Minor
              Found in apps/meteor/app/api/server/api.ts - About 1 hr to fix

                Function _getUserAuth has a Cognitive Complexity of 13 (exceeds 5 allowed). Consider refactoring.
                Open

                const getUserAuth = function _getUserAuth(...args: any[]): {
                    token: string;
                    user: (this: Restivus) => Promise<{ userId: string; token: string }>;
                } {
                    const invalidResults = [undefined, null, false];
                Severity: Minor
                Found in apps/meteor/app/api/server/api.ts - About 1 hr to fix

                Cognitive Complexity

                Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

                A method's cognitive complexity is based on a few simple rules:

                • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
                • Code is considered more complex for each "break in the linear flow of the code"
                • Code is considered more complex when "flow breaking structures are nested"

                Further reading

                Function _defaultOptionsEndpoint has 37 lines of code (exceeds 25 allowed). Consider refactoring.
                Open

                const defaultOptionsEndpoint = async function _defaultOptionsEndpoint(this: Restivus): Promise<void> {
                    // check if a pre-flight request
                    if (!this.request.headers['access-control-request-method'] && !this.request.headers.origin) {
                        this.done();
                        return;
                Severity: Minor
                Found in apps/meteor/app/api/server/api.ts - About 1 hr to fix

                  Function logout has 29 lines of code (exceeds 25 allowed). Consider refactoring.
                  Open

                          const logout = async function (this: Restivus): Promise<{ status: string; data: { message: string } }> {
                              // Remove the given auth token from the user's account
                              const authToken = this.request.headers['x-auth-token'];
                              const hashedToken = Accounts._hashLoginToken(authToken);
                              const tokenLocation = self._config?.auth?.token;
                  Severity: Minor
                  Found in apps/meteor/app/api/server/api.ts - About 1 hr to fix

                    Function constructor has 29 lines of code (exceeds 25 allowed). Consider refactoring.
                    Open

                        constructor(properties: IAPIProperties) {
                            super(properties);
                            this.apiPath = properties.apiPath;
                            this.authMethods = [];
                            this.fieldSeparator = '.';
                    Severity: Minor
                    Found in apps/meteor/app/api/server/api.ts - About 1 hr to fix

                      Function addRateLimiterRuleForRoutes has 27 lines of code (exceeds 25 allowed). Consider refactoring.
                      Open

                          protected addRateLimiterRuleForRoutes({
                              routes,
                              rateLimiterOptions,
                              endpoints,
                              apiVersion,
                      Severity: Minor
                      Found in apps/meteor/app/api/server/api.ts - About 1 hr to fix

                        Function _getUserAuth has 26 lines of code (exceeds 25 allowed). Consider refactoring.
                        Open

                        const getUserAuth = function _getUserAuth(...args: any[]): {
                            token: string;
                            user: (this: Restivus) => Promise<{ userId: string; token: string }>;
                        } {
                            const invalidResults = [undefined, null, false];
                        Severity: Minor
                        Found in apps/meteor/app/api/server/api.ts - About 1 hr to fix

                          Function failure has a Cognitive Complexity of 9 (exceeds 5 allowed). Consider refactoring.
                          Open

                              public failure<T, TErrorType extends string, TStack extends string, TErrorDetails>(
                                  result?: T,
                                  errorType?: TErrorType,
                                  stack?: TStack,
                                  error?: { details: TErrorDetails },
                          Severity: Minor
                          Found in apps/meteor/app/api/server/api.ts - About 55 mins to fix

                          Cognitive Complexity

                          Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

                          A method's cognitive complexity is based on a few simple rules:

                          • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
                          • Code is considered more complex for each "break in the linear flow of the code"
                          • Code is considered more complex when "flow breaking structures are nested"

                          Further reading

                          Function getRequestIP has a Cognitive Complexity of 8 (exceeds 5 allowed). Consider refactoring.
                          Open

                          const getRequestIP = (req: Request): string | null => {
                              const socket = req.socket || req.connection?.socket;
                              const remoteAddress =
                                  req.headers['x-real-ip'] || (typeof socket !== 'string' && (socket?.remoteAddress || req.connection?.remoteAddress || null));
                              let forwardedFor = req.headers['x-forwarded-for'];
                          Severity: Minor
                          Found in apps/meteor/app/api/server/api.ts - About 45 mins to fix

                          Cognitive Complexity

                          Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

                          A method's cognitive complexity is based on a few simple rules:

                          • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
                          • Code is considered more complex for each "break in the linear flow of the code"
                          • Code is considered more complex when "flow breaking structures are nested"

                          Further reading

                          Avoid too many return statements within this function.
                          Open

                              return forwardedFor[forwardedFor.length - httpForwardedCount];
                          Severity: Major
                          Found in apps/meteor/app/api/server/api.ts - About 30 mins to fix

                            Avoid too many return statements within this function.
                            Open

                                        return auth;
                            Severity: Major
                            Found in apps/meteor/app/api/server/api.ts - About 30 mins to fix

                              Avoid too many return statements within this function.
                              Open

                                              return {
                                                  totp: {
                                                      code,
                                                      login: settings.get('LDAP_Enable') ? objectToLDAPLogin : auth,
                                                  },
                              Severity: Major
                              Found in apps/meteor/app/api/server/api.ts - About 30 mins to fix

                                Identical blocks of code found in 2 locations. Consider refactoring.
                                Open

                                            validate: (params: {
                                                user: { value: string };
                                                name?: { key: string; value?: string };
                                                members?: { key: string; value?: string[] };
                                                customFields?: { key: string; value?: string };
                                Severity: Major
                                Found in apps/meteor/app/api/server/api.ts and 1 other location - About 3 hrs to fix
                                apps/meteor/app/api/server/v1/channels.ts on lines 644..650

                                Duplicated Code

                                Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

                                Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

                                When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

                                Tuning

                                This issue has a mass of 113.

                                We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

                                The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

                                If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

                                See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

                                Refactorings

                                Further Reading

                                Similar blocks of code found in 2 locations. Consider refactoring.
                                Open

                                    public internalError<T>(msg?: T): InternalError<T> {
                                        return {
                                            statusCode: 500,
                                            body: {
                                                success: false,
                                Severity: Major
                                Found in apps/meteor/app/api/server/api.ts and 1 other location - About 1 hr to fix
                                apps/meteor/app/api/server/api.ts on lines 297..305

                                Duplicated Code

                                Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

                                Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

                                When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

                                Tuning

                                This issue has a mass of 60.

                                We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

                                The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

                                If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

                                See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

                                Refactorings

                                Further Reading

                                Similar blocks of code found in 2 locations. Consider refactoring.
                                Open

                                    public unauthorized<T>(msg?: T): UnauthorizedResult<T> {
                                        return {
                                            statusCode: 403,
                                            body: {
                                                success: false,
                                Severity: Major
                                Found in apps/meteor/app/api/server/api.ts and 1 other location - About 1 hr to fix
                                apps/meteor/app/api/server/api.ts on lines 287..295

                                Duplicated Code

                                Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

                                Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

                                When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

                                Tuning

                                This issue has a mass of 60.

                                We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

                                The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

                                If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

                                See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

                                Refactorings

                                Further Reading

                                Identical blocks of code found in 2 locations. Consider refactoring.
                                Open

                                const getUserAuth = function _getUserAuth(...args: any[]): {
                                    token: string;
                                    user: (this: Restivus) => Promise<{ userId: string; token: string }>;
                                } {
                                Severity: Minor
                                Found in apps/meteor/app/api/server/api.ts and 1 other location - About 50 mins to fix
                                apps/meteor/app/api/server/api.ts on lines 996..996

                                Duplicated Code

                                Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

                                Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

                                When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

                                Tuning

                                This issue has a mass of 51.

                                We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

                                The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

                                If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

                                See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

                                Refactorings

                                Further Reading

                                Identical blocks of code found in 2 locations. Consider refactoring.
                                Open

                                    getUserAuth: () => { token: string; user: (this: Restivus) => Promise<{ userId: string; token: string }> };
                                Severity: Minor
                                Found in apps/meteor/app/api/server/api.ts and 1 other location - About 50 mins to fix
                                apps/meteor/app/api/server/api.ts on lines 893..896

                                Duplicated Code

                                Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

                                Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

                                When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

                                Tuning

                                This issue has a mass of 51.

                                We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

                                The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

                                If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

                                See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

                                Refactorings

                                Further Reading

                                Similar blocks of code found in 2 locations. Consider refactoring.
                                Open

                                settings.watch<number>('API_Enable_Rate_Limiter_Limit_Calls_Default', (value) => {
                                    defaultRateLimiterOptions.numRequestsAllowed = value;
                                    API.v1.reloadRoutesToRefreshRateLimiter();
                                });
                                Severity: Minor
                                Found in apps/meteor/app/api/server/api.ts and 1 other location - About 35 mins to fix
                                apps/meteor/app/api/server/api.ts on lines 1050..1053

                                Duplicated Code

                                Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

                                Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

                                When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

                                Tuning

                                This issue has a mass of 47.

                                We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

                                The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

                                If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

                                See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

                                Refactorings

                                Further Reading

                                Similar blocks of code found in 2 locations. Consider refactoring.
                                Open

                                settings.watch<number>('API_Enable_Rate_Limiter_Limit_Time_Default', (value) => {
                                    defaultRateLimiterOptions.intervalTimeInMS = value;
                                    API.v1.reloadRoutesToRefreshRateLimiter();
                                });
                                Severity: Minor
                                Found in apps/meteor/app/api/server/api.ts and 1 other location - About 35 mins to fix
                                apps/meteor/app/api/server/api.ts on lines 1055..1058

                                Duplicated Code

                                Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

                                Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

                                When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

                                Tuning

                                This issue has a mass of 47.

                                We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

                                The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

                                If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

                                See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

                                Refactorings

                                Further Reading

                                Similar blocks of code found in 2 locations. Consider refactoring.
                                Open

                                    const origins = CORSOriginSetting.trim()
                                        .split(',')
                                        .map((origin) => String(origin).trim().toLocaleLowerCase());
                                Severity: Minor
                                Found in apps/meteor/app/api/server/api.ts and 1 other location - About 35 mins to fix
                                apps/meteor/ee/server/apps/communication/uikit.ts on lines 29..32

                                Duplicated Code

                                Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

                                Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

                                When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

                                Tuning

                                This issue has a mass of 46.

                                We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

                                The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

                                If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

                                See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

                                Refactorings

                                Further Reading

                                There are no issues that match your filters.

                                Category
                                Status