Skip to content

Instantly share code, notes, and snippets.

@raxityo
Created July 6, 2022 16:20
Show Gist options
  • Save raxityo/f3872a4caeaa11f79921c3c252ceccc6 to your computer and use it in GitHub Desktop.
Save raxityo/f3872a4caeaa11f79921c3c252ceccc6 to your computer and use it in GitHub Desktop.
An example implementation of session-less redis store that can be used with `passport-oauth1` and any strategies that depend on oauth1, such as passport-twitter
/**
* ©️ Copyright 2022 Raxit Majithiya https://github.com/raxityo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { Request } from 'express'
import redis from 'lib/redis'
/**
* Session store to store tokens<>tokenSecret pair in redis instead of using client side session.
*
* Usage when setting up the strategy options:
* ```
* const sessionKey = 'oauth:twitter'
* const strategyOptions: IStrategyOptionWithRequest & { store: RedisSessionStore } = {
* consumerKey,
* consumerSecret,
* callbackURL,
* passReqToCallback: true,
* includeEmail: true,
* sessionKey,
* store: new RedisSessionStore({ key: sessionKey }),
* }
* ```
*/
export class RedisSessionStore {
static EX_TOKEN = 3600
key: string
constructor(options: { key: string }) {
this.key = options.key
}
get = (req: Request, token: string, callback: (error: Error | null, tokenSecret: string | null) => void) => {
redis.get(this.getKey(token), (error, tokenSecret) =>
tokenSecret
? callback(null, tokenSecret)
: callback(error || new Error('Failed to find request token in session'), null)
)
}
set = (req: Request, token: string, tokenSecret: string, callback: () => void) => {
redis.set(this.getKey(token), tokenSecret, 'EX', RedisSessionStore.EX_TOKEN, () => callback())
}
destroy = (req: Request, token: string, callback: () => void) => {
redis.del(this.getKey(token), () => callback())
}
private getKey = (token: string) => `${this.key}:${token}`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment