-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.w
116 lines (99 loc) · 2.7 KB
/
main.w
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
bring cloud;
bring util;
bring http;
bring expect;
struct Credentials {
username: str;
password: str;
}
class BasicAuth {
user: str;
password: str;
new(user: str?, password: str?) {
this.user = user ?? "admin";
this.password = password ?? "admin";
}
pub inflight call(req: cloud.ApiRequest): bool {
try {
let authHeader = this.authHeader(req.headers);
let credentials = this.authCredentials(authHeader);
let username = credentials.username;
let password = credentials.password;
return username == this.user && password == this.password;
} catch e {
log("exception caught {e}");
return false;
}
}
inflight authCredentials(header: str): Credentials {
let auth = util.base64Decode(header.split(" ").at(1));
let splittedAuth = auth.split(":");
let username = splittedAuth.at(0);
let password = splittedAuth.at(1);
return Credentials {
username: username,
password: password
};
}
// workaround for https://github.com/winglang/wing/issues/3205
inflight authHeader(headers: Map<str>?): str {
if (this.authHeaderPresent(headers)) {
let authHeaderOptional = headers?.tryGet("authorization");
let var authHeader = headers?.tryGet("Authorization");
if (authHeader == nil) {
authHeader = authHeaderOptional;
}
// force cast to str from str?
return "{authHeader}";
} else {
log("headers: {Json.stringify(headers)}");
log("no auth header");
throw("no auth header");
}
}
// workaround for https://github.com/winglang/wing/issues/3205
inflight authHeaderPresent(headers: Map<str>?): bool {
if (headers?.has("authorization") == false) && (headers?.has("Authorization") == false) {
return false;
}
return true;
}
}
let auth = new BasicAuth();
let api = new cloud.Api();
api.get("/hello", inflight (req) => {
let authenticated = auth.call(req);
if (!authenticated) {
return {
status: 401,
headers: {
"Content-Type" => "text/plain"
},
body: "Unauthorized"
};
}
return {
status: 200,
headers: {
"Content-Type" => "text/plain"
},
body: "hello world"
};
});
// workaround for https://github.com/winglang/wing/issues/3289
// this shouldn't be necessary, since api.url should
// be directly accessible in the test
let apiUrl = api.url;
test "not authenticated" {
let response = http.get("{apiUrl}/hello");
expect.equal(response.status, 401);
}
test "authenticated" {
let response = http.get("{apiUrl}/hello", {
headers: {
Accept: "application/json",
Authorization: "Basic " + util.base64Encode("admin:admin")
}
});
expect.equal(response.status, 200);
}