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 | 8x 80x 8x 11x 11x 11x 8x 1x 1x 8x 14x 8x 8x 65x 65x 8x 3x 1x 1x 3x 3x 8x 1x 1x 8x 11x 11x 11x 11x 11x 8x 11x 8x 19x 19x 19x 19x 8x 8x 14x 14x 14x 14x 14x 14x 14x 14x 8x 7x 7x 2x 5x 5x 5x 5x 5x 5x 8x 1x 1x 1x 1x 1x 1x 8x 8x 8x 5x 8x 8x 63x 63x | import { UserModel } from '../models/user_model'; import {IUser, UserData} from 'types/user_types'; import bcrypt from 'bcrypt'; import jwt from 'jsonwebtoken'; import { RefreshTokenModel } from '../models/refresh_token_model'; import {config} from '../config/config' import {Document} from "mongoose"; import { BlacklistedTokenModel } from '../models/Blacklisted_token_model'; const userToUserData = (user: Document<unknown, {}, IUser> & IUser): UserData => { return { ...user.toJSON(), id: user.id.toString() }; }; export const addUser = async (username: string, password: string, email: string, authProvider: string): Promise<UserData> => { const newUser = new UserModel({username, password, email, authProvider: authProvider || 'local'}); await newUser.save() return userToUserData(newUser); }; export const getUsers = async (): Promise<UserData[]> => { const users = await UserModel.find().exec(); return users.map(userToUserData); } const getIUserByEmail = async (email: string): Promise<IUser | null> => { return await UserModel.findOne({ email }).exec(); }; export const getUserByEmail = async (email: string): Promise<UserData | null> => { const user = await UserModel.findOne({ email }).exec(); return user ? userToUserData(user) : null; }; export const getUserById = async (id: string): Promise<UserData | null> => { const user = await UserModel.findById(id).exec(); return user ? userToUserData(user) : null; }; export const updateUserById = async (id: string, updateData: Partial<UserData>): Promise<UserData | null> => { if (updateData.password) { const salt = config.token.salt(); updateData.password = await bcrypt.hash(updateData.password, salt); } const user = await UserModel.findByIdAndUpdate(id, updateData, { new: true }).exec(); return user ? userToUserData(user) : null; }; export const deleteUserById = async (id: string): Promise<UserData | null> => { const user = await UserModel.findByIdAndDelete(id).exec(); return user ? userToUserData(user) : null; }; export const registerUser = async (username: string, password: string, email: string, authProvider: string = "local"): Promise<UserData> => { let hashedPassword: string = ''; // If registering with a password (local registration) Eif (password && authProvider === 'local') { const salt = config.token.salt(); hashedPassword = await bcrypt.hash(password, salt); } return await addUser(username, hashedPassword, email, authProvider); }; export const getUserByUsernameOrEmail = async (username: string, email: string) => { return await UserModel.findOne({ $or: [{ username }, { email }] }).exec(); }; /** Generate access and refresh tokens */ const generateTokens = (id: string): { accessToken: string, refreshToken: string } => { const random = Math.floor(Math.random() * 1000000); const accessToken = jwt.sign( { userId: id, random: random }, config.token.access_token_secret(), { expiresIn: config.token.token_expiration() as jwt.SignOptions['expiresIn'] }); const refreshToken = jwt.sign( { userId: id, random: random }, config.token.refresh_token_secret(), { expiresIn: config.token.refresh_token_expiration() as jwt.SignOptions['expiresIn'] }); return { accessToken, refreshToken }; } export const loginUserGoogle = async (email: string, authProvider: string, name: string, image: string | undefined) => { let user = await UserModel.findOne({ email }); // If the user does not exist, create a new user if (!user) { user = await UserModel.create({ email, authProvider, username: name, imageFilename: image }); } const tokens = generateTokens(user.id.toString()); return {...tokens, userId: user.id, username: user.username, imageFilename: user.imageFilename} } export const loginUser = async (email: string, password: string, authProvider: string = "local"): Promise<{ accessToken: string, refreshToken: string, userId: string, username: string, imageFilename?: string } | null> => { const user = await getIUserByEmail(email); Iif (!user) { return null; } // Local login (with password) Eif (authProvider === 'local') { Iif (!(await bcrypt.compare(password, user.password))) { return null; } } // OAuth login (Google) Iif (authProvider === 'google') { if (user.authProvider !== authProvider) { throw new Error(`User is registered with ${user.authProvider}, not ${authProvider}.`); } } const { accessToken, refreshToken } = generateTokens(user.id); await new RefreshTokenModel({ userId: user.id, token: refreshToken, accessToken: accessToken }).save(); return { accessToken, refreshToken, userId: user?.id, username: user.username, imageFilename: user.imageFilename }; }; export const refreshToken = async (refreshToken: string): Promise<{ newRefreshToken: string; accessToken: string }> => { const existingToken = await findRefreshToken(refreshToken); if (!existingToken) { throw new Error('Invalid refresh token'); } const decoded = jwt.verify(refreshToken, config.token.refresh_token_secret()) as { userId: string }; const user = await getUserById(decoded.userId); Iif (!user) { throw new Error('Invalid refresh token'); } const { accessToken: newAccessToken, refreshToken: newRefreshToken } = generateTokens(user.id); await updateRefreshTokenAccessToken(refreshToken, newAccessToken, newRefreshToken); return { accessToken: newAccessToken, newRefreshToken }; } /** * Invalidate the refresh token for a user * If the user didn't send a refresh -> cancel them all (as required) * If sent and the token is valid -> cancel it * If sent and the token is invalid -> return false * @param refreshToken * @param userId */ export const logoutUser = async (refreshToken: string | undefined, userId: string): Promise<boolean> => { Eif (refreshToken) { // Find the refresh token document const tokenDoc = await findRefreshToken(refreshToken); if (tokenDoc && tokenDoc.userId === userId) { // Delete the specific refresh token await RefreshTokenModel.findOneAndDelete({token: refreshToken}).exec(); await BlacklistedTokenModel.create({token: tokenDoc.accessToken}); return true; } else E{ // Invalid refresh token return false; } } return false; // } else { // // None or invalid refresh token provided, delete all refresh tokens for the user // const refreshTokens = await RefreshTokenModel.find({ userId }).exec(); // for (const tokenDoc of refreshTokens) { // await BlacklistedTokenModel.create({ token: tokenDoc.accessToken }); // } // await RefreshTokenModel.deleteMany({ userId }).exec(); // return true; // } }; export const findRefreshToken = async (token: string) => { return await RefreshTokenModel.findOne({ token }).exec(); }; export const updateRefreshTokenAccessToken = async (oldRefreshToken: string, newAccessToken: string, newRefreshToken: string): Promise<void> => { await RefreshTokenModel.findOneAndUpdate( { token: oldRefreshToken }, { token: newRefreshToken, accessToken: newAccessToken } ).exec(); }; export const blacklistToken = async (token: string): Promise<void> => { await new BlacklistedTokenModel({ token }).save(); }; export const isAccessTokenBlacklisted = async (token: string): Promise<boolean> => { const blacklistedToken = await BlacklistedTokenModel.findOne({ token }).exec(); return !!blacklistedToken; }; |