Newer
Older
const ContextualModule = require('core/injection/ContextualModule')
const crypto = require('core/utils/crypto')
const HttpError = require('core/errors/HttpError')
const { User } = require('database/models')
const BEARER_PREFIX = 'Bearer '
module.exports = class AuthService extends ContextualModule {
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
static getServiceName() {
return 'authService'
}
constructor(ctx) {
super(ctx);
this._user = null
this._stack = [] // TODO: Support user impersonation
}
async attemptLogin(email, password) {
if (this._user) {
if (this._user.email === email && await this._user.checkPassword(password)) {
return this._user
} else {
throw new HttpError(401, 'Forbidden')
}
} else {
const user = await this.ctx.services.userService.findByEmail(email)
if (user) {
if (await user.checkPassword(password)) {
this.authenticateAs(user)
return user
} else {
throw new HttpError(403, 'Huh')
}
} else {
throw new HttpError(403, 'Wha')
}
}
}
async getUser() {
if (this._user) {
return this._user
} else if (this.ctx.session && this.ctx.session.user) {
try {
const value = JSON.parse(await crypto.decrypt(this.ctx.session.user))
const user = await this.ctx.services.userService.findUser(value.id)
if (user) {
this.authenticateAs(user)
return user
} else {
return null
}
} catch(e) {
console.error(e)
this.clearSessionAuth()
return null
}
} else if (this.ctx.get('Authorization')) {
const token = this.ctx.get('Authorization').substr(BEARER_PREFIX.length)

Louis
committed
console.log("TOKEN", token)
const user = await this.ctx.services.userService.findByAccessToken(token)

Louis
committed
console.log(user)
} else if (this.ctx.get('x-api-token')) {
const token = this.ctx.get('x-api-token')
let user = null
try {
user = await User.fromToken(token)
} catch(e) {
console.error(e)
}
if (user) {
this.authenticateAs(user)
}
return user
}
authenticateAs(user) {
this._user = user
}
async saveToSession(logoutIfEmpty = true) {
const user = await this.getUser()
if (user) {
this.ctx.session.user = await crypto.encrypt(JSON.stringify({ id: user.id }))
} else if (logoutIfEmpty) {
this.ctx.session.user = null
}
}
async clearSessionAuth() {
this.ctx.session.token = null
}
}