jsonwebtoken#sign TypeScript Examples
The following examples show how to use
jsonwebtoken#sign.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: meet_processor.ts From jibri-queue with Apache License 2.0 | 6 votes |
authToken(): string {
const cachedAuth: string = this.asapCache.get('asap');
if (cachedAuth) {
return cachedAuth;
}
const auth = sign({}, this.signingKey, {
issuer: AsapJwtIss,
audience: AsapJwtAud,
algorithm: 'RS256',
keyid: AsapJwtKid,
expiresIn: 60 * 60, // 1 hour
});
this.asapCache.set('asap', auth);
return auth;
}
Example #2
Source File: authentication.spec.ts From advanced-node with GNU General Public License v3.0 | 6 votes |
describe('Authentication Middleware', () => {
it('should return 403 if authorization header was not provided', async () => {
app.get('/fake_route', auth)
const { status, body } = await request(app).get('/fake_route')
expect(status).toBe(403)
expect(body.error).toBe(new ForbiddenError().message)
})
it('should return 200 if authorization header is valid', async () => {
const authorization = sign({ key: 'any_user_id' }, env.jwtSecret)
app.get('/fake_route', auth, (req, res) => {
res.json(req.locals)
})
const { status, body } = await request(app)
.get('/fake_route')
.set({ authorization })
expect(status).toBe(200)
expect(body).toEqual({ userId: 'any_user_id' })
})
})
Example #3
Source File: survey-result.test.ts From clean-ts-api with GNU General Public License v3.0 | 6 votes |
mockAccessToken = async (): Promise<string> => {
const res = await accountCollection.insertOne({
name: 'Rodrigo',
email: '[email protected]',
password: '123',
role: 'admin'
})
const id = res.insertedId.toHexString()
const accessToken = sign({ id }, env.jwtSecret)
await accountCollection.updateOne({
_id: res.insertedId
}, {
$set: {
accessToken
}
})
return accessToken
}
Example #4
Source File: auth.service.ts From Phantom with MIT License | 6 votes |
/**
* @author Aya Abohadima
* @description sign payload function : create token
* @param payload - object went to convert to token
* @returns token which created
*/
async signPayload(payload) {
return (
'Bearer ' +
sign(payload, process.env.SECRET_KEY, { expiresIn: '67472347632732h' })
);
}
Example #5
Source File: survey.test.ts From clean-ts-api with GNU General Public License v3.0 | 6 votes |
mockAccessToken = async (): Promise<string> => {
const res = await accountCollection.insertOne({
name: 'Rodrigo',
email: '[email protected]',
password: '123',
role: 'admin'
})
const id = res.insertedId.toHexString()
const accessToken = sign({ id }, env.jwtSecret)
await accountCollection.updateOne({
_id: res.insertedId
}, {
$set: {
accessToken
}
})
return accessToken
}
Example #6
Source File: survey-result-routes.test.ts From clean-ts-api with GNU General Public License v3.0 | 6 votes |
mockAccessToken = async (): Promise<string> => {
const res = await accountCollection.insertOne({
name: 'Rodrigo',
email: '[email protected]',
password: '123'
})
const id = res.insertedId.toHexString()
const accessToken = sign({ id }, env.jwtSecret)
await accountCollection.updateOne({
_id: res.insertedId
}, {
$set: {
accessToken
}
})
return accessToken
}
Example #7
Source File: AuthenticateUserService.ts From GoBarber with MIT License | 6 votes |
public async execute({ email, password }: IRequest): Promise<IResponse> {
const user = await this.usersRepository.findByEmail(email);
if (!user) {
throw new AppError('Incorrect Email/Password validation.', 401);
}
// user.password = senha criptografada
if (!(await this.hashProvider.compareHash(password, user.password))) {
throw new AppError('Incorrect Email/Password validation.', 401);
}
const token = sign({}, authConfig.secret, {
subject: user.id,
expiresIn: authConfig.expiresIn,
});
return {
user,
token,
};
}
Example #8
Source File: AuthenticateUserService.ts From gobarber-project with MIT License | 6 votes |
public async execute({ email, password }: IRequest): Promise<IResponse> {
const user = await this.usersRepository.findByEmail(email);
if (!user) {
throw new AppError('Incorrect email/password combination.', 401);
}
const passwordMatched = await this.hashProvider.compareHash(
password,
user.password,
);
if (!passwordMatched) {
throw new AppError('Error email/password combination.', 401);
}
const { secret, expiresIn } = authConfig.jwt;
const token = sign({}, secret, {
subject: user.id,
expiresIn,
});
return {
user,
token,
};
}
Example #9
Source File: survey-routes.test.ts From clean-ts-api with GNU General Public License v3.0 | 6 votes |
mockAccessToken = async (): Promise<string> => {
const res = await accountCollection.insertOne({
name: 'Rodrigo',
email: '[email protected]',
password: '123',
role: 'admin'
})
const id = res.insertedId.toHexString()
const accessToken = sign({ id }, env.jwtSecret)
await accountCollection.updateOne({
_id: res.insertedId
}, {
$set: {
accessToken
}
})
return accessToken
}
Example #10
Source File: JWT.ts From ZenTS with MIT License | 6 votes |
public static async sign(payload: { [key: string]: any }): Promise<string> {
return new Promise((resolve, reject) => {
const options = Object.assign({}, this.getOptions(), { noTimestamp: true })
sign(payload, config.security.secretKey, options, (err, jwt: string) => {
if (err) {
return reject(err)
}
return resolve(jwt)
})
})
}
Example #11
Source File: jwt.ts From umbriel with MIT License | 6 votes |
static signUser(user: User): JWT {
const token = sign({}, auth.secretKey, {
subject: user.id,
expiresIn: auth.expiresIn,
})
const jwt = new JWT({ userId: user.id, token })
return jwt
}
Example #12
Source File: createTokens.ts From vsinder-api with Apache License 2.0 | 6 votes |
createTokens = (user: User) => {
const refreshToken = sign(
{ userId: user.id, tokenVersion: user.tokenVersion },
process.env.REFRESH_TOKEN_SECRET,
{
expiresIn: "14d",
}
);
const accessToken = sign(
{ userId: user.id },
process.env.ACCESS_TOKEN_SECRET,
{
expiresIn: "15min",
}
);
return { refreshToken, accessToken };
}
Example #13
Source File: createTokens.ts From vsinder with Apache License 2.0 | 6 votes |
createTokens = (user: User): { refreshToken: string, accessToken: string } => {
const refreshToken = sign(
{ userId: user.id, tokenVersion: user.tokenVersion },
process.env.REFRESH_TOKEN_SECRET,
{
expiresIn: "14d",
}
);
const accessToken = sign(
{ userId: user.id },
process.env.ACCESS_TOKEN_SECRET,
{
expiresIn: "15min",
}
);
return { refreshToken, accessToken };
}
Example #14
Source File: AuthenticateUserService.ts From gobarber-api with MIT License | 6 votes |
public async execute({ email, password }: IRequest): Promise<IResponse> {
const user = await this.usersRepository.findByEmail(email);
if (!user) {
throw new AppError('Incorrect email/password combination.', 401);
}
const passwordMatched = await this.hashProvider.comapreHash(
password,
user.password,
);
if (!passwordMatched) {
throw new AppError('Incorrect email/password combination.', 401);
}
const { secret, expiresIn } = authConfig.jwt;
const token = sign({}, secret, {
subject: user.id,
expiresIn,
});
return {
user,
token,
};
}
Example #15
Source File: oauth.ts From your_spotify with GNU General Public License v3.0 | 6 votes |
router.get('/spotify/callback', withGlobalPreferences, async (req, res) => {
const { query, globalPreferences } = req as GlobalPreferencesRequest;
const { code } = query;
const infos = await Spotify.exchangeCode(code as string);
try {
const client = Spotify.getHttpClient(infos.accessToken);
const { data: spotifyMe } = await client.get('/me');
let user = await getUserFromField('spotifyId', spotifyMe.id);
if (!user) {
if (!globalPreferences.allowRegistrations) {
return res.redirect(`${get('CLIENT_ENDPOINT')}/registrations-disabled`);
}
const nbUsers = await getNumberOfUsers();
user = await createUser(spotifyMe.display_name, spotifyMe.id, nbUsers === 0);
}
await storeInUser('_id', user._id, infos);
const token = sign({ userId: user._id.toString() }, 'MyPrivateKey', {
expiresIn: '1h',
});
res.cookie('token', token);
} catch (e) {
logger.error(e);
}
return res.redirect(get('CLIENT_ENDPOINT'));
});
Example #16
Source File: auth.ts From hotseat-api with MIT License | 6 votes |
createTokens = async (
userId: string,
userPassword: string,
): Promise<string[]> => {
const createToken = sign(
{
sub: userId,
},
jwtConfig.jwt.tokenSecret,
{
expiresIn: jwtConfig.jwt.tokenExpiresIn,
},
);
const createRefreshToken = sign(
{
sub: userId,
},
jwtConfig.jwt.refreshTokenSecret + userPassword,
{
expiresIn: jwtConfig.jwt.refreshTokenExpiresIn,
},
);
return Promise.all([createToken, createRefreshToken]);
}
Example #17
Source File: vonage.service.ts From loopback4-microservice-catalog with MIT License | 5 votes |
async setUploadTarget(
storageConfig: VonageS3TargetOptions | VonageAzureTargetOptions,
): Promise<void> {
const {apiKey, apiSecret} = this.vonageConfig;
const ttl = 200;
const jwtPayload = {
iss: apiKey,
ist: 'project',
iat: moment().unix(),
exp: moment().add(ttl, 'seconds').unix(),
};
const token = sign(jwtPayload, apiSecret);
let type = '';
const credentials = {};
if (storageConfig.name === ExternalStorageName.AWSS3) {
const accessKey = this.vonageConfig.awsAccessKey;
const secretKey = this.vonageConfig.awsSecretKey;
if (!accessKey || !secretKey) {
throw new HttpErrors.InternalServerError(
`Missing Aws S3 credentials for setting vongae upload target`,
);
}
const {bucket, endpoint} = storageConfig as VonageS3TargetOptions;
if (bucket) {
type = 'S3';
Object.assign(credentials, {
accessKey,
secretKey,
bucket,
endpoint,
});
}
} else if (storageConfig.name === ExternalStorageName.AZURE) {
const accountKey = this.vonageConfig.azureAccountKey;
const container = this.vonageConfig.azureAccountContainer;
const {accountName, domain} = storageConfig as VonageAzureTargetOptions;
if (!accountKey || !container) {
throw new HttpErrors.InternalServerError(
`Missing Azure credentials for setting vongae upload target`,
);
}
if (accountName) {
type = 'Azure';
Object.assign(credentials, {
accountName,
accountKey,
container,
domain,
});
}
}
await axios({
url: `https://api.opentok.com/v2/project/${this.vonageConfig.apiKey}/archive/storage`,
method: 'put',
data: {
type,
config: credentials,
fallback: storageConfig.fallback,
},
headers: {
'X-OPENTOK-AUTH': token,
},
});
}
Example #18
Source File: AuthenticateUserService.ts From nlw-heat-node with MIT License | 5 votes |
async execute(code: string) {
const url = "https://github.com/login/oauth/access_token";
const { data: accessTokenResponse } =
await axios.post<IAccessTokenResponse>(url, null, {
params: {
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code,
},
headers: {
Accept: "application/json",
},
});
const response = await axios.get<IUserResponse>(
"https://api.github.com/user",
{
headers: {
authorization: `Bearer ${accessTokenResponse.access_token}`,
},
}
);
const { login, id, avatar_url, name } = response.data;
let user = await prismaClient.user.findFirst({
where: {
github_id: id,
},
});
if (!user) {
user = await prismaClient.user.create({
data: {
github_id: id,
login,
avatar_url,
name,
},
});
}
const token = sign(
{
user: {
name: user.name,
avatar_ur: user.avatar_url,
id: user.id,
},
},
process.env.JWT_SECRET,
{
subject: user.id,
expiresIn: "1d",
}
);
return { token, user };
}
Example #19
Source File: user.spec.ts From advanced-node with GNU General Public License v3.0 | 5 votes |
describe('User Routes', () => {
let backup: IBackup
let connection: PgConnection
let pgUserRepo: Repository<PgUser>
beforeAll(async () => {
connection = PgConnection.getInstance()
const db = await makeFakeDb([PgUser])
backup = db.backup()
pgUserRepo = connection.getRepository(PgUser)
})
afterAll(async () => {
await connection.disconnect()
})
beforeEach(() => {
backup.restore()
})
describe('DELETE /users/picture', () => {
it('should return 403 if authorization header is not present', async () => {
const { status } = await request(app)
.delete('/api/users/picture')
expect(status).toBe(403)
})
it('should return 200 with valid data', async () => {
const { id } = await pgUserRepo.save({ email: 'any_email', name: 'any name' })
const authorization = sign({ key: id }, env.jwtSecret)
const { status, body } = await request(app)
.delete('/api/users/picture')
.set({ authorization })
expect(status).toBe(200)
expect(body).toEqual({ pictureUrl: undefined, initials: 'AN' })
})
})
describe('PUT /users/picture', () => {
const uploadSpy = jest.fn()
jest.mock('@/infra/gateways/aws-s3-file-storage', () => ({
AwsS3FileStorage: jest.fn().mockReturnValue({ upload: uploadSpy })
}))
it('should return 403 if authorization header is not present', async () => {
const { status } = await request(app)
.put('/api/users/picture')
expect(status).toBe(403)
})
it('should return 200 with valid data', async () => {
uploadSpy.mockResolvedValueOnce('any_url')
const { id } = await pgUserRepo.save({ email: 'any_email', name: 'any name' })
const authorization = sign({ key: id }, env.jwtSecret)
const { status, body } = await request(app)
.put('/api/users/picture')
.set({ authorization })
.attach('picture', Buffer.from('any_buffer'), { filename: 'any_name', contentType: 'image/png' })
expect(status).toBe(200)
expect(body).toEqual({ pictureUrl: 'any_url', initials: undefined })
})
})
})
Example #20
Source File: jwt-token-handler.ts From advanced-node with GNU General Public License v3.0 | 5 votes |
async generate ({ expirationInMs, key }: TokenGenerator.Input): Promise<TokenGenerator.Output> {
const expirationInSeconds = expirationInMs / 1000
return sign({ key }, this.secret, { expiresIn: expirationInSeconds })
}
Example #21
Source File: AuthFixture.ts From typescript-clean-architecture with MIT License | 5 votes |
public static async loginUser(user: {id: string}): Promise<{accessToken: string}> {
const accessToken: string = sign({id: user.id}, ApiServerConfig.ACCESS_TOKEN_SECRET);
return {accessToken};
}
Example #22
Source File: auth.service.ts From Phantom with MIT License | 5 votes |
/**
* @author Nada Abdelmaboud <[email protected]>
* @description google aouth handler
* @param {Object}
*/
async googleLogin(req) {
if (!req.user) {
throw new NotFoundException('no such user');
}
let user = req.user;
let type;
let checkUser = await this.userService.checkMAilExistAndFormat(user.email);
let payload;
if (!checkUser) {
type = 'sign';
let newUser = await this.userService.createUser({
email: user.email,
birthday: null,
firstName: user.firstName,
lastName: user.lastName,
password: '',
isGoogle: true,
profileImage: user.picture,
});
if (!newUser) {
throw new BadRequestException();
}
payload = {
_id: newUser._id,
};
} else {
type = 'login';
payload = {
_id: checkUser._id,
};
}
return {
token:
'Bearer ' +
sign(payload, process.env.SECRET_KEY, { expiresIn: '67472347632732h' }),
type: type,
};
}
Example #23
Source File: jsonWebToken.service.ts From rest-api.ts with MIT License | 5 votes |
encode(payload: Object): string {
return sign(payload, this.JWT_PRIVATE_KEY, {expiresIn: '1 day'});
}
Example #24
Source File: token.ts From jibri-queue with Apache License 2.0 | 5 votes |
export function recorderToken(options: SignOptions, privateKey: Buffer): string {
const payload = {
room: '*',
};
return sign(payload, privateKey, options);
}
Example #25
Source File: Auth.provider.ts From nodetskeleton with MIT License | 5 votes |
async getJwt(session: ISession): Promise<string> {
const token = sign(session, AppSettings.JWTEncryptionKey, {
algorithm: AppConstants.HS512_ALGORITHM,
expiresIn: AppSettings.JWTExpirationTime,
});
return Promise.resolve(token);
}
Example #26
Source File: auth.ts From hakka with MIT License | 5 votes |
export function createSecureToken(payload: CookieUserPayload) {
const token = sign(payload, process.env.ENCRYPT_SECRET)
return token
}
Example #27
Source File: JWT.ts From nodejs-backend-architecture-typescript with Apache License 2.0 | 5 votes |
public static async encode(payload: JwtPayload): Promise<string> {
const cert = await this.readPrivateKey();
if (!cert) throw new InternalError('Token generation failure');
// @ts-ignore
return promisify(sign)({ ...payload }, cert, { algorithm: 'RS256' });
}
Example #28
Source File: user.service.ts From Phantom with MIT License | 4 votes |
/**
* @author Aya Abohadima <[email protected]>
* @description update information in user profile
* @param {String} userId -id of user
* @param {UpdateDto} updateDto -update data
* @returns {Number} 1
*/
async updateUserInfo(userId, updateDto: UpdateDto) {
const user = await this.getUserMe(userId);
if (!user) return 0;
if (updateDto.firstName)
await this.userModel.updateOne(
{ _id: userId },
{ firstName: updateDto.firstName },
);
if (updateDto.lastName)
await this.userModel.updateOne(
{ _id: userId },
{ lastName: updateDto.lastName },
);
if (updateDto.userName)
await this.userModel.updateOne(
{ _id: userId },
{ userName: updateDto.userName },
);
if (updateDto.location)
await this.userModel.updateOne(
{ _id: userId },
{ location: updateDto.location },
);
if (updateDto.bio)
await this.userModel.updateOne({ _id: userId }, { about: updateDto.bio });
if (updateDto.gender)
await this.userModel.updateOne(
{ _id: userId },
{ gender: updateDto.gender },
);
if (updateDto.country)
await this.userModel.updateOne(
{ _id: userId },
{ country: updateDto.country },
);
if (updateDto.profileImage) {
await this.userModel.updateOne(
{ _id: userId },
{ profileImage: updateDto.profileImage },
);
}
if (
updateDto.email &&
!(await this.checkMAilExistAndFormat(updateDto.email))
) {
var token =
'Bearer ' +
sign(
{
email: user.email,
_id: user._id,
newEmail: updateDto.email,
firstName: updateDto.firstName
? updateDto.firstName
: user.firstName,
},
process.env.SECRET_KEY,
{ expiresIn: '67472347632732h' },
);
await this.email.sendEmail(
user.email,
token,
'change email',
updateDto.firstName ? updateDto.firstName : user.firstName,
);
}
if (updateDto.birthDate)
await this.userModel.updateOne(
{ _id: userId },
{ birthDate: updateDto.birthDate },
);
return 1;
}