How to use tokenKeep method in ng-mocks

Best JavaScript code snippet using ng-mocks

login.js

Source:login.js Github

copy

Full Screen

1import {getLineBreaksParsedToHtml} from './shared/generic.js';2import {openLink} from './shared/generic.js';3import {4 aesGcmExportBase64,5 pbkdf2PassToAesGcmKey6} from './shared/crypto.js';7export {MyLogin as default};8let MyLogin = {9 name:'my-login',10 template:`<div class="login">11 12 <!-- centered logo -->13 <img class="logo clickable"14 @click="openLink(customLogoUrl,true)"15 :src="customLogo"16 />17 18 <!-- server not connected -->19 <template v-if="!backendReady">20 21 <div class="contentBox">22 <div class="top lower" :style="customBgLogin">23 <div class="area">24 <img class="icon bg" src="images/lock.png" />25 <h1>{{ appName }}</h1>26 </div>27 </div>28 29 <div class="content">30 <my-button image="load.gif"31 :active="false"32 :caption="message.wsBroken[language]"33 :naked="true"34 />35 </div>36 </div>37 </template>38 39 <!-- not ready for login yet (downloading schema/public data/...) -->40 <template v-if="backendReady && !loginReady">41 <div class="contentBox">42 <div class="top lower" :style="customBgLogin">43 <div class="area">44 <img class="icon bg" src="images/lock.png" />45 <h1>{{ appName }}</h1>46 </div>47 </div>48 <div class="content">49 <my-button image="load.gif"50 :caption="message.loading[language]"51 :naked="true"52 />53 </div>54 </div>55 </template>56 57 <!-- ready for login -->58 <template v-if="backendReady && loginReady">59 60 <!-- HTTP message -->61 <div class="contentBox" v-if="httpMode">62 <div class="top warning">63 <div class="area">64 <img class="icon bg" src="images/warning.png" />65 <h1>{{ message.httpMode[language] }}</h1>66 </div>67 </div>68 </div>69 70 <!-- maintenance mode message -->71 <div class="contentBox" v-if="!productionMode">72 <div class="top warning">73 <div class="area">74 <img class="icon bg" src="images/warning.png" />75 <h1>{{ message.maintenanceMode[language] }}</h1>76 </div>77 </div>78 </div>79 80 <!-- unexpected error message -->81 <div class="contentBox" v-if="appInitErr">82 <div class="top warning">83 <div class="area">84 <img class="icon bg" src="images/warning.png" />85 <h1>{{ message.error[language] }}</h1>86 </div>87 </div>88 </div>89 90 <!-- busy overlay -->91 <div class="input-block-overlay-bg" :class="{show:loading}">92 <div class="input-block-overlay">93 <img class="busy" src="images/load.gif" />94 </div>95 </div>96 97 <!-- login dialog -->98 <div class="contentBox">99 <div class="top lower" :style="customBgLogin">100 <div class="area">101 <img class="icon bg" src="images/lock.png" />102 <h1>{{ appName }}</h1>103 </div>104 </div>105 106 <div class="content" :class="{ badAuth:badAuth }">107 108 <input class="default" type="text"109 @keyup="badAuth = false"110 @keyup.enter="authenticate"111 v-model="username"112 v-focus113 placeholder="username"114 />115 <input class="default" type="password"116 @keyup="badAuth = false"117 @keyup.enter="authenticate"118 v-model="password"119 placeholder="password"120 />121 <div class="actions">122 <my-button123 @trigger="tokenKeepInput = !tokenKeepInput"124 :caption="message.stayLoggedIn[language]"125 :image="tokenKeep ? 'checkbox1.png' : 'checkbox0.png'"126 :naked="true"127 />128 129 <my-button130 @trigger="authenticate"131 :active="isValid"132 :caption="message.login[language]"133 :image="loading ? 'load.gif' : 'ok.png'"134 :right="true"135 />136 </div>137 </div>138 </div>139 </template>140 141 <!-- custom company message -->142 <div class="contentBox" v-if="showCustom">143 <div class="top lower" :style="customBgLogin">144 <div class="area">145 <img class="icon bg" src="images/home.png" />146 <h1>{{ companyName }}</h1>147 </div>148 </div>149 150 <div class="content" v-if="companyWelcome !== ''">151 <span v-html="getLineBreaksParsedToHtml(companyWelcome)"></span>152 </div>153 </div>154 155 <!-- cluster node ID -->156 <div class="clusterNode">{{ message.clusterNode[language] + clusterNodeName }}</div>157 </div>`,158 props:{159 backendReady:{ type:Boolean, required:true }, // can talk to backend160 httpMode: { type:Boolean, required:true }, // unencrypted connection161 loginReady: { type:Boolean, required:true } // can login162 },163 emits:['authenticated'],164 data:function() {165 return {166 // inputs167 password:'',168 username:'',169 170 // states171 appInitErr:false, // application failed to initialize172 badAuth:false, // authentication failed173 loading:false,174 showError:false,175 176 // default messages177 language:'en_US',178 languages:['de','en_US'],179 message:{180 clusterNode:{181 de:'Verbunden mit: ',182 en_US:'Connected with: '183 },184 error:{185 de:'Ein Fehler ist aufgetreten - bitte erneut versuchen',186 en_US:'An error occurred - please try again'187 },188 httpMode:{189 de:'Verbindung ist nicht verschlüsselt',190 en_US:'Connection is not encrypted'191 },192 loading:{193 de:'Am Laden...',194 en_US:'Loading...'195 },196 login:{197 de:'Anmelden',198 en_US:'Login'199 },200 maintenanceMode:{201 de:'Wartungsmodus ist aktiv',202 en_US:'Maintenance mode is active'203 },204 stayLoggedIn:{205 de:'Angemeldet bleiben',206 en_US:'Stay logged in'207 },208 wsBroken:{209 de:'Warten auf Serververbindung',210 en_US:'Waiting for server connection'211 }212 }213 };214 },215 computed:{216 // input217 tokenKeepInput:{218 get() { return this.tokenKeep; },219 set(v) { return this.$store.commit('local/tokenKeep',v); } 220 },221 222 // states223 isValid: (s) => !s.badAuth && s.username !== '' && s.password !== '',224 showCustom:(s) => s.activated && (s.companyName !== '' || s.companyWelcome !== ''),225 226 // stores227 activated: (s) => s.$store.getters['local/activated'],228 appName: (s) => s.$store.getters['local/appName'],229 appVersion: (s) => s.$store.getters['local/appVersion'],230 companyColorLogin:(s) => s.$store.getters['local/companyColorLogin'],231 companyName: (s) => s.$store.getters['local/companyName'],232 companyWelcome: (s) => s.$store.getters['local/companyWelcome'],233 customBgLogin: (s) => s.$store.getters['local/customBgLogin'],234 customLogo: (s) => s.$store.getters['local/customLogo'],235 customLogoUrl: (s) => s.$store.getters['local/customLogoUrl'],236 token: (s) => s.$store.getters['local/token'],237 tokenKeep: (s) => s.$store.getters['local/tokenKeep'],238 clusterNodeName: (s) => s.$store.getters.clusterNodeName,239 kdfIterations: (s) => s.$store.getters.constants.kdfIterations,240 productionMode: (s) => s.$store.getters.productionMode241 },242 watch:{243 loginReady:function(v) {244 if(!v) return;245 246 // authenticate via login getter, if set247 let pos = window.location.hash.indexOf('?');248 if(pos !== -1) {249 let getters = window.location.hash.substr(pos+1).split('&');250 let gettersKeep = [];251 let login = '';252 253 for(let i = 0, j = getters.length; i < j; i++) {254 let parts = getters[i].split('=');255 256 if(parts[0] === 'login') {257 login = parts[1];258 continue; // login getter is removed from URL259 }260 gettersKeep.push(getters[i]);261 }262 263 if(login !== '') {264 this.authenticatePublic(login);265 this.$router.replace(266 window.location.hash.substr(1,pos) + gettersKeep.join('&')267 );268 return;269 }270 }271 272 // attempt authentication if token is available273 if(this.token !== '')274 return this.authenticateByToken();275 }276 },277 mounted:function() {278 // overwrite language by browser setting279 if(this.languages.includes(window.navigator.language))280 this.language = window.navigator.language;281 282 // set page title283 this.$store.commit('pageTitle',this.message.login[this.language]);284 285 // clear token & login key, if available but not to be kept286 if(!this.tokenKeep && this.token !== '') {287 this.$store.commit('local/loginKeyAes',null);288 this.$store.commit('local/token','');289 }290 },291 methods:{292 // externals293 aesGcmExportBase64,294 getLineBreaksParsedToHtml,295 pbkdf2PassToAesGcmKey,296 openLink,297 298 // misc299 handleError(action) {300 switch(action) {301 case 'aesExport': break; // very unexpected, should not happen302 case 'authToken': break; // token auth failed, to be expected, can expire303 case 'authUser': this.badAuth = true; break; // user authorization failed, mark inputs invalid304 case 'kdfCreate': break; // very unexpected, should not happen305 }306 this.loading = false;307 },308 parentError() {309 // stop loading, when parent caught error310 this.loading = false;311 this.appInitErr = true;312 },313 314 // authenticate by username/password or public user315 authenticate() {316 if(!this.isValid) return;317 318 ws.send('auth','user',{319 username:this.username,320 password:this.password321 },true).then(322 res => this.authenticatedByUser(323 res.payload.loginId,324 res.payload.loginName,325 res.payload.token,326 res.payload.saltKdf327 ),328 () => this.handleError('authUser')329 );330 this.loading = true;331 },332 authenticatePublic(username) {333 // keep token as public user is not asked334 this.$store.commit('local/tokenKeep',true);335 336 ws.send('auth','user',{username:username},true).then(337 res => this.authenticatedByUser(338 res.payload.loginId,339 res.payload.loginName,340 res.payload.token,341 null342 ),343 () => this.handleError('authUser')344 );345 this.loading = true;346 },347 authenticateByToken() {348 ws.send('auth','token',{token:this.token},true).then(349 res => this.appEnable(350 res.payload.loginId,351 res.payload.loginName352 ),353 () => this.handleError('authToken')354 );355 this.loading = true;356 },357 authenticatedByUser(loginId,loginName,token,saltKdf) {358 if(token === '')359 return this.handleError('authUser');360 361 // store authentication token362 this.$store.commit('local/token',token);363 364 if(saltKdf === null)365 return this.appEnable(loginId,loginName);366 367 // generate AES key from credentials and login private key salt368 this.pbkdf2PassToAesGcmKey(this.password,saltKdf,this.kdfIterations,true).then(369 key => {370 this.aesGcmExportBase64(key).then(371 keyBase64 => {372 // export AES key to local storage373 this.$store.commit('local/loginKeyAes',keyBase64);374 this.$store.commit('local/loginKeySalt',saltKdf);375 this.appEnable(loginId,loginName);376 },377 err => this.handleError('aesExport')378 );379 },380 err => this.handleError('kdfCreate')381 );382 },383 384 // authentication successful, prepare application load385 appEnable(loginId,loginName) {386 let token = JSON.parse(atob(this.token.split('.')[1]));387 this.$store.commit('isAdmin',token.admin);388 this.$store.commit('isNoAuth',token.noAuth);389 this.$store.commit('loginId',loginId);390 this.$store.commit('loginName',loginName);391 this.$emit('authenticated');392 }393 }...

Full Screen

Full Screen

getSignature.js

Source:getSignature.js Github

copy

Full Screen

1var apis = require("../api").apis;2var request = require('request');3var globals = require('../../common/global').global;4var crypto = require('crypto');5var fs=require("fs");6var signature = {};7var tokenKeep,keepTime,ticketKeep,ticketKeepTime;8var tokenKeep_openid, keepTime_openid, ticketKeep_openid, ticketKeepTime_openid;9exports.signature = signature;10//获取微信签名所需的access_token11signature.GetAccessToken = function(req, res, next) {12 var access_token = req.cookies.access_token;13 var nowTime;14 if(access_token){15 console.info("在cookies返回access_token:", access_token);16 req.body.access_token = access_token;17 return next();18 }19 apis.GetAccessToken.url = apis.AccessTokenUrl + "?grant_type=client_credential&appid=" + apis.appid + "&secret=" + apis.appsecret;20 console.info("获取微信access_token请求参数:", apis.GetAccessToken);21 function callback(error, response, body) {22 if (!error && response.statusCode == 200) {23 var json = JSON.parse(body);24 console.info("获取微信access_token返回:", json);25 if (json.access_token) {26 res.cookie('access_token',json.access_token,{ maxAge: 6600000});27 tokenKeep=json.access_token;28 keepTime=new Date().getTime();29 req.body.access_token = json.access_token;30 return next();31 }32 return res.json({ error: json.errcode, message: json.errmsg });33 } else {34 return res.render('error', { error: -2, message: "服务器异常" });35 }36 }37 nowTime = new Date().getTime();38 if (tokenKeep == "" || tokenKeep == undefined || tokenKeep == null || keepTime == undefined || (nowTime-keepTime>6000000)) {39 request(apis.GetAccessToken, callback);40 }41 else{42 req.body.access_token=tokenKeep;43 return next();44 }45}46//获取微信签名所需的ticket47signature.GetTicket = function(req, res, next) {48 var ticket = req.cookies.ticket;49 var nowTime;50 if(ticket){51 console.info("在cookies返回ticket:", ticket);52 req.body.ticket = ticket;53 return next();54 }55 apis.GetTicket.url = apis.TicketUrl + "?access_token=" + req.body.access_token + "&type=jsapi";56 console.info("获取微信ticket请求参数:", apis.GetTicket);57 function callback(error, response, body) {58 if (!error && response.statusCode == 200) {59 var json = JSON.parse(body);60 console.info("获取微信ticket返回:", json);61 if (json.ticket) {62 res.cookie('ticket',json.ticket,{ maxAge: 6600000});63 req.body.ticket = json.ticket;64 ticketKeep = json.ticket;65 ticketKeepTime=new Date().getTime();66 return next();67 }68 return res.render('error', {69 error: json.errcode,70 message: json.errmsg71 });72 } else {73 return res.render('error', { error: -2, message: "服务器异常" });74 }75 }76 nowTime = new Date().getTime();77 if (ticketKeep == "" || ticketKeep == undefined || ticketKeep == null || ticketKeepTime==undefined || (nowTime - ticketKeepTime>6000000)) {78 request(apis.GetTicket, callback);79 }80 else{81 req.body.ticket=ticketKeep;82 return next();83 }84}85//拼装配置参数86signature.GetConfig = function(req, res, next) {87 var ticket = req.body.ticket;88 var noncestr = globals.generateRandomAlphaNum(10, 1);89 var timestamp = (Date.parse(new Date()) / 1000).toString();90 var url = req.query.url;91 var string = 'jsapi_ticket=' + ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url;92 var signature = crypto.createHash('SHA1').update(string).digest("HEX");93 req.body.ConfigData = {94 time: new Date().getTime(),95 url: url,96 config: {97 timestamp: timestamp,98 nonceStr: noncestr,99 signature: signature,100 appId: apis.appid101 }102 };103 console.log("返回微信配置参数", req.body.ConfigData)104 return next();105}106// 获取openid和网页授权access_token107signature.GetOpenId = function (req, res, next) {108 var openid = req.cookies.openid;109 var nowTime;110 if (openid) {111 console.info("在cookies返回openid:", openid);112 req.body.openid = openid;113 return next();114 }115 nowTime = new Date().getTime();116 if (tokenKeep_openid == "" || tokenKeep_openid == undefined || tokenKeep_openid == null || keepTime_openid == undefined || (nowTime - keepTime_openid > 6000000)) {117 let reqJson = apis.GetOpenId(req.query.code);118 console.info('GetOpenId参数:', reqJson);119 request(reqJson, (error, response, body) => {120 if (!error && response.statusCode == 200) {121 var json = JSON.parse(body);122 console.info("获取GetOpenId返回:", json);123 if (json.openid) {124 res.cookie('openid', json.openid, { maxAge: 6600000 });125 tokenKeep_openid = json.openid;126 keepTime_openid = new Date().getTime();127 req.body.openid = json.openid;128 return next();129 }130 return res.json({ error: json.errcode, message: json.errmsg });131 } else {132 return res.render('error', { error: -2, message: "服务器异常" });133 }134 });135 }136 else {137 req.body.openid = tokenKeep_openid;138 return next();139 }140 ...

Full Screen

Full Screen

storeLocal.js

Source:storeLocal.js Github

copy

Full Screen

1export {MyStoreLocal as default};2const MyStoreLocal = {3 namespaced:true,4 state:{5 activated:false, // application is activated via valid license file6 appName:'App Name',7 appNameShort:'App',8 appVersion:'', // full application version (as in 1.2.0.3422)9 companyColorHeader:'',// custom color on header10 companyColorLogin:'', // custom color on login screen11 companyLogo:'', // custom company logo12 companyLogoUrl:'', // custom company logo, href URL when clicked on13 companyName:'', // custom company name on login screen14 companyWelcome:'', // custom welcome message on login screen15 fieldIdMapOption:{}, // map of field IDs with field options16 loginKeyAes:null, // en-/decryption key for login private key17 loginKeySalt:null, // salt for login key KDF18 menuIdMapOpen:{}, // map of menu IDs with open state (true/false)19 token:'', // JWT token20 tokenKeep:false // keep JWT token between sessions21 },22 mutations:{23 activated:function(state,payload) {24 state.activated = payload;25 set('activated',payload);26 },27 appName:function(state,payload) {28 state.appName = payload;29 set('appName',payload);30 },31 appNameShort:function(state,payload) {32 state.appNameShort = payload;33 set('appNameShort',payload);34 },35 appVersion:function(state,payload) {36 state.appVersion = payload;37 set('appVersion',payload);38 },39 companyColorHeader:function(state,payload) {40 state.companyColorHeader = payload;41 set('companyColorHeader',payload);42 },43 companyColorLogin:function(state,payload) {44 state.companyColorLogin = payload;45 set('companyColorLogin',payload);46 },47 companyLogo:function(state,payload) {48 state.companyLogo = payload;49 set('companyLogo',payload);50 },51 companyLogoUrl:function(state,payload) {52 state.companyLogoUrl = payload;53 set('companyLogoUrl',payload);54 },55 companyName:function(state,payload) {56 state.companyName = payload;57 set('companyName',payload);58 },59 companyWelcome:function(state,payload) {60 state.companyWelcome = payload;61 set('companyWelcome',payload);62 },63 fieldOptionSet:function(state,payload) {64 let fieldId = payload.fieldId;65 let name = payload.name;66 let value = payload.value;67 68 if(typeof state.fieldIdMapOption[fieldId] === 'undefined')69 state.fieldIdMapOption[fieldId] = {};70 71 state.fieldIdMapOption[fieldId][name] = value;72 73 set('fieldIdMapOption',state.fieldIdMapOption);74 },75 loginKeyAes:function(state,payload) {76 state.loginKeyAes = payload;77 set('loginKeyAes',payload);78 },79 loginKeySalt:function(state,payload) {80 state.loginKeySalt = payload;81 set('loginKeySalt',payload);82 },83 menuIdMapOpenToggle:function(state,payload) {84 if(typeof state.menuIdMapOpen[payload] === 'undefined')85 state.menuIdMapOpen[payload] = true;86 else87 state.menuIdMapOpen[payload] = !state.menuIdMapOpen[payload];88 89 set('menuIdMapOpen',state.menuIdMapOpen);90 },91 token:function(state,payload) {92 state.token = payload;93 set('token',payload);94 },95 tokenKeep:function(state,payload) {96 state.tokenKeep = payload;97 set('tokenKeep',payload);98 }99 },100 getters:{101 customBgLogin:function(state) {102 if(!state.activated || state.companyColorLogin === '')103 return '';104 105 return `background-color:#${state.companyColorLogin};`;106 },107 customBgHeader:function(state) {108 if(!state.activated || state.companyColorHeader === '')109 return '';110 111 return `background-color:#${state.companyColorHeader};`;112 },113 customLogo:function(state) {114 if(!state.activated || state.companyLogo === '')115 return 'images/logo.png';116 117 return `data:image/png;base64,${state.companyLogo}`;118 },119 customLogoUrl:function(state) {120 if(!state.activated || state.companyLogoUrl === '')121 return 'https://rei3.de/';122 123 return state.companyLogoUrl;124 },125 126 // simple getters127 activated: (state) => state.activated,128 appName: (state) => state.appName,129 appNameShort: (state) => state.appNameShort,130 appVersion: (state) => state.appVersion,131 companyColorHeader:(state) => state.companyColorHeader,132 companyColorLogin: (state) => state.companyColorLogin,133 companyLogo: (state) => state.companyLogo,134 companyLogoUrl: (state) => state.companyLogoUrl,135 companyName: (state) => state.companyName,136 companyWelcome: (state) => state.companyWelcome,137 fieldIdMapOption: (state) => state.fieldIdMapOption,138 loginKeyAes: (state) => state.loginKeyAes,139 loginKeySalt: (state) => state.loginKeySalt,140 menuIdMapOpen: (state) => state.menuIdMapOpen,141 token: (state) => state.token,142 tokenKeep: (state) => state.tokenKeep143 }144};145// read values from local storage on init146let init = function() {147 for(let k in MyStoreLocal.state) {148 let value = localStorage.getItem(k);149 150 if(value !== null)151 MyStoreLocal.state[k] = JSON.parse(value);152 }153} ()154let set = function(name,value) {155 localStorage.setItem(name,JSON.stringify(value));...

Full Screen

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 ng-mocks 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