qpa-client/server/src/Auth/SessionManager.ts

111 lines
3.3 KiB
TypeScript
Raw Normal View History

2018-04-02 20:23:44 +02:00
// Free API to get location from IP: http://freegeoip.net/json/149.11.144.50
2018-05-11 10:12:56 +02:00
import {User, UserDbObject, UserSession, UserSessionDbObject} from "../@types";
2018-05-05 22:11:43 +02:00
const randomstring = require('random-string')
import {sendEmail} from '../post_office'
import {domain} from '../config'
import {ObjectID} from "mongodb";
import AuthRepository from "./AuthRepository";
2018-05-04 19:53:16 +02:00
2018-09-30 12:33:59 +02:00
export class SessionAlreadyValidatedError extends Error {}
2018-09-30 09:36:17 +02:00
const generateHash = () => randomstring({
2018-05-11 10:12:56 +02:00
length: 48,
letters: true,
special: false
})
2018-05-04 19:53:16 +02:00
export class SessionInvite {
2018-05-11 08:24:18 +02:00
hash: string
2018-05-04 19:53:16 +02:00
userId: string
2018-05-11 10:12:56 +02:00
timeValidated?: number
2018-05-04 19:53:16 +02:00
constructor(user: User) {
2018-05-11 10:12:56 +02:00
this.hash = generateHash()
2018-05-04 19:53:16 +02:00
this.userId = user.id
2018-05-11 10:12:56 +02:00
this.timeValidated = null
2018-04-02 20:23:44 +02:00
}
}
2018-05-11 08:24:18 +02:00
2018-05-04 19:53:16 +02:00
export default class SessionManager {
authRepository: AuthRepository
2018-05-04 19:53:16 +02:00
constructor(authRepository: AuthRepository) {
this.authRepository = authRepository
2018-05-11 10:12:56 +02:00
}
inviteUser = async (email: string): Promise<SessionInvite> => {
const user = await this.authRepository.getUser({ email });
if (!user) {
throw new Error('Could not find user for this email');
}
const { _id, ...userProps } = user;
const invite = new SessionInvite({
id: _id.toString(),
...userProps
});
2018-05-11 10:12:56 +02:00
try {
const persistedInvite = await this.authRepository.saveSessionInvite(invite)
2018-05-11 10:12:56 +02:00
console.log(`Invite persisted for user ${user.username}`, persistedInvite)
} catch (e) {
console.error('Failed to save invite', invite)
throw e;
2018-05-04 19:53:16 +02:00
}
2018-05-19 13:43:35 +02:00
return new Promise(async (resolve: (SessionInvite) => void, reject)=>{
try {
await sendEmail({
to: user.email,
from: `signin@${domain}`,
2018-09-30 12:33:59 +02:00
text: `Follow this link to start a session: https://${domain}/login/${invite.hash}`,
2018-05-19 13:43:35 +02:00
subject: 'Invitation for session'
})
resolve(invite)
console.log(`Sent invitation to ${user.email}`)
} catch (e) {
reject(e)
console.error('Failed to send invitation email ', invite, e)
throw e
}
})
2018-05-11 10:12:56 +02:00
}
2018-05-04 19:53:16 +02:00
initiateSession = async (inviteHash: string): Promise<UserSessionDbObject> => {
const sessionInvite: SessionInvite = await this.authRepository.getSessionInvite(inviteHash)
2019-01-30 16:44:05 +01:00
if (!sessionInvite) {
throw new Error(`Could not find invite with hash ${inviteHash}`)
}
2018-05-11 10:12:56 +02:00
if (sessionInvite.timeValidated) {
2018-09-30 09:36:17 +02:00
throw new SessionAlreadyValidatedError()
2018-05-11 10:12:56 +02:00
}
const matchingUser: UserDbObject = await this.authRepository.getUserById(sessionInvite.userId)
2019-01-30 16:44:05 +01:00
if (!matchingUser) {
console.error(`Invite hash ${inviteHash} could not find related userId ${sessionInvite.userId}`)
throw new Error('Cannot find related user to this invite')
}
if (matchingUser._id.equals(sessionInvite.userId)) {
const session: UserSessionDbObject = {
user: matchingUser._id,
2018-05-11 10:12:56 +02:00
ctime: Date.now(),
isValid: true,
hash: generateHash(),
2018-05-04 19:53:16 +02:00
}
const persistedSession = await this.authRepository.createSession(session)
2018-05-11 10:12:56 +02:00
return Promise.resolve(persistedSession)
} else {
console.warn(`user ids didn't match. userId: ${matchingUser._id}. sessionUserId: ${sessionInvite.userId}`)
return Promise.resolve(null)
2018-05-04 19:53:16 +02:00
}
2018-05-11 10:12:56 +02:00
}
2018-06-03 12:33:51 +02:00
getSession = async(sessionHash: string): Promise<UserSessionDbObject> => {
return await this.authRepository.getSession(sessionHash)
2018-06-03 12:33:51 +02:00
}
2018-05-04 19:53:16 +02:00
}