@stacksjs/auth 0.68.1 → 0.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,76 @@ declare interface Credentials {
5
5
  declare type AuthToken = `${number}:${number}:${string}`
6
6
 
7
7
  const authConfig = { username: 'email', password: 'password' }
8
- export declare function attempt(credentials: Credentials): Promise<boolean>;
9
- export declare function team(): Promise<TeamModel | undefined>;
10
- export declare function authToken(): Promise<AuthToken | undefined>;
8
+
9
+ let authUser: any
10
+
11
+ export async function attempt(credentials: Credentials): Promise<boolean> {
12
+ let hashCheck = false
13
+
14
+ const user = await User.where(authConfig.username, credentials[authConfig.username]).first()
15
+ const authPass = credentials[authConfig.password]
16
+
17
+ if (typeof authPass === 'string' && user?.password)
18
+ hashCheck = await verifyHash(authPass, user?.password, 'bcrypt')
19
+
20
+ if (hashCheck) {
21
+ if (user) {
22
+ authUser = user
23
+
24
+ return true
25
+ }
26
+ }
27
+
28
+ return false
29
+ }
30
+
31
+ export async function team(): Promise<TeamModel | undefined> {
32
+ if (authUser) {
33
+ const teams = await authUser.userTeams()
34
+
35
+ return teams[0].team
36
+ }
37
+
38
+ const bearerToken = request.bearerToken()
39
+
40
+ if (!bearerToken) {
41
+ return undefined
42
+ }
43
+
44
+ const parts = bearerToken.split(':')
45
+
46
+ if (parts.length !== 3)
47
+ throw new HttpError(401, 'Invalid bearer token format')
48
+
49
+ const tokenId = Number(parts[0])
50
+ const teamId = parts[1]
51
+ const plainString = parts[2]
52
+
53
+ const accessToken = await AccessToken.where('id', Number(tokenId)).where('token', plainString).first()
54
+
55
+ if (Number(teamId) !== Number(accessToken?.team_id)) {
56
+ return undefined
57
+ }
58
+
59
+ const team = await Team.find(Number(accessToken?.team_id))
60
+
61
+ return team
62
+ }
63
+
64
+ export async function authToken(): Promise<AuthToken | undefined> {
65
+ if (authUser) {
66
+ const teams = await authUser.userTeams()
67
+
68
+ const team = teams[0]
69
+
70
+ const accessTokens = await team.teamAccessTokens()
71
+ const accessToken = accessTokens[0]
72
+
73
+ const tokenId = accessToken?.id
74
+
75
+ if (!accessToken)
76
+ throw new HttpError(500, 'Error generating token!')
77
+
78
+ return `${tokenId}:${team.id}:${accessToken.token}`
79
+ }
80
+ }