rajt
Version:
A serverless bundler layer, fully typed for AWS Lambda (Node.js and LLRT) and Cloudflare Workers.
85 lines (66 loc) • 2.08 kB
text/typescript
import { Envir } from 't0n'
import { Token as Factory } from 'cripta'
import c from '../context'
export class Token {
static
static
static fromRequest() {
const token = this.fromCookie() || this.fromHeader()
return token ? this.parse(token) : null
}
static fromHeader(): string | null {
const header = c.cx.req.header(this.
if (header) {
const position = header.toLowerCase().indexOf(this.
if (position !== -1) {
let token = header.slice(position + this.
const commaPos = token.indexOf(',')
if (commaPos !== -1) token = token.slice(0, commaPos).trim()
return token
}
}
return null
}
static fromCookie(): string | null {
const uid = c.cx.req.header('uid')
if (uid) {
const auth = c.cookie.get('__auth_' + uid)
return auth ? auth : null
}
return null
}
static parse(token: string) {
const host = this.host(Envir.get('FLOW_SERVER'))
return Factory.parse(token)
.issuedBy(host)
.permittedFor(host)
}
static create(user: any, exp: number = 7200) {
const time = Math.floor(Date.now() / 1000)
const host = this.host(c.cx.req.header('host') || '')
return Factory.create()
.issuedBy(host)
.permittedFor(host)
.issuedAt(time)
.expiresAt(time + exp)
.body(user)
}
static setPrefix(prefix: string): void {
this.
}
static setName(name: string): void {
this.
}
static host(url?: string | null | undefined): string {
if (!url) url = c.cx.req.url || c.cx.req.header('host') || ''
let formattedUrl = String(url)
if (!formattedUrl.startsWith('http'))
formattedUrl = 'http://' + formattedUrl
try {
const parsedUrl = new URL(formattedUrl)
return parsedUrl.host
} catch (e) {
return ''
}
}
}