v2 / vlib / veb / oauth / oauth.v
64 lines · 56 sloc · 1.23 KB · c51d30bf5309653c6b573ec815268e69a78ea8cc
Raw
1module oauth
2
3import json
4import net.http
5
6pub enum TokenPostType {
7 form
8 json
9}
10
11pub struct Context {
12pub:
13 token_url string
14 client_id string
15 client_secret string
16 token_post_type TokenPostType = .form
17 redirect_uri string
18}
19
20pub struct Request {
21pub:
22 client_id string
23 client_secret string
24 code string
25 state string
26}
27
28pub fn (ctx &Context) get_token(code string) string {
29 oauth_request := Request{
30 client_id: ctx.client_id
31 client_secret: ctx.client_secret
32 code: code
33 // state: csrf
34 }
35
36 js := json.encode(oauth_request)
37 if ctx.token_post_type == .json {
38 resp := http.post_json(ctx.token_url, js) or {
39 // app.info(err.msg())
40
41 // return app.redirect_to_index()
42 return ''
43 }
44 println('OAUTH RESPONSE ${resp}')
45 return resp.body
46 } else {
47 resp := http.post_form(ctx.token_url, {
48 'client_id': ctx.client_id
49 'client_secret': ctx.client_secret
50 'code': code
51 'grant_type': 'authorization_code'
52 //'scope': bot
53 'redirect_uri': ctx.redirect_uri
54 }) or {
55 // app.info(err.msg())
56
57 // return app.redirect_to_index()
58 return ''
59 }
60 println('OAUTH RESPONSE ${resp}')
61 return resp.body
62 }
63 return ''
64}
65