-
-
Save lorique/6ad269b30005b5efb985141741375cd5 to your computer and use it in GitHub Desktop.
Postman - Pre-Request script for handing tokens
This file contains hidden or 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
| // Refresh the token if necessary | |
| let tokenDate = new Date(2010,1,1); | |
| let tokenTimestamp = pm.collectionVariables.get('timestamp'); | |
| let userId = pm.collectionVariables.get('userid') | |
| let token = pm.collectionVariables.get('token') | |
| let expiresInTime = pm.collectionVariables.get('expires_in'); | |
| if(tokenTimestamp){ | |
| tokenDate = Date.parse(tokenTimestamp); | |
| } | |
| if(!expiresInTime){ | |
| expiresInTime = 1500000; // Set default expiration time to 15 minutes | |
| } | |
| now = Date.now(); | |
| let elapsed = (now - tokenDate) / 1000; | |
| if(elapsed >= expiresInTime || token === null || token === undefined) | |
| { | |
| let url = pm.environment.get('host') | |
| url += ':' + pm.environment.get('port') | |
| url += pm.environment.get('uri') | |
| pm.sendRequest({ | |
| url: url + '/auth/login', | |
| method: 'POST', | |
| header: { | |
| 'Accept': 'application/json', | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: { | |
| mode: 'raw', | |
| raw: { | |
| 'email': pm.environment.get('username'), | |
| 'password': pm.environment.get('password'), | |
| } | |
| } | |
| }, function (err, res) { | |
| if (res.code === 200) { | |
| let response = res.json(); | |
| pm.collectionVariables.set('token', response.access_token); | |
| pm.collectionVariables.set('timestamp', new Date()); | |
| pm.collectionVariables.set('userid', response.id); | |
| pm.collectionVariables.set('expires_in', response.expires_in); | |
| console.log('Token set: ' + response.access_token); | |
| } | |
| else { | |
| console.log(res); | |
| throw new Error('Login failed with status: ' + res.status + ' (Code: ' + res.code + ')') | |
| } | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment