This repository has been archived by the owner on Nov 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
auth.go
73 lines (63 loc) · 1.65 KB
/
auth.go
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
package main
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"strings"
)
// Proxied User model. The real user model is in github.com/datatogether/identity/user.go
type User struct {
Id string `json:"id" sql:"id"`
Created int64 `json:"created" sql:"created"`
Updated int64 `json:"updated" sql:"updated"`
Username string `json:"username" sql:"username"`
Email string `json:"email" sql:"email"`
Name string `json:"name" sql:"name"`
Description string `json:"description" sql:"description"`
HomeUrl string `json:"home_url" sql:"home_url"`
CurrentKey string `json:"currentKey"`
Anonymous bool `json:"-"`
}
func requestAddUser(r *http.Request) (*http.Request, error) {
u := anonymousUser(r)
token := r.FormValue("api_token")
if token != "" {
res, err := http.Get(fmt.Sprintf("%s/users/?access_token=%s&envelope=false", cfg.IdentityServiceUrl, token))
if err != nil {
log.Infoln(err.Error())
return r, err
}
if res.StatusCode == http.StatusOK {
authUser := &User{}
if err := json.NewDecoder(res.Body).Decode(authUser); err != nil {
log.Infoln(err.Error())
return r, err
}
u = authUser
}
}
ctx := r.Context()
if u != nil {
ctx = context.WithValue(ctx, "user", u)
}
return r.WithContext(ctx), nil
}
func getIP(r *http.Request) string {
remoteAddr := r.Header.Get("x-forwarded-for")
if remoteAddr != "" {
return strings.TrimSpace(strings.Split(remoteAddr, ",")[0])
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return ""
}
return ip
}
func anonymousUser(r *http.Request) *User {
return &User{
Username: getIP(r),
Anonymous: true,
}
}