File tree 2 files changed +80
-2
lines changed
2 files changed +80
-2
lines changed Original file line number Diff line number Diff line change 6
6
)
7
7
8
8
var (
9
- ErrMalformedToken = errors .New ("token: invalid format" )
9
+ ErrMalformedToken = errors .New ("foundations/ token: invalid format" )
10
10
)
11
11
12
12
// TokenFromBearerString returns the token from a bearer token string.
@@ -15,5 +15,10 @@ func TokenFromBearerString(str string) (string, error) {
15
15
return "" , ErrMalformedToken
16
16
}
17
17
18
- return strings .TrimPrefix (strings .TrimSpace (str ), "Bearer " ), nil
18
+ tok := strings .TrimSpace (strings .TrimPrefix (str , "Bearer " ))
19
+ if tok == "" {
20
+ return "" , ErrMalformedToken
21
+ }
22
+
23
+ return tok , nil
19
24
}
Original file line number Diff line number Diff line change
1
+ package token
2
+
3
+ import (
4
+ "testing"
5
+
6
+ "github.com/stretchr/testify/assert"
7
+ )
8
+
9
+ func TestTokenFromBearerString (t * testing.T ) {
10
+ tests := []struct {
11
+ name string
12
+ input string
13
+ want string
14
+ wantErr bool
15
+ }{
16
+ {
17
+ name : "Valid bearer token" ,
18
+ input : "Bearer abc123" ,
19
+ want : "abc123" ,
20
+ wantErr : false ,
21
+ },
22
+ {
23
+ name : "Valid bearer token with spaces" ,
24
+ input : "Bearer xyz789 " ,
25
+ want : "xyz789" ,
26
+ wantErr : false ,
27
+ },
28
+ {
29
+ name : "Missing 'Bearer' prefix" ,
30
+ input : "abc123" ,
31
+ want : "" ,
32
+ wantErr : true ,
33
+ },
34
+ {
35
+ name : "Empty string" ,
36
+ input : "" ,
37
+ want : "" ,
38
+ wantErr : true ,
39
+ },
40
+ {
41
+ name : "Only 'Bearer' without token" ,
42
+ input : "Bearer " ,
43
+ want : "" ,
44
+ wantErr : true ,
45
+ },
46
+ {
47
+ name : "Lowercase 'bearer'" ,
48
+ input : "bearer abc123" ,
49
+ want : "" ,
50
+ wantErr : true ,
51
+ },
52
+ {
53
+ name : "Token with spaces" ,
54
+ input : "Bearer abc 123 xyz" ,
55
+ want : "abc 123 xyz" ,
56
+ wantErr : false ,
57
+ },
58
+ }
59
+
60
+ for _ , tt := range tests {
61
+ t .Run (tt .name , func (t * testing.T ) {
62
+ got , err := TokenFromBearerString (tt .input )
63
+
64
+ if tt .wantErr {
65
+ assert .Error (t , err )
66
+ assert .Empty (t , got )
67
+ } else {
68
+ assert .NoError (t , err )
69
+ assert .Equal (t , tt .want , got )
70
+ }
71
+ })
72
+ }
73
+ }
You can’t perform that action at this time.
0 commit comments