How to use jwt method in devicefarmer-stf

Best JavaScript code snippet using devicefarmer-stf

sagas.ts

Source:sagas.ts Github

copy

Full Screen

1import { call, Effect, fork, put, select } from "redux-saga/effects";2import { calculateTimeLeft } from "../../../components/shared/utils";3import { TMessage } from "../../../components/translatedMessages/utils";4import { TGlobalDependencies } from "../../../di/setupBindings";5import { ICreateJwtEndpointResponse } from "../../../lib/api/auth/SignatureAuthApi";6import { getJwtExpiryDate, hasValidPermissions } from "../../../utils/JWTUtils";7import { EthereumAddressWithChecksum } from "../../../utils/opaque-types/types";8import { EDelayTiming, safeDelay } from "../../../utils/safeTimers";9import { accessWalletAndRunEffect } from "../../access-wallet/sagas";10import { actions } from "../../actions";11import { neuCall, neuTakeLatest } from "../../sagasUtils";12import { selectEthereumAddressWithChecksum } from "../../web3/selectors";13import { AUTH_JWT_TIMING_THRESHOLD, AUTH_TOKEN_REFRESH_THRESHOLD } from "../constants";14import { JwtNotAvailable, MessageSignCancelledError } from "../errors";15import { selectJwt } from "../selectors";16/**17 * Load to store jwt from browser storage18 */19export function* loadJwt({ jwtStorage }: TGlobalDependencies): Iterator<Effect> {20 return jwtStorage.get();21}22/**23 * Save jwt to the browser storage and update the store24 */25export function* setJwt({ jwtStorage }: TGlobalDependencies, jwt: string): Iterator<any> {26 jwtStorage.set(jwt);27 yield put(actions.auth.setJWT(jwt));28}29/**30 * Generates and invokes a signer to sign a challenge.31 */32function* signChallenge(33 { web3Manager, signatureAuthApi, cryptoRandomString, logger }: TGlobalDependencies,34 permissions: Array<string> = [],35): Iterator<any> {36 const address: EthereumAddressWithChecksum = yield select(selectEthereumAddressWithChecksum);37 const salt = cryptoRandomString({ length: 64 });38 if (!web3Manager.personalWallet) {39 throw new Error("Wallet unavailable Error");40 }41 const signerType = web3Manager.personalWallet.getSignerType();42 logger.info("Obtaining auth challenge from api");43 const {44 body: { challenge },45 } = yield signatureAuthApi.challenge(address, salt, signerType, permissions);46 logger.info("Signing challenge");47 const signedChallenge = yield web3Manager.personalWallet.signMessage(challenge);48 logger.info("Challenge signed");49 return {50 challenge,51 signedChallenge,52 signerType,53 };54}55/**56 * Create new JWT from the authentication server.57 */58export function* createJwt(59 { signatureAuthApi, logger }: TGlobalDependencies,60 permissions: Array<string> = [],61): Iterator<any> {62 logger.info("Creating jwt");63 const { signedChallenge, challenge, signerType } = yield neuCall(signChallenge, permissions);64 logger.info("Sending signed challenge back to api");65 const { jwt }: ICreateJwtEndpointResponse = yield signatureAuthApi.createJwt(66 challenge,67 signedChallenge,68 signerType,69 );70 yield neuCall(setJwt, jwt);71 logger.info("Jwt created successfully");72}73/**74 * Escalate JWT with the authentication server.75 * Used to add additional permissions to existing JWT76 */77export function* escalateJwt(78 { signatureAuthApi, logger }: TGlobalDependencies,79 permissions: Array<string> = [],80): Iterator<any> {81 const currentJwt: string = yield select(selectJwt);82 if (!currentJwt) {83 throw new JwtNotAvailable();84 }85 logger.info("Escalating jwt");86 const { signedChallenge, challenge, signerType } = yield neuCall(signChallenge, permissions);87 logger.info("Sending signed challenge back to api");88 const { jwt }: ICreateJwtEndpointResponse = yield signatureAuthApi.escalateJwt(89 challenge,90 signedChallenge,91 signerType,92 );93 yield neuCall(setJwt, jwt);94 logger.info("Jwt escalated successfully");95}96/**97 * Refresh JWT with new default expire date.98 * Permissions expire dates left untouched.99 */100export function* refreshJWT({ signatureAuthApi, logger }: TGlobalDependencies): Iterator<any> {101 logger.info("Refreshing jwt");102 const { jwt }: ICreateJwtEndpointResponse = yield signatureAuthApi.refreshJwt();103 yield neuCall(setJwt, jwt);104 logger.info("Jwt refreshed successfully");105}106/**107 * Saga to ensure all the needed permissions are present and still valid on the current jwt108 * If needed permissions are not present/valid will escalate permissions with authentication server109 */110export function* ensurePermissionsArePresentAndRunEffect(111 { logger }: TGlobalDependencies,112 effect: Iterator<any>,113 permissions: Array<string> = [],114 title: TMessage,115 message?: TMessage,116 inputLabel?: TMessage,117): Iterator<any> {118 const jwt: string = yield select(selectJwt);119 // check whether all permissions are present and still valid120 if (jwt && hasValidPermissions(jwt, permissions)) {121 yield effect;122 return;123 }124 // obtain a freshly signed token with missing permissions125 try {126 const obtainJwtEffect = neuCall(escalateJwt, permissions);127 yield call(accessWalletAndRunEffect, obtainJwtEffect, title, message, inputLabel);128 yield effect;129 } catch (error) {130 if (error instanceof MessageSignCancelledError) {131 logger.info("Signing Cancelled");132 } else {133 throw error;134 }135 }136}137/**138 * Refresh jwt before timing out.139 * In case it's not possible will log out user.140 */141export function* handleJwtTimeout({ logger }: TGlobalDependencies): Iterator<any> {142 try {143 const jwt: string | undefined = yield select(selectJwt);144 if (!jwt) {145 throw new JwtNotAvailable();146 }147 const expiryDate = getJwtExpiryDate(jwt);148 const timeLeft = calculateTimeLeft(expiryDate, true, "milliseconds");149 const timeLeftWithThreshold =150 timeLeft >= AUTH_TOKEN_REFRESH_THRESHOLD ? timeLeft - AUTH_TOKEN_REFRESH_THRESHOLD : timeLeft;151 if (AUTH_JWT_TIMING_THRESHOLD > AUTH_TOKEN_REFRESH_THRESHOLD) {152 throw new Error("Timing threshold should be smaller than token refresh threshold");153 }154 const timing: EDelayTiming = yield safeDelay(timeLeftWithThreshold, {155 threshold: AUTH_JWT_TIMING_THRESHOLD,156 });157 // If timing matches exact refresh jwt158 // in case timeout was delayed (for e.g. hibernation), logout with session timeout message159 switch (timing) {160 case EDelayTiming.EXACT:161 yield neuCall(refreshJWT);162 break;163 case EDelayTiming.DELAYED:164 yield put(actions.auth.jwtTimeout());165 break;166 }167 } catch (e) {168 logger.error("Failed to handle jwt timeout", e);169 throw e;170 }171}172export function* authJwtSagas(): Iterator<Effect> {173 yield fork(neuTakeLatest, actions.auth.setJWT, handleJwtTimeout);...

Full Screen

Full Screen

authentication.service.ts

Source:authentication.service.ts Github

copy

Full Screen

1import { Injectable } from '@angular/core';2import { HttpClient, HttpHeaders } from '@angular/common/http';3import { JwtHelper } from 'angular2-jwt';4import {Router} from '@angular/router';5import { URL } from '../api-url/url';6import {Observable} from 'rxjs';7import {ConfirmationService} from "primeng/api";8import {User} from "../models/user";9@Injectable({10 providedIn: 'root'11})12export class AuthenticationService {13 authenticated: boolean = false;14 jwtToken: string;15 roles: Array<any> = [];16 display: boolean;17 user: User;18 constructor(private http: HttpClient, private router:Router, private confirmationService: ConfirmationService)19 {20 this.jwtToken = this.loadToken();21 if (this.jwtToken){22 this.authenticated = true;23 }24 }25 login(form: User) {26 return this.http.post(URL+"login", form, { observe: 'response' });27 }28 saveToken(jwtToken) {29 this.jwtToken = jwtToken;30 localStorage.setItem('jwtToken', jwtToken);31 let jwtHelper = new JwtHelper();32 this.roles = jwtHelper.decodeToken(this.jwtToken).roles;33 // this.email = jwtHelper.decodeToken(this.jwtToken).sub;34 }35 getUserAuthenticated(){36 this.jwtToken = localStorage.getItem('jwtToken');37 let jwtHelper = new JwtHelper();38 if (this.jwtToken){39 this.user = jwtHelper.decodeToken(this.jwtToken).user;40 this.roles = jwtHelper.decodeToken(this.jwtToken).roles;41 }42 return this.user ;43 }44 loadToken() {45 this.jwtToken = localStorage.getItem('jwtToken');46 return this.jwtToken;47 }48 register(user) {49 return this.http.put(URL+ "user/register", user);50 }51 resendPassword(email: string){52 return this.http.post(URL+ 'forgotpassword?email='+email, {});53 }54 logout(){55 this.jwtToken= null;56 this.authenticated = false;57 localStorage.removeItem('jwtToken');58 }59 isAdmin(){60 let jwtHelper=new JwtHelper();61 this.jwtToken= localStorage.getItem('jwtToken');62 if (this.jwtToken){63 this.roles=jwtHelper.decodeToken(this.jwtToken).roles;64 for(let r of this.roles) {65 if(r == 'ROLE_LUNCHLADY'){66 return true;67 }68 }69 }70 return false;71 }72 isUser(){73 let jwtHelper=new JwtHelper();74 this.jwtToken= localStorage.getItem('jwtToken');75 if (this.jwtToken){76 this.roles=jwtHelper.decodeToken(this.jwtToken).roles;77 for(let r of this.roles) {78 if(r == 'ROLE_USER'){79 return true;80 }81 }82 }83 }84 show() {85 this.display = true86 }87 onClose() {88 this.display = false89 }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import Vue from 'vue'2import Vuex from 'vuex'3import jwt_decode from "jwt-decode"4Vue.use(Vuex)5export default new Vuex.Store({6 state: {7 shoppingCart: [],8 jwtToken: null,9 jwtData: null10 },11 getters: {12 getShoppingCart(state) {13 return state.shoppingCart14 },15 isAuthorized(state){16 return state.jwtData != null17 },18 getEmail(state){19 if(!state.jwtData) return null20 return state.jwtData['sub']21 },22 getFirstname(state){23 if(!state.jwtData) return "Kasutaja"24 return state.jwtData['firstname']25 },26 hasRole: (state) => (role) => {27 return state.jwtData['scope'].includes(role)28 }29 },30 mutations: {31 loadCookies(state) {32 state.shoppingCart = JSON.parse(Vue.cookie.get("shopping_cart"))33 state.jwtToken = Vue.cookie.get("jwt")34 if (state.jwtToken) {35 state.jwtData = jwt_decode(state.jwtToken);36 }37 if (!state.shoppingCart) {38 state.shoppingCart = []39 }40 },41 setJwtToken(state, {jwt}) {42 state.jwtToken = jwt43 Vue.cookie.set("jwt", state.jwtToken)44 state.jwtData = jwt_decode(jwt);45 },46 addShoppingItem(state, {item}) {47 state.shoppingCart.push(item)48 Vue.cookie.set("shopping_cart", JSON.stringify(state.shoppingCart))49 },50 changeShoppingItemQuantity(state, {id, amount}) {51 state.shoppingCart[id]['amount'] = amount52 Vue.cookie.set('shopping_cart', JSON.stringify(state.shoppingCart))53 },54 removeShoppingItem(state, {id}) {55 Vue.delete(state.shoppingCart, id)56 Vue.cookie.set("shopping_cart", JSON.stringify(state.shoppingCart))57 },58 logOut(state) {59 Vue.cookie.delete("jwt")60 state.jwtToken = null61 state.jwtData = null62 }63 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var jwt = require('devicefarmer-stf-client').jwt;2var util = require('util');3var fs = require('fs');4var path = require('path');5var url = require('url');6var http = require('http');7var request = require('request');8var express = require('express');9var bodyParser = require('body-parser');10var app = express();11var server = http.createServer(app);12var io = require('socket.io').listen(server);13var WebSocket = require('ws');14var wss = new WebSocket.Server({ port: 8080 });15var wss2 = new WebSocket.Server({ port: 8081 });16var wss3 = new WebSocket.Server({ port: 8082 });17var wss4 = new WebSocket.Server({ port: 8083 });18var wss5 = new WebSocket.Server({ port: 8084 });19var wss6 = new WebSocket.Server({ port: 8085 });20var wss7 = new WebSocket.Server({ port: 8086 });21var wss8 = new WebSocket.Server({ port: 8087 });22var wss9 = new WebSocket.Server({ port: 8088 });23var wss10 = new WebSocket.Server({ port: 8089 });24var wss11 = new WebSocket.Server({ port: 8090 });25var wss12 = new WebSocket.Server({ port: 8091 });26var wss13 = new WebSocket.Server({ port: 8092 });27var wss14 = new WebSocket.Server({ port: 8093 });28var wss15 = new WebSocket.Server({ port: 8094 });29var wss16 = new WebSocket.Server({ port: 8095 });30var wss17 = new WebSocket.Server({ port: 8096 });31var wss18 = new WebSocket.Server({ port: 8097 });32var wss19 = new WebSocket.Server({ port: 8098 });33var wss20 = new WebSocket.Server({ port: 8099 });34var wss21 = new WebSocket.Server({ port: 8100 });35var wss22 = new WebSocket.Server({ port: 8101 });36var wss23 = new WebSocket.Server({ port: 8102 });37var wss24 = new WebSocket.Server({ port: 8103 });38var wss25 = new WebSocket.Server({ port: 8104 });39var wss26 = new WebSocket.Server({ port: 8105 });

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run devicefarmer-stf automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful