Skip to content
Snippets Groups Projects
Select Git revision
  • 690cfff79cdd8c932ad95661d99dc0ed0f8c02b3
  • main default protected
  • jw_sonar
  • v6.0.0 protected
  • bedran_exercise-list
  • ask-user-to-delete-exercises-on-duplicates
  • update-dependencies
  • jw_sonar_backup
  • add_route_assignments
  • 6.0.0-dev
  • 5.0.1
  • 5.0.0
  • 4.1.0
  • 4.0.0
  • 3.5.3
  • 3.5.2
  • 3.5.1
  • 3.5.0
  • 3.4.2
  • 3.4.1
  • 3.4.0
  • 3.3.0
  • 3.2.0
  • 3.1.3
  • 3.1.2
  • 3.1.1
  • 3.1.0
  • 3.0.1
  • 3.0.0
29 results

Session.ts

Blame
  • Session.ts 2.86 KiB
    import { getReasonPhrase, StatusCodes } from 'http-status-codes';
    import * as jwt                         from 'jsonwebtoken';
    import { JwtPayload }                   from 'jsonwebtoken';
    import Config                           from '../config/Config';
    import express                          from 'express';
    import UserManager                      from '../managers/UserManager';
    import DojoResponse                     from '../shared/types/Dojo/DojoResponse';
    import { User }                         from '../types/DatabaseTypes';
    
    
    class Session {
        private _profile!: User;
    
        get profile(): User {
            return this._profile;
        }
    
        set profile(newProfile: User) {
            delete newProfile.password;
            this._profile = newProfile;
        }
    
        constructor() { }
    
        async initSession(req: express.Request, res: express.Response) {
            const authorization = req.headers.authorization;
            if ( authorization ) {
                if ( authorization.startsWith('Bearer ') ) {
                    const jwtToken = authorization.replace('Bearer ', '');
    
                    try {
                        const jwtData = jwt.verify(jwtToken, Config.jwtConfig.secret) as JwtPayload;
    
                        if ( jwtData.profile ) {
                            this.profile = jwtData.profile;
                            this.profile = await UserManager.getById(this.profile.id!) ?? this.profile;
                        }
                    } catch ( err ) {
                        res.sendStatus(StatusCodes.UNAUTHORIZED).end();
                    }
                }
            }
        }
    
        private static getToken(profileJson: any): string | null {
            return profileJson === null ? null : jwt.sign({ profile: profileJson }, Config.jwtConfig.secret, Config.jwtConfig.expiresIn > 0 ? { expiresIn: Config.jwtConfig.expiresIn } : {});
        }
    
        private async getResponse<T>(code: number, data: T, descriptionOverride?: string): Promise<DojoResponse<T>> {
            const profileJson = this.profile;
    
            let reasonPhrase = '';
    
            try {
                reasonPhrase = getReasonPhrase(code);
            } catch {}
    
            return {
                timestamp   : (new Date()).toISOString(),
                code        : code,
                description : descriptionOverride ? descriptionOverride : reasonPhrase,
                sessionToken: Session.getToken(profileJson),
                data        : data
            };
        }
    
        /*
         Send a response to the client
         Information: Data could be a promise or an object. If it's a promise, we wait on the data to be resolved before sending the response
         */
        sendResponse(res: express.Response, code: number, data?: any, descriptionOverride?: string) {
            Promise.resolve(data).then((toReturn: any) => {
                this.getResponse(code, toReturn, descriptionOverride).then(response => {
                    res.status(code).json(response);
                });
            });
        }
    }
    
    
    export default Session;