-
Notifications
You must be signed in to change notification settings - Fork 85
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
02ffcf8
commit a92dd01
Showing
13 changed files
with
343 additions
and
55 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
module.exports = { | ||
export default { | ||
testEnvironment: 'node', | ||
testEnvironmentOptions: { | ||
NODE_ENV: 'test', | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import { ObjectId } from 'mongoose'; | ||
import { JwtPayload } from 'jsonwebtoken'; | ||
|
||
export interface IToken { | ||
token: string; | ||
user: ObjectId; | ||
type: string; | ||
expires: Date; | ||
blacklisted: boolean; | ||
} | ||
|
||
export interface IPayload extends JwtPayload { | ||
sub: string; | ||
iat: number; | ||
exp: number; | ||
type: string; | ||
} | ||
|
||
export interface TokenPayload { | ||
token: string; | ||
expires: Date; | ||
} | ||
|
||
export interface AccessAndRefreshTokens { | ||
access: TokenPayload; | ||
refresh: TokenPayload; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
import jwt from 'jsonwebtoken'; | ||
import moment, { Moment } from 'moment'; | ||
import mongoose, { ObjectId } from 'mongoose'; | ||
import httpStatus from 'http-status'; | ||
import config from '../config/config'; | ||
import Token from './token.model'; | ||
import ApiError from '../utils/ApiError'; | ||
import tokenTypes from './token.types'; | ||
import { AccessAndRefreshTokens, IToken } from './token.interfaces'; | ||
import { ToJSONUser } from '../Users/user.interfaces'; | ||
import { getUserByEmail } from '../Users/user.service'; | ||
|
||
/** | ||
* Generate token | ||
* @param {ObjectId} userId | ||
* @param {Moment} expires | ||
* @param {string} type | ||
* @param {string} [secret] | ||
* @returns {string} | ||
*/ | ||
export const generateToken = ( | ||
userId: ObjectId, | ||
expires: Moment, | ||
type: string, | ||
secret: string = config.jwt.secret | ||
): string => { | ||
const payload = { | ||
sub: userId, | ||
iat: moment().unix(), | ||
exp: expires.unix(), | ||
type, | ||
}; | ||
return jwt.sign(payload, secret); | ||
}; | ||
|
||
/** | ||
* Save a token | ||
* @param {string} token | ||
* @param {ObjectId} userId | ||
* @param {Moment} expires | ||
* @param {string} type | ||
* @param {boolean} [blacklisted] | ||
* @returns {Promise<IToken>} | ||
*/ | ||
export const saveToken = async ( | ||
token: string, | ||
userId: ObjectId, | ||
expires: Moment, | ||
type: string, | ||
blacklisted: boolean = false | ||
): Promise<IToken> => { | ||
const tokenDoc = await Token.create({ | ||
token, | ||
user: userId, | ||
expires: expires.toDate(), | ||
type, | ||
blacklisted, | ||
}); | ||
return tokenDoc; | ||
}; | ||
|
||
/** | ||
* Verify token and return token doc (or throw an error if it is not valid) | ||
* @param {string} token | ||
* @param {string} type | ||
* @returns {Promise<IToken>} | ||
*/ | ||
export const verifyToken = async (token: string, type: string): Promise<IToken> => { | ||
const payload = jwt.verify(token, config.jwt.secret); | ||
let tokenDoc; | ||
if (typeof payload.sub === 'string') { | ||
tokenDoc = await Token.findOne({ | ||
token, | ||
type, | ||
user: new mongoose.Schema.Types.ObjectId(payload.sub), | ||
blacklisted: false, | ||
}); | ||
} | ||
if (!tokenDoc) { | ||
throw new Error('Token not found'); | ||
} | ||
return tokenDoc; | ||
}; | ||
|
||
/** | ||
* Generate auth tokens | ||
* @param {ToJSONUser} user | ||
* @returns {Promise<AccessAndRefreshTokens>} | ||
*/ | ||
export const generateAuthTokens = async (user: ToJSONUser): Promise<AccessAndRefreshTokens> => { | ||
const accessTokenExpires = moment().add(config.jwt.accessExpirationMinutes, 'minutes'); | ||
const accessToken = generateToken(user.id, accessTokenExpires, tokenTypes.ACCESS); | ||
|
||
const refreshTokenExpires = moment().add(config.jwt.refreshExpirationDays, 'days'); | ||
const refreshToken = generateToken(user.id, refreshTokenExpires, tokenTypes.REFRESH); | ||
await saveToken(refreshToken, user.id, refreshTokenExpires, tokenTypes.REFRESH); | ||
|
||
return { | ||
access: { | ||
token: accessToken, | ||
expires: accessTokenExpires.toDate(), | ||
}, | ||
refresh: { | ||
token: refreshToken, | ||
expires: refreshTokenExpires.toDate(), | ||
}, | ||
}; | ||
}; | ||
|
||
/** | ||
* Generate reset password token | ||
* @param {string} email | ||
* @returns {Promise<string>} | ||
*/ | ||
export const generateResetPasswordToken = async (email: string): Promise<string> => { | ||
const user = await getUserByEmail(email); | ||
if (!user) { | ||
throw new ApiError(httpStatus.NOT_FOUND, 'No users found with this email'); | ||
} | ||
const expires = moment().add(config.jwt.resetPasswordExpirationMinutes, 'minutes'); | ||
const resetPasswordToken = generateToken(user.id, expires, tokenTypes.RESET_PASSWORD); | ||
await saveToken(resetPasswordToken, user.id, expires, tokenTypes.RESET_PASSWORD); | ||
return resetPasswordToken; | ||
}; | ||
|
||
/** | ||
* Generate verify email token | ||
* @param {ToJSONUser} user | ||
* @returns {Promise<string>} | ||
*/ | ||
export const generateVerifyEmailToken = async (user: ToJSONUser): Promise<string> => { | ||
const expires = moment().add(config.jwt.verifyEmailExpirationMinutes, 'minutes'); | ||
const verifyEmailToken = generateToken(user.id, expires, tokenTypes.VERIFY_EMAIL); | ||
await saveToken(verifyEmailToken, user.id, expires, tokenTypes.VERIFY_EMAIL); | ||
return verifyEmailToken; | ||
}; |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import { Model, ObjectId } from 'mongoose'; | ||
import { QueryResult } from '../plugins/paginate'; | ||
|
||
export interface IUser { | ||
name: string; | ||
email: string; | ||
password: string; | ||
role?: string; | ||
isEmailVerified?: boolean; | ||
} | ||
|
||
export interface ToJSONUser { | ||
name: string; | ||
email: string; | ||
password: string; | ||
role: string; | ||
isEmailVerified: boolean; | ||
id: ObjectId; | ||
} | ||
|
||
export interface IUserStatics extends Model<IUser> { | ||
isEmailTaken(email: string, excludeUserId?: ObjectId): Promise<boolean>; | ||
isPasswordMatch(password: string): Promise<boolean>; | ||
paginate(filter: Record<string, any>, options: Record<string, any>): Promise<QueryResult>; | ||
toJSON(): void; | ||
} | ||
|
||
export interface UpdateUserBody { | ||
name?: string; | ||
email?: string; | ||
password?: string; | ||
} | ||
|
||
export interface NewRegisteredUser { | ||
name: string; | ||
email: string; | ||
password: string; | ||
} | ||
|
||
export interface NewCreatedUser { | ||
name: string; | ||
email: string; | ||
password: string; | ||
role: string; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.