FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
adminforth/adminforth/auth.ts at update-express-version · devforth/adminforth · GitHub
devforth
adminforth
Repository navigation
Code
Issues
16
(16)
Pull requests
4
(4)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
adminforth
/
adminforth
/
auth.ts
Copy path
More file actions
More file actions
Latest commit
History
History
History
201 lines (176 loc) · 7.02 KB
Breadcrumbs
adminforth
/
adminforth
/
auth.ts
Copy path
File metadata and controls
201 lines (176 loc) · 7.02 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import
jwt
from
'jsonwebtoken'
;
import
crypto
from
'crypto'
;
import
AdminForth
from
'./index.js'
;
import
{
IAdminForthAuth
}
from
'./types/Back.js'
;
import
{
afLogger
}
from
'./modules/logger.js'
;
import
is_ip_private
from
'private-ip'
// Function to generate a password hash using PBKDF2
function
calcPasswordHash
(
password
,
salt
,
iterations
=
100000
,
keyLength
=
64
,
digest
=
'sha512'
)
{
return
new
Promise
(
(
resolve
,
reject
)
=>
{
crypto
.
pbkdf2
(
password
,
salt
,
iterations
,
keyLength
,
digest
,
(
err
,
derivedKey
)
=>
{
if
(
err
)
reject
(
err
)
;
resolve
(
derivedKey
.
toString
(
'hex'
)
)
;
}
)
;
}
)
;
}
// Function to generate a random salt
function
generateSalt
(
length
=
16
)
{
return
crypto
.
randomBytes
(
length
)
.
toString
(
'hex'
)
;
}
function
parseTimeToSeconds
(
time
:
string
)
:
number
{
const
unit
=
time
.
slice
(
-
1
)
;
const
value
=
parseInt
(
time
.
slice
(
0
,
-
1
)
,
10
)
;
switch
(
unit
)
{
case
's'
:
return
value
;
case
'm'
:
return
value
*
60
;
case
'h'
:
return
value
*
60
*
60
;
case
'd'
:
return
value
*
60
*
60
*
24
;
default
:
throw
new
Error
(
`Invalid time unit:
${
unit
}
`
)
;
}
}
class
AdminForthAuth
implements
IAdminForthAuth
{
adminforth
:
AdminForth
;
constructor
(
adminforth
)
{
this
.
adminforth
=
adminforth
;
}
getClientIp
(
headers
:
object
)
{
const
clientIpHeader
=
this
.
adminforth
.
config
.
auth
.
clientIpHeader
;
const
headersLower
=
Object
.
keys
(
headers
)
.
reduce
(
(
acc
,
key
)
=>
{
acc
[
key
.
toLowerCase
(
)
]
=
headers
[
key
]
;
return
acc
;
}
,
{
}
)
;
let
ip
:
string
|
null
=
null
;
if
(
clientIpHeader
)
{
ip
=
headersLower
[
clientIpHeader
.
toLowerCase
(
)
]
;
}
else
{
// first try common headers which can't bee spoofed, in other words
// most common to nginx/traefik/apache
// then fallback to less secure headers
ip
=
headersLower
[
'x-forwarded-for'
]
?.
split
(
','
)
.
shift
(
)
.
trim
(
)
||
headersLower
[
'x-real-ip'
]
||
headersLower
[
'x-client-ip'
]
||
headersLower
[
'x-cluster-client-ip'
]
||
headersLower
[
'forwarded'
]
||
headersLower
[
'remote-addr'
]
||
headersLower
[
'client-ip'
]
||
headersLower
[
'client-address'
]
||
headersLower
[
'client'
]
||
headersLower
[
'x-host'
]
||
null
;
}
const
isIpPrivate
=
is_ip_private
(
ip
)
if
(
isIpPrivate
)
{
return
null
;
}
return
ip
;
}
removeAuthCookie
(
response
)
{
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
response
.
setHeader
(
'Set-Cookie'
,
`adminforth_
${
brandSlug
}
_jwt=; Path=
${
this
.
adminforth
.
config
.
baseUrl
||
'/'
}
; HttpOnly; SameSite=Strict; Expires=Thu, 01 Jan 1970 00:00:00 GMT`
)
;
}
setAuthCookie
(
{
expireInDuration
,
response
,
username
,
pk
}
:
{
expireInDuration
?:
string
,
response
:
any
,
username
:
string
,
pk
:
string
|
null
}
)
{
const
expiresIn
:
string
=
expireInDuration
||
(
process
.
env
.
ADMINFORTH_AUTH_EXPIRESIN
||
'24h'
)
;
// might be h,m,d in string
const
expiresInSec
=
parseTimeToSeconds
(
expiresIn
)
;
const
token
=
this
.
issueJWT
(
{
username
,
pk
}
,
'auth'
,
expiresInSec
)
;
const
expiresCookieFormat
=
new
Date
(
Date
.
now
(
)
+
expiresInSec
*
1000
)
.
toUTCString
(
)
;
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
response
.
setHeader
(
'Set-Cookie'
,
`adminforth_
${
brandSlug
}
_jwt=
${
token
}
; Path=
${
this
.
adminforth
.
config
.
baseUrl
||
'/'
}
; HttpOnly; SameSite=Strict; Expires=
${
expiresCookieFormat
}
`
)
;
}
removeCustomCookie
(
{
response
,
name
}
)
{
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
response
.
setHeader
(
'Set-Cookie'
,
`adminforth_
${
brandSlug
}
_
${
name
}
=; Path=
${
this
.
adminforth
.
config
.
baseUrl
||
'/'
}
; HttpOnly; SameSite=Strict; Expires=Thu, 01 Jan 1970 00:00:00 GMT`
)
;
}
setCustomCookie
(
{
response
,
payload
}
:
{
response
:
any
,
payload
:
{
name
:
string
,
value
:
string
,
expiry
?:
number
|
undefined
,
expirySeconds
:
number
|
undefined
,
httpOnly
:
boolean
,
sessionBased
?:
boolean
|
undefined
}
}
)
{
const
{
name
,
value
,
expiry
,
httpOnly
,
expirySeconds
,
sessionBased
}
=
payload
;
let
expiryMs
=
24
*
60
*
60
*
1000
;
// default 1 day
if
(
expirySeconds
!==
undefined
)
{
expiryMs
=
expirySeconds
*
1000
;
}
else
if
(
expiry
!==
undefined
)
{
afLogger
.
warn
(
`setCustomCookie: expiry(in ms) is deprecated, use expirySeconds instead (seconds), traceback:
${
new
Error
(
)
.
stack
}
`
)
;
expiryMs
=
expiry
;
}
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
response
.
setHeader
(
'Set-Cookie'
,
`adminforth_
${
brandSlug
}
_
${
name
}
=
${
value
}
; Path=
${
this
.
adminforth
.
config
.
baseUrl
||
'/'
}
;
${
httpOnly
?
' HttpOnly;'
:
''
}
SameSite=Strict;
${
sessionBased
?
''
:
`Expires=
${
new
Date
(
Date
.
now
(
)
+
expiryMs
)
.
toUTCString
(
)
}
`
}
`
)
;
}
getCustomCookie
(
{
cookies
,
name
}
:
{
cookies
:
{
key
:
string
,
value
:
string
}
[
]
,
name
:
string
}
)
:
string
|
null
{
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
return
cookies
.
find
(
(
cookie
)
=>
cookie
.
key
===
`adminforth_
${
brandSlug
}
_
${
name
}
`
)
?.
value
||
null
;
}
issueJWT
(
payload
:
Object
,
type
:
string
,
expiresIn
:
string
|
number
=
'24h'
)
:
string
{
// read ADMINFORH_SECRET from environment if not drop error
const
secret
=
process
.
env
.
ADMINFORTH_SECRET
;
if
(
!
secret
)
{
throw
new
Error
(
'ADMINFORTH_SECRET environment not set'
)
;
}
// issue JWT token
return
jwt
.
sign
(
{
...
payload
,
t
:
type
}
,
secret
,
{
expiresIn
}
)
;
}
async
verify
(
jwtToken
:
string
,
mustHaveType
:
string
,
decodeUser
:
boolean
|
undefined
=
true
)
:
Promise
<
Object
>
{
// read ADMINFORH_SECRET from environment if not drop error
const
secret
=
process
.
env
.
ADMINFORTH_SECRET
;
if
(
!
secret
)
{
throw
new
Error
(
'ADMINFORTH_SECRET environment not set'
)
;
}
let
decoded
;
try
{
// verify JWT token
decoded
=
jwt
.
verify
(
jwtToken
,
secret
)
;
}
catch
(
err
)
{
if
(
err
.
name
===
'TokenExpiredError'
)
{
afLogger
.
info
(
`Token expired:
${
err
.
message
}
`
)
;
}
else
if
(
err
.
name
===
'JsonWebTokenError'
)
{
afLogger
.
info
(
`Token error:
${
err
.
message
}
, JWT secret changed?`
)
;
}
else
{
afLogger
.
error
(
`Failed to verify JWT token:
${
err
}
`
)
;
}
return
null
;
}
const
{
pk
,
t
}
=
decoded
;
if
(
t
!==
mustHaveType
)
{
afLogger
.
error
(
`Invalid token type during verification:
${
t
}
, must be
${
mustHaveType
}
`
)
;
return
null
;
}
if
(
decodeUser
!==
false
)
{
const
dbUser
=
await
this
.
adminforth
.
getUserByPk
(
pk
)
;
if
(
!
dbUser
)
{
afLogger
.
error
(
`User with pk
${
pk
}
not found in database`
)
;
// will logout user which was deleted
return
null
;
}
decoded
.
dbUser
=
dbUser
;
}
return
decoded
;
}
static
async
generatePasswordHash
(
password
)
{
const
salt
=
generateSalt
(
)
;
const
hashedPassword
=
await
calcPasswordHash
(
password
,
salt
)
;
return
`
${
salt
}
:
${
hashedPassword
}
`
;
}
static
async
verifyPassword
(
password
,
hashedPassword
)
{
const
[
salt
,
hash
]
=
hashedPassword
.
split
(
':'
)
;
const
newHash
=
await
calcPasswordHash
(
password
,
salt
)
;
return
newHash
===
hash
;
}
}
export
default
AdminForthAuth
;
Back
|
FazBrowse Home
|
New Git URL